Esempio n. 1
0
 def __set_pure_state__(self, state):
     self._updating = True
     state_pickler.set_state(self,
                             state,
                             first=['actor'],
                             ignore=['_updating'])
     self._updating = False
Esempio n. 2
0
 def __set_pure_state__(self, state):
     # The reader has its own file_name which needs to be fixed.
     fname = state._file_path.abs_pth
     # Now call the parent class to setup everything.
     self.initialize(fname)
     # Setup the rest of the state.
     set_state(self, state, ignore=['_file_path'])
Esempio n. 3
0
 def __set_pure_state__(self, state):
     # Do everything but our kids.
     set_state(self, state, ignore=['children'])
     # Setup children.
     handle_children_state(self.children, state.children)
     # Now setup the children.
     set_state(self, state, first=['children'], ignore=['*'])
Esempio n. 4
0
 def __setstate__(self, str_state):
     # This method is unnecessary since this object will almost
     # never be pickled by itself and only via an object that
     # contains it, therefore __init__ will be called when the
     # scene is constructed.  However, setstate is defined just for
     # completeness.
     state_pickler.set_state(self, state_pickler.loads_state(str_state))
    def __set_pure_state__(self, state):
        """ Attempt to restore the reference to file path """
        # restore the file_path
        # possibly a bug in apptools.persistence.file_path.FilePath
        self.file_path = FilePath("")
        set_state(self.file_path, state.file_path)

        # Load the file and setup the datasets
        self.initialize(str(self.file_path))

        try:
            # restore the selected dataset
            self.dataset = state._dataset
        except TraitError as exception:
            msg = ("Could not restore references for '{dataset}' in {path}\n"
                   "Proceed with restoring the data saved anyway.\n"
                   "Got {error}: {error_msg}")
            logger.warning(msg.format(dataset=state._dataset,
                                      path=str(self.file_path),
                                      error=type(exception).__name__,
                                      error_msg=str(exception)))
            # do not overwrite _dataset and datasets while setting states
            state.pop("_dataset", None)
            state.pop("datasets", None)
            # VTKDataSource will restore the data
            super(CUDSFileSource, self).__set_pure_state__(state)
        else:
            # all is done except for the children
            # Setup the children.
            handle_children_state(self.children, state.children)
            # Set the children's state
            set_state(self, state, first=['children'], ignore=['*'])
Esempio n. 6
0
    def test_update(self):
        """Test if update method calls the handlers in order."""
        registry = version_registry.registry

        # First an elementary test.
        c = Classic()
        state = state_pickler.get_state(c)
        h = Handler()
        registry.register("Classic", __name__, h.upgrade)
        c1 = state_pickler.create_instance(state)
        state_pickler.set_state(c1, state)
        self.assertEqual(h.calls, [("upgrade", state, 0)])
        # Remove the handler.
        registry.unregister("Classic", __name__)

        # Now check to see if this works for inheritance trees.
        t = Test()
        state = state_pickler.get_state(t)
        h = Handler()
        registry.register("Classic", __name__, h.upgrade)
        registry.register("New", __name__, h.upgrade)
        registry.register("Test", __name__, h.upgrade1)
        t1 = state_pickler.create_instance(state)
        state_pickler.set_state(t1, state)
        # This should call New handler, then the Test and then
        # Classic.
        self.assertEqual(
            h.calls,
            [
                ("upgrade", state, 0),
                ("upgrade1", state, 1),
                ("upgrade", state.a, 0),
            ],
        )
Esempio n. 7
0
    def __set_pure_state__(self, state):
        # If we are already running, there is a problem since the
        # components will be started automatically in the module's
        # handle_components even though their state is not yet set call
        # so we disable it here and restart it later.
        running = self.running
        self.running = False

        # Remove the actor states since we don't want these unpickled.
        actor_st = state.pop('actor', None)
        contour_st = state.pop('contour', None)
        # Create and set the components.
        handle_children_state(self.components, state.components)
        components = self.components

        # Restore our state using set_state.
        state_pickler.set_state(self, state)

        # Now set our actor and component by finding the right one to get from
        # the state.
        if actor_st is not None:
            for cst, c in zip(state.components, components):
                actor = find_object_given_state(actor_st, cst, c)
                if actor is not None:
                    self.actor = actor
                    break
        if contour_st is not None:
            for cst, c in zip(state.components, components):
                contour = find_object_given_state(contour_st, cst, c)
                if contour is not None:
                    self.contour = contour
                    break
        # Now start all components if needed.
        self._start_components()
        self.running = running
    def test_update(self):
        """Test if update method calls the handlers in order."""
        registry = version_registry.registry

        # First an elementary test.
        c = Classic()
        state = state_pickler.get_state(c)
        h = Handler()
        registry.register('Classic', __name__, h.upgrade)
        c1 = state_pickler.create_instance(state)
        state_pickler.set_state(c1, state)
        self.assertEqual(h.calls, [('upgrade', state, 0)])
        # Remove the handler.
        registry.unregister('Classic', __name__)

        # Now check to see if this works for inheritance trees.
        t = Test()
        state = state_pickler.get_state(t)
        h = Handler()
        registry.register('Classic', __name__, h.upgrade)
        registry.register('New', __name__, h.upgrade)
        registry.register('Test', __name__, h.upgrade1)
        t1 = state_pickler.create_instance(state)
        state_pickler.set_state(t1, state)
        # This should call New handler, then the Test and then
        # Classic.
        self.assertEqual(h.calls, [('upgrade', state, 0),
                                   ('upgrade1', state, 1),
                                   ('upgrade', state.a, 0)])
Esempio n. 9
0
 def __set_pure_state__(self, state):
     # Do everything but our kids.
     set_state(self, state, ignore=['children'])
     # Setup children.
     handle_children_state(self.children, state.children)
     # Now setup the children.
     set_state(self, state, first=['children'], ignore=['*'])
    def __set_pure_state__(self, state):
        # Pop the transformation matrix for the box widget.
        mat = state.pop('matrix')
        # Now set their state.
        set_state(self, state, first=['widget_mode'], ignore=['*'])
        # Set state of rest of the attributes ignoring the widget_mode.
        set_state(self, state, ignore=['widget_mode'])

        # Set the transformation for Box widget.
        tfm = tvtk.Transform()
        tfm.set_matrix(pickle.loads(mat))
        w = self._widget_dict['Box']
        w.set_transform(tfm)

        # Some widgets need some cajoling to get their setup right.
        w = self.widget
        # Set the input.
        if len(self.inputs) > 0:
            self.configure_input(w, self.inputs[0].outputs[0])
        w.update_traits()
        mode = self.widget_mode
        if mode == 'Plane':
            wd = state._widget_dict[mode]
            w.origin = wd.origin
            w.normal = wd.normal
            w.update_placement()
        self.update_implicit_function()
        # Set the widgets trait so that the widget is rendered if needed.
        self.widgets = [w]
Esempio n. 11
0
 def __set_pure_state__(self, state):
     for prop in [
             'axes', '_property', '_title_text_property',
             '_label_text_property'
     ]:
         obj = getattr(self, prop)
         state_pickler.set_state(obj, state[prop])
Esempio n. 12
0
 def __set_pure_state__(self, state):
     # The reader has its own file_name which needs to be fixed.
     fname = state._file_path.abs_pth
     # Now call the parent class to setup everything.
     self.initialize(fname)
     # Setup the rest of the state.
     set_state(self, state, ignore=['_file_path'])
Esempio n. 13
0
    def __set_pure_state__(self, state):
        # Pop the transformation matrix for the box widget.
        mat = state.pop('matrix')
        # Now set their state.
        set_state(self, state, first=['widget_mode'], ignore=['*'])
        # Set state of rest of the attributes ignoring the widget_mode.
        set_state(self, state, ignore=['widget_mode'])

        # Set the transformation for Box widget.
        tfm = tvtk.Transform()
        tfm.set_matrix(pickle.loads(mat))
        w = self._widget_dict['Box']
        w.set_transform(tfm)

        # Some widgets need some cajoling to get their setup right.
        w = self.widget
        # Set the input.
        if len(self.inputs) > 0:
            w.input = self.inputs[0].outputs[0]
        w.update_traits()
        mode = self.widget_mode
        if mode == 'Plane':
            wd = state._widget_dict[mode]
            w.origin = wd.origin
            w.normal = wd.normal
            w.update_placement()
        self.update_implicit_function()
        # Set the widgets trait so that the widget is rendered if needed.
        self.widgets = [w]
Esempio n. 14
0
 def __setstate__(self, str_state):
     # This method is unnecessary since this object will almost
     # never be pickled by itself and only via an object that
     # contains it, therefore __init__ will be called when the
     # scene is constructed.  However, setstate is defined just for
     # completeness.
     state_pickler.set_state(self, state_pickler.loads_state(str_state))
Esempio n. 15
0
    def test_state_setter(self):
        """Test some of the features of the set_state method."""
        t = TestClassic()
        self.set_object(t)
        # Get the saved state.
        res = state_pickler.get_state(t)

        # Now create a new instance and test the setter.
        t1 = state_pickler.create_instance(res)

        keys = ['c', 'b', 'f', 'i', 'tuple', 'list', 'l', 'numeric',
                'n', 's', 'u', 'pure_list', 'inst', 'ref', 'dict']
        ignore = list(keys)
        ignore.remove('b')
        first = ['b']
        last = []
        state_pickler.set_state(t1, res, ignore=ignore, first=first, last=last)
        # Only 'b' should have been set.
        self.assertEqual(t1.b, True)
        # Rest are unchanged.
        self.assertEqual(t1.i, 7)
        self.assertEqual(t1.s, 'String')
        self.assertEqual(t1.u, u'Unicode')
        self.assertEqual(t1.inst.a, 'a')
        self.assertEqual(t1.list[0], 1)
        self.assertEqual(t1.tuple[-1].a, 'a')
        self.assertEqual(t1.dict['a'], 1)

        # Check if last works.
        last = ignore
        ignore = []
        first = []
        state_pickler.set_state(t1, res, ignore=ignore, first=first, last=last)
        # Check everything.
        self.verify_unpickled(t1, res)
Esempio n. 16
0
 def __set_pure_state__(self, state):
     self.volume_mapper_type = state['_volume_mapper_type']
     state_pickler.set_state(self, state, ignore=['ctf_state'])
     ctf_state = state['ctf_state']
     ctf, otf = load_ctfs(ctf_state, self._volume_property)
     self._ctf = ctf
     self._otf = otf
     self._update_ctf_fired()
Esempio n. 17
0
 def __set_pure_state__(self, state):
     self.volume_mapper_type = state['_volume_mapper_type']
     state_pickler.set_state(self, state, ignore=['ctf_state'])
     ctf_state = state['ctf_state']
     ctf, otf = load_ctfs(ctf_state, self._volume_property)
     self._ctf = ctf
     self._otf = otf
     self._update_ctf_fired()
Esempio n. 18
0
 def _load_saved_state(self):
     """Load the saved state (if any) of this object.
     """
     saved_state = self._saved_state
     if len(saved_state) > 0:
         state = cPickle.loads(saved_state)
         if hasattr(self, "__set_pure_state__"):
             self.__set_pure_state__(state)
         else:
             state_pickler.set_state(self, state)
         self._saved_state = ""
Esempio n. 19
0
    def __set_pure_state__(self, state):
        handle_children_state(self.children, state.children)

        # As `camera.distance` is derived from other camera parameters
        # if camera is defined, we should skip restoring "distance"
        if state.scene and state.scene.camera:
            state.scene.camera.pop("distance", None)

        # Now set our complete state.  Doing the scene last ensures
        # that the camera view is set right.
        set_state(self, state, last=['scene'])
Esempio n. 20
0
 def _load_saved_state(self):
     """Load the saved state (if any) of this object.
     """
     saved_state = self._saved_state
     if len(saved_state) > 0:
         state = pickle.loads(saved_state)
         if hasattr(self, '__set_pure_state__'):
             self.__set_pure_state__(state)
         else:
             state_pickler.set_state(self, state)
         self._saved_state = ''
Esempio n. 21
0
    def __set_pure_state__(self, state):
        handle_children_state(self.children, state.children)

        # As `camera.distance` is derived from other camera parameters
        # if camera is defined, we should skip restoring "distance"
        if state.scene and state.scene.camera:
            state.scene.camera.pop("distance", None)

        # Now set our complete state.  Doing the scene last ensures
        # that the camera view is set right.
        set_state(self, state, last=['scene'])
Esempio n. 22
0
    def test_state_setter_classic(self):
        """Test if classic classes' state can be set."""
        t = TestClassic()
        self.set_object(t)
        # Get the pickled state.
        res = state_pickler.get_state(t)

        # Now create a new instance and set its state.
        t1 = state_pickler.create_instance(res)
        state_pickler.set_state(t1, res)
        # Check each attribute.
        self.verify_unpickled(t1, res)
Esempio n. 23
0
    def test_state_setter_classic(self):
        """Test if classic classes' state can be set."""
        t = TestClassic()
        self.set_object(t)
        # Get the pickled state.
        res = state_pickler.get_state(t)

        # Now create a new instance and set its state.
        t1 = state_pickler.create_instance(res)
        state_pickler.set_state(t1, res)
        # Check each attribute.
        self.verify_unpickled(t1, res)
Esempio n. 24
0
 def test_reference_cycle(self):
     """Test if reference cycles are handled when setting the state."""
     class A: pass
     class B: pass
     a = A()
     b = B()
     a.a = b
     b.b = a
     state = state_pickler.get_state(a)
     z = A()
     z.a = B()
     z.a.b = z
     state_pickler.set_state(z, state)
Esempio n. 25
0
 def __set_pure_state__(self, state):
     # Current number of scenes.
     n_scene = len(self.scenes)
     # Number of scenes in saved state.
     n_saved_scene = len(state.scenes)
     # Remove extra ones.
     for i in range(n_scene - n_saved_scene):
         self.close_scene(self.scenes[-1])
     # Add new ones.
     for i in range(n_saved_scene - n_scene):
         self.new_scene()
     # Set the state.
     state_pickler.set_state(self, state)
Esempio n. 26
0
 def __set_pure_state__(self, state):
     # Current number of scenes.
     n_scene = len(self.scenes)
     # Number of scenes in saved state.
     n_saved_scene = len(state.scenes)
     # Remove extra ones.
     for i in range(n_scene - n_saved_scene):
         self.close_scene(self.scenes[-1])
     # Add new ones.
     for i in range(n_saved_scene - n_scene):
         self.new_scene()
     # Set the state.
     state_pickler.set_state(self, state)
    def test_state_setter(self):
        """Test some of the features of the set_state method."""
        t = TestClassic()
        self.set_object(t)
        # Get the saved state.
        res = state_pickler.get_state(t)

        # Now create a new instance and test the setter.
        t1 = state_pickler.create_instance(res)

        keys = [
            "c",
            "b",
            "f",
            "i",
            "tuple",
            "list",
            "longi",
            "numeric",
            "n",
            "s",
            "u",
            "pure_list",
            "inst",
            "ref",
            "dict",
        ]
        ignore = list(keys)
        ignore.remove("b")
        first = ["b"]
        last = []
        state_pickler.set_state(t1, res, ignore=ignore, first=first, last=last)
        # Only 'b' should have been set.
        self.assertTrue(t1.b)
        # Rest are unchanged.
        self.assertEqual(t1.i, 7)
        self.assertEqual(t1.s, "String")
        self.assertEqual(t1.u, "Unicode")
        self.assertEqual(t1.inst.a, "a")
        self.assertEqual(t1.list[0], 1)
        self.assertEqual(t1.tuple[-1].a, "a")
        self.assertEqual(t1.dict["a"], 1)

        # Check if last works.
        last = ignore
        ignore = []
        first = []
        state_pickler.set_state(t1, res, ignore=ignore, first=first, last=last)
        # Check everything.
        self.verify_unpickled(t1, res)
Esempio n. 28
0
    def __set_pure_state__(self, state):
        # Use the saved path to initialize the file_list and timestep.
        fname = state.file_path.abs_pth
        if not isfile(fname):
            msg = 'Could not find file at %s\n'%fname
            msg += 'Please move the file there and try again.'
            raise IOError(msg)

        self.initialize(fname)
        # Now set the remaining state without touching the children.
        set_state(self, state, ignore=['children', 'file_path'])
        # Setup the children.
        handle_children_state(self.children, state.children)
        # Setup the children's state.
        set_state(self, state, first=['children'], ignore=['*'])
Esempio n. 29
0
    def __set_pure_state__(self, state):
        # Use the saved path to initialize the file_list and timestep.
        fname = state.file_path.abs_pth
        if not isfile(fname):
            msg = 'Could not find file at %s\n' % fname
            msg += 'Please move the file there and try again.'
            raise IOError, msg

        self.initialize(fname)
        # Now set the remaining state without touching the children.
        set_state(self, state, ignore=['children', 'file_path'])
        # Setup the children.
        handle_children_state(self.children, state.children)
        # Setup the children's state.
        set_state(self, state, first=['children'], ignore=['*'])
Esempio n. 30
0
 def __set_pure_state__(self, state):
     z = state.data
     if z is not None:
         d = gunzip_string(z)
         r = tvtk.DataSetReader(read_from_input_string=1, input_string=d)
         warn = r.global_warning_display
         r.global_warning_display = 0
         r.update()
         r.global_warning_display = warn
         self.data = r.output
     # Now set the remaining state without touching the children.
     set_state(self, state, ignore=['children', 'data'])
     # Setup the children.
     handle_children_state(self.children, state.children)
     # Setup the children's state.
     set_state(self, state, first=['children'], ignore=['*'])
Esempio n. 31
0
 def __set_pure_state__(self, state):
     z = state.data
     if z is not None:
         d = gunzip_string(z)
         r = tvtk.DataSetReader(read_from_input_string=1,
                                input_string=d)
         warn = r.global_warning_display
         r.global_warning_display = 0
         r.update()
         r.global_warning_display = warn
         self.data = r.output
     # Now set the remaining state without touching the children.
     set_state(self, state, ignore=['children', 'data'])
     # Setup the children.
     handle_children_state(self.children, state.children)
     # Setup the children's state.
     set_state(self, state, first=['children'], ignore=['*'])
Esempio n. 32
0
    def test_reference_cycle(self):
        """Test if reference cycles are handled when setting the state."""
        class A:
            pass

        class B:
            pass

        a = A()
        b = B()
        a.a = b
        b.b = a
        state = state_pickler.get_state(a)
        z = A()
        z.a = B()
        z.a.b = z
        state_pickler.set_state(z, state)
Esempio n. 33
0
 def __set_pure_state__(self, state):
     self._unpickling = True
     # First create all the allowed widgets in the widget_list attr.
     handle_children_state(self.widget_list, state.widget_list)
     # Now set their state.
     set_state(self, state, first=['widget_list'], ignore=['*'])
     # Set the widget attr depending on value saved.
     m = [x.__class__.__name__ for x in self.widget_list]
     w_c_name = state.widget.__metadata__['class_name']
     w = self.widget = self.widget_list[m.index(w_c_name)]
     # Set the input.
     if len(self.inputs) > 0:
         self.configure_input(w, self.inputs[0].outputs[0])
     # Fix for the point widget.
     if w_c_name == 'PointWidget':
         w.place_widget()
     # Set state of rest of the attributes ignoring the widget_list.
     set_state(self, state, ignore=['widget_list'])
     # Some widgets need some cajoling to get their setup right.
     w.update_traits()
     if w_c_name == 'PlaneWidget':
         w.origin = state.widget.origin
         w.normal = state.widget.normal
         w.center = state.widget.center
         w.update_placement()
         w.get_poly_data(self.poly_data)
     elif w_c_name == 'SphereWidget':
         # XXX: This hack is necessary because the sphere widget
         # does not update its poly data even when its ivars are
         # set (plus it does not have an update_placement method
         # which is a bug).  So we force this by creating a similar
         # sphere source and copy its output.
         s = tvtk.SphereSource(center=w.center,
                               radius=w.radius,
                               theta_resolution=w.theta_resolution,
                               phi_resolution=w.phi_resolution,
                               lat_long_tessellation=True)
         s.update()
         self.poly_data.shallow_copy(s.output)
     else:
         w.get_poly_data(self.poly_data)
     self._unpickling = False
     # Set the widgets trait so that the widget is rendered if needed.
     self.widgets = [w]
Esempio n. 34
0
    def __set_pure_state__(self, state):
        handle_children_state(self.children, state.children)

        # As `camera.distance` is derived from other camera parameters
        # if camera is defined, we should skip restoring "distance"
        if state.scene and state.scene.camera:
            state.scene.camera.pop("distance", None)

        # Now set our complete state.  Doing the scene last ensures
        # that the camera view is set right.  Before doing this though,
        # if the light_manager is None, the scene hasn't been painted,
        # in that case save the light manager state and set the state later.
        # All we do is set the _saved_light_manager_state and the scene
        # will take care of the rest.
        if self.scene is not None and self.scene.light_manager is None:
            lm_state = state['scene'].pop('light_manager', None)
            self.scene._saved_light_manager_state = lm_state

        set_state(self, state, last=['scene'])
Esempio n. 35
0
    def __set_pure_state__(self, state):
        handle_children_state(self.children, state.children)

        # As `camera.distance` is derived from other camera parameters
        # if camera is defined, we should skip restoring "distance"
        if state.scene and state.scene.camera:
            state.scene.camera.pop("distance", None)

        # Now set our complete state.  Doing the scene last ensures
        # that the camera view is set right.  Before doing this though,
        # if the light_manager is None, the scene hasn't been painted,
        # in that case save the light manager state and set the state later.
        # All we do is set the _saved_light_manager_state and the scene
        # will take care of the rest.
        if self.scene is not None and self.scene.light_manager is None:
            lm_state = state['scene'].pop('light_manager', None)
            self.scene._saved_light_manager_state = lm_state

        set_state(self, state, last=['scene'])
Esempio n. 36
0
 def __set_pure_state__(self, state):
     self._unpickling = True
     # First create all the allowed widgets in the widget_list attr.
     handle_children_state(self.widget_list, state.widget_list)
     # Now set their state.
     set_state(self, state, first=['widget_list'], ignore=['*'])
     # Set the widget attr depending on value saved.
     m = [x.__class__.__name__ for x in self.widget_list]
     w_c_name = state.widget.__metadata__['class_name']
     w = self.widget = self.widget_list[m.index(w_c_name)]
     # Set the input.
     if len(self.inputs) > 0:
         self.configure_input_data(w, self.inputs[0].outputs[0])
     # Fix for the point widget.
     if w_c_name == 'PointWidget':
         w.place_widget()
     # Set state of rest of the attributes ignoring the widget_list.
     set_state(self, state, ignore=['widget_list'])
     # Some widgets need some cajoling to get their setup right.
     w.update_traits()
     if w_c_name == 'PlaneWidget':
         w.origin = state.widget.origin
         w.normal = state.widget.normal
         w.center = state.widget.center
         w.update_placement()
         w.get_poly_data(self.poly_data)
     elif w_c_name == 'SphereWidget':
         # XXX: This hack is necessary because the sphere widget
         # does not update its poly data even when its ivars are
         # set (plus it does not have an update_placement method
         # which is a bug).  So we force this by creating a similar
         # sphere source and copy its output.
         s = tvtk.SphereSource(center=w.center, radius=w.radius,
                               theta_resolution=w.theta_resolution,
                               phi_resolution=w.phi_resolution,
                               lat_long_tessellation=True)
         s.update()
         self.poly_data.shallow_copy(s.output)
     else:
         w.get_poly_data(self.poly_data)
     self._unpickling = False
     # Set the widgets trait so that the widget is rendered if needed.
     self.widgets = [w]
Esempio n. 37
0
    def test_state_setter(self):
        """Test some of the features of the set_state method."""
        t = TestClassic()
        self.set_object(t)
        # Get the saved state.
        res = state_pickler.get_state(t)

        # Now create a new instance and test the setter.
        t1 = state_pickler.create_instance(res)

        keys = [
            'c', 'b', 'f', 'i', 'tuple', 'list', 'l', 'numeric', 'n', 's', 'u',
            'pure_list', 'inst', 'ref', 'dict'
        ]
        ignore = list(keys)
        ignore.remove('b')
        first = ['b']
        last = []
        state_pickler.set_state(t1, res, ignore=ignore, first=first, last=last)
        # Only 'b' should have been set.
        self.assertEqual(t1.b, True)
        # Rest are unchanged.
        self.assertEqual(t1.i, 7)
        self.assertEqual(t1.s, 'String')
        self.assertEqual(t1.u, u'Unicode')
        self.assertEqual(t1.inst.a, 'a')
        self.assertEqual(t1.list[0], 1)
        self.assertEqual(t1.tuple[-1].a, 'a')
        self.assertEqual(t1.dict['a'], 1)

        # Check if last works.
        last = ignore
        ignore = []
        first = []
        state_pickler.set_state(t1, res, ignore=ignore, first=first, last=last)
        # Check everything.
        self.verify_unpickled(t1, res)
Esempio n. 38
0
    def __set_pure_state__(self, state):
        xyz_fn = state.xyz_file_path.abs_pth
        q_fn = state.q_file_path.abs_pth
        if not isfile(xyz_fn):
            msg = 'Could not find file at %s\n'%xyz_fn
            msg += 'Please move the file there and try again.'
            raise IOError, msg

        # Setup the reader state.
        set_state(self, state, first=['reader'], ignore=['*'])
        # Initialize the files.
        self.initialize(xyz_fn, q_fn, configure=False)
        # Now set the remaining state without touching the children.
        set_state(self, state, ignore=['children', 'xyz_file_path', 'q_file_path'])
        # Setup the children.
        handle_children_state(self.children, state.children)
        # Setup the children's state.
        set_state(self, state, first=['children'], ignore=['*'])
Esempio n. 39
0
    def __set_pure_state__(self, state):
        xyz_fn = state.xyz_file_path.abs_pth
        q_fn = state.q_file_path.abs_pth
        if not isfile(xyz_fn):
            msg = 'Could not find file at %s\n' % xyz_fn
            msg += 'Please move the file there and try again.'
            raise IOError, msg

        # Setup the reader state.
        set_state(self, state, first=['reader'], ignore=['*'])
        # Initialize the files.
        self.initialize(xyz_fn, q_fn, configure=False)
        # Now set the remaining state without touching the children.
        set_state(self,
                  state,
                  ignore=['children', 'xyz_file_path', 'q_file_path'])
        # Setup the children.
        handle_children_state(self.children, state.children)
        # Setup the children's state.
        set_state(self, state, first=['children'], ignore=['*'])
Esempio n. 40
0
 def __set_pure_state__(self, state):
     if 'glyph_dict' in state:
         # Set their state.
         set_state(self, state, first=['glyph_dict'], ignore=['*'])
         ignore = ['glyph_dict']
     else:
         # Set the dict state using the persisted list.
         gd = self.glyph_dict
         gl = self.glyph_list
         handle_children_state(gl, state.glyph_list)
         for g, gs in zip(gl, state.glyph_list):
             name = camel2enthought(g.__class__.__name__)
             if name not in gd:
                 gd[name] = g
             # Set the glyph source's state.
             set_state(g, gs)
         ignore = ['glyph_list']
     g_name = state.glyph_source.__metadata__['class_name']
     name = camel2enthought(g_name)
     # Set the correct glyph_source.
     self.glyph_source = self.glyph_dict[name]
     set_state(self, state, ignore=ignore)
Esempio n. 41
0
 def __set_pure_state__(self, state):
     if 'glyph_dict' in state:
         # Set their state.
         set_state(self, state, first=['glyph_dict'], ignore=['*'])
         ignore = ['glyph_dict']
     else:
         # Set the dict state using the persisted list.
         gd = self.glyph_dict
         gl = self.glyph_list
         handle_children_state(gl, state.glyph_list)
         for g, gs in zip(gl, state.glyph_list):
             name = camel2enthought(g.__class__.__name__)
             if name not in gd:
                 gd[name] = g
             # Set the glyph source's state.
             set_state(g, gs)
         ignore = ['glyph_list']
     g_name = state.glyph_source.__metadata__['class_name']
     name = camel2enthought(g_name)
     # Set the correct glyph_source.
     self.glyph_source = self.glyph_dict[name]
     set_state(self, state, ignore=ignore)
Esempio n. 42
0
 def __set_pure_state__(self, state):
     first = ['light_mode', 'number_of_lights']
     state_pickler.set_state(self, state, first=first, last=['lights'])
Esempio n. 43
0
 def __set_pure_state__(self, state):
     self._updating = True
     state_pickler.set_state(self, state, first=['actor'],
                             ignore=['_updating'])
     self._updating = False
Esempio n. 44
0
 def __set_pure_state__(self, state):
     handle_children_state(self.components, state.components)
     state_pickler.set_state(self, state)
     self.update_pipeline()
Esempio n. 45
0
 def __set_pure_state__(self, state):
     handle_children_state(self.children, state.children)
     # Now set our complete state.  Doing the scene last ensures
     # that the camera view is set right.
     set_state(self, state, last=['scene'])
Esempio n. 46
0
 def __set_pure_state__(self, state):
     mat = state.pop('matrix')
     super(TransformData, self).__set_pure_state__(state)
     state_pickler.set_state(self, state)
     self._transform.set_matrix(cPickle.loads(mat))
     self.widget.set_transform(self._transform)
Esempio n. 47
0
 def __set_pure_state__(self, state):
     handle_children_state(self.components, state.components)
     state_pickler.set_state(self, state)
     self.update_pipeline()
Esempio n. 48
0
 def __set_pure_state__(self, state):
     for prop in ['axes', '_property', '_title_text_property',
                  '_label_text_property']:
         obj = getattr(self, prop)
         state_pickler.set_state(obj, state[prop])
Esempio n. 49
0
 def __set_pure_state__(self, state):
     mat = state.pop('matrix')
     super(DataSetClipper, self).__set_pure_state__(state)
     state_pickler.set_state(self, state)
     self._transform.set_matrix(cPickle.loads(mat))
     self.widget.set_transform(self._transform)
Esempio n. 50
0
 def __set_pure_state__(self, state):
     handle_children_state(self.children, state.children)
     # Now set our complete state.  Doing the scene last ensures
     # that the camera view is set right.
     set_state(self, state, last=["scene"])
Esempio n. 51
0
 def __setstate__(self, str_state):
     self.__init__()
     state_pickler.set_state(self, state_pickler.loads_state(str_state))
Esempio n. 52
0
 def __set_pure_state__(self, state):
     state_pickler.set_state(self, state)
     self._position_changed(self.position)
Esempio n. 53
0
 def __set_pure_state__(self, state):
     first = ['light_mode', 'number_of_lights']
     state_pickler.set_state(self, state, first=first, last=['lights'])
Esempio n. 54
0
 def __setstate__(self, str_state):
     self.__init__()
     state_pickler.set_state(self, state_pickler.loads_state(str_state))
Esempio n. 55
0
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)