Пример #1
0
    def test_observe_trait(self):
        # Given
        @observe(trait("value"), post_init=True, dispatch="ui")
        @observe("name")
        def handler(event):
            pass

        class_name = "MyClass"
        bases = (object,)
        class_dict = {"attr": "something", "my_listener": handler}

        # When
        update_traits_class_dict(class_name, bases, class_dict)

        # Then
        self.assertEqual(
            class_dict[ObserverTraits],
            {
                "my_listener": [
                    {
                        "expression": [trait("name")],
                        "post_init": False,
                        "dispatch": "same",
                        "handler_getter": getattr,
                    },
                    {
                        "expression": [trait("value")],
                        "post_init": True,
                        "dispatch": "ui",
                        "handler_getter": getattr,
                    },
                ],
            },
        )
class ClassWithPropertyMultipleObserves(PersonInfo):
    """ Dummy class to test observing multiple values.
    """

    computed_value = Property(observe=[trait("age"), trait("gender")])

    computed_value_n_calculations = Int()

    def _get_computed_value(self):
        self.computed_value_n_calculations += 1
        return len(self.gender) + self.age
Пример #3
0
    def test_nested_list_reassigned_value_compared_equally(self):
        container = ClassWithListOfListOfInstance()
        events = []
        handler = events.append
        container.observe(
            expression=(trait(
                "list_of_list_of_instances", notify=False).list_items(
                    notify=False).list_items(notify=False).trait("value")),
            handler=handler,
        )

        inner_list = [SingleValue()]
        container.list_of_list_of_instances = [inner_list]
        # sanity check
        self.assertEqual(len(events), 0)

        # assignment of a list that compares equally should be handled
        # correctly.
        # This relies on TraitList not trying to suppress notifications
        # when new values compared equally to old values.
        container.list_of_list_of_instances[0] = inner_list
        second_instance = SingleValue()
        container.list_of_list_of_instances[0].append(second_instance)
        self.assertEqual(len(events), 0)

        # when
        second_instance.value += 1

        # then
        event, = events
        self.assertEqual(event.object, second_instance)
        self.assertEqual(event.name, "value")
        self.assertEqual(event.old, 0)
        self.assertEqual(event.new, 1)
Пример #4
0
class Album(HasTraits):

    records = List(Instance(Record))

    records_default_call_count = Int()

    record_number_change_events = List()

    name_to_records = Dict(Str, Record)

    name_to_records_default_call_count = Int()

    name_to_records_clicked_events = List()

    def _records_default(self):
        self.records_default_call_count += 1
        return [Record()]

    @observe(trait("records").list_items().trait("number"))
    def handle_record_number_changed(self, event):
        self.record_number_change_events.append(event)

    def _name_to_records_default(self):
        self.name_to_records_default_call_count += 1
        return {"Record": Record()}

    @observe("name_to_records:items:clicked")
    def handle_event(self, event):
        self.name_to_records_clicked_events.append(event)
Пример #5
0
    def test_observe_instance_in_nested_list(self):

        container = ClassWithListOfListOfInstance()
        events = []
        handler = events.append
        container.observe(
            expression=(
                trait("list_of_list_of_instances", notify=False)
                .list_items(notify=False)
                .list_items(notify=False)
                .trait("value")
            ),
            handler=handler,
        )

        # sanity check
        single_value_instance = SingleValue()
        inner_list = [single_value_instance]
        container.list_of_list_of_instances.append(inner_list)
        self.assertEqual(len(events), 0)

        # when
        single_value_instance.value += 1

        # then
        event, = events
        self.assertEqual(event.object, single_value_instance)
        self.assertEqual(event.name, "value")
        self.assertEqual(event.old, 0)
        self.assertEqual(event.new, 1)
Пример #6
0
    def test_observe_instance_in_set(self):
        container = ClassWithSetOfInstance()
        events = []
        handler = events.append
        container.observe(
            handler=handler,
            expression=(
                trait("instances", notify=False)
                .set_items(notify=False)
                .trait("value")
            ),
        )

        single_value_instance = SingleValue()
        container.instances = set([single_value_instance])
        # sanity check
        self.assertEqual(len(events), 0)

        # when
        single_value_instance.value += 1

        # then
        event, = events
        self.assertEqual(event.object, single_value_instance)
        self.assertEqual(event.name, "value")
        self.assertEqual(event.old, 0)
        self.assertEqual(event.new, 1)
Пример #7
0
    def _get_items(self):
        """Gets the current list of InstanceChoiceItem items."""
        if self._items is not None:
            return self._items

        factory = self.factory
        if self._value is not None:
            values = self._value() + factory.values
        else:
            values = factory.values

        items = []
        adapter = factory.adapter
        for value in values:
            if not isinstance(value, InstanceChoiceItem):
                value = adapter(object=value)
            # rebuild_items when an item's name changes so it is reflected by
            # combobox. This change was added to fix enthought/traitsui#1641
            value.object.observe(
                self.rebuild_items,
                trait(value.name_trait, optional=True),
                dispatch="ui",
            )
            items.append(value)

        self._items = items

        return items
Пример #8
0
    def test_observe_dispatch_ui(self):
        # Test to ensure "ui" is one of the allowed value
        # Not testing the actual effect as it requires GUI event loop
        # as well as assumption on the local thread identity while running
        # the test.
        person = Person()

        person.observe(repr, trait("age"), dispatch="ui")
Пример #9
0
    def test_no_new_trait_added(self):
        # Test enthought/traits#447 can be avoided with observe
        team = Team()
        team.observe(lambda e: None, trait("leader").trait("does_not_exist"))

        with self.assertRaises(ValueError):
            team.leader = Person()

        self.assertNotIn("does_not_exist", team.leader.trait_names())
Пример #10
0
    def test_extended_trait_on_any_value(self):
        team = Team()
        team.any_value = 123

        with self.assertRaises(ValueError) as exception_cm:
            team.observe(lambda e: None,
                         trait("any_value").trait("does_not_exist"))

        self.assertEqual(str(exception_cm.exception),
                         "Trait named 'does_not_exist' not found on 123.")
class ClassWithPropertyObservesItems(ClassWithInstanceDefaultInit):
    """ Dummy class to test property observing container items"""

    discounted = Property(
        Bool(), observe=trait("list_of_infos").list_items().trait("age"))

    discounted_n_calculations = Int()

    def _get_discounted(self):
        self.discounted_n_calculations += 1
        return any(info.age > 70 for info in self.list_of_infos)
Пример #12
0
    def test_overloaded_signature_expression(self):
        # Test the overloaded signature for expression
        expressions = [
            trait("age"),
            "age",
            [trait("age")],
            ["age"],
        ]
        for expression in expressions:

            class NewPerson(Person):
                events = List()

                @observe(expression)
                def handler(self, event):
                    self.events.append(event)

            person = NewPerson()
            person.age += 1
            self.assertEqual(len(person.events), 1)
Пример #13
0
class Teacher(HasTraits):
    """ Model for testing list + post_init (enthought/traits#275) """

    students = List(Instance(Student))

    student_graduate_events = List()

    @observe(trait("students",
                   notify=True).list_items(notify=False).trait("graduate"),
             post_init=True)
    def _student_graduate(self, event):
        self.student_graduate_events.append(event)
class Person(HasTraits):

    scores = List(Int)

    @observe("scores")
    def notify_scores_change(self, event):
        print("{event.name} changed from {event.old} to {event.new}. "
              "(Event type: {event.__class__.__name__})".format(event=event))

    @observe(trait("scores", notify=False).list_items())
    def notify_scores_content_change(self, event):
        print("scores added: {event.added}. scores removed: {event.removed} "
              "(Event type: {event.__class__.__name__})".format(event=event))
Пример #15
0
    def test_items_on_a_list_not_observable_by_named_trait(self):
        # The member_names is a list of str, attempt to observe extended
        # trait on them should fail.
        team = Team()

        team.observe(
            lambda e: None,
            trait("member_names").list_items().trait("does_not_exist"))

        with self.assertRaises(ValueError) as exception_cm:
            team.member_names = ["Paul"]

        self.assertEqual(str(exception_cm.exception),
                         "Trait named 'does_not_exist' not found on 'Paul'.")
Пример #16
0
    def test_trait_is_not_list(self):

        team = Team()
        # The `list_items` should not be used here.
        # Error is not emitted now as leader is not defined so there is no
        # way to check.
        team.observe(lambda e: None, trait("leader").list_items())

        person = Person()
        with self.assertRaises(ValueError) as exception_cm:
            team.leader = person

        self.assertIn(
            "Expected a TraitList to be observed",
            str(exception_cm.exception),
        )
Пример #17
0
    def test_duplicated_items_tracked(self):
        # test for enthought/traits#237
        container = ClassWithListOfInstance()
        events = []
        handler = events.append
        container.observe(
            expression=(
                trait("list_of_instances", notify=False)
                .list_items(notify=False)
                .trait("value")
            ),
            handler=handler,
        )

        instance = SingleValue()
        # The item is repeated.
        container.list_of_instances.append(instance)
        container.list_of_instances.append(instance)
        self.assertEqual(len(events), 0)

        # when
        instance.value += 1

        # then
        self.assertEqual(len(events), 1)
        events.clear()

        # when
        container.list_of_instances.pop()
        instance.value += 1

        # then
        self.assertEqual(len(events), 1)
        events.clear()

        # when
        container.list_of_instances.pop()
        instance.value += 1

        # then
        self.assertEqual(len(events), 0)
Пример #18
0
class Person(HasTraits):
    @observe(trait("age", optional=True))
    def notify_age_change(self, event):
        print("age changed")
Пример #19
0
class TasksApplication(GUIApplication):
    """ A base class for Pyface tasks applications.
    """

    # -------------------------------------------------------------------------
    # 'TaskApplication' interface
    # -------------------------------------------------------------------------

    # Task management --------------------------------------------------------

    #: List of all running tasks
    tasks = List(Instance("pyface.tasks.task.Task"))

    #: Currently active Task if any.
    active_task = Property(
        observe=trait("active_window").trait("active_task", optional=True)
    )

    #: List of all application task factories.
    task_factories = List()

    #: The default layout for the application. If not specified, a single
    #: window will be created with the first available task factory.
    default_layout = List(
        Instance("pyface.tasks.task_window_layout.TaskWindowLayout")
    )

    #: Hook to add global schema additions to tasks/windows
    extra_actions = List(
        Instance("pyface.action.schema.schema_addition.SchemaAddition")
    )

    #: Hook to add global dock pane additions to tasks/windows
    extra_dock_pane_factories = List(Callable)

    # Window lifecycle methods -----------------------------------------------

    def create_task(self, id):
        """ Creates the Task with the specified ID.

        Parameters
        ----------
        id : str
            The id of the task factory to use.

        Returns
        -------
        The new Task, or None if there is not a suitable TaskFactory.
        """
        factory = self._get_task_factory(id)
        if factory is None:
            logger.warning("Could not find task factory {}".format(id))
            return None

        task = factory.create(id=factory.id)
        task.extra_actions.extend(self.extra_actions)
        task.extra_dock_pane_factories.extend(self.extra_dock_pane_factories)
        return task

    def create_window(self, layout=None, **kwargs):
        """ Connect task to application and open task in a new window.

        Parameters
        ----------
        layout : TaskLayout instance or None
            The pane layout for the window.
        **kwargs : dict
            Additional keyword arguments to pass to the window factory.


        Returns
        -------
        window : ITaskWindow instance or None
            The new TaskWindow.
        """
        from pyface.tasks.task_window_layout import TaskWindowLayout

        window = super().create_window(**kwargs)

        if layout is not None:
            for task_id in layout.get_tasks():
                task = self.create_task(task_id)
                if task is not None:
                    window.add_task(task)
                else:
                    msg = "Missing factory for task with ID %r"
                    logger.error(msg, task_id)
        else:
            # Create an empty layout to set default size and position only
            layout = TaskWindowLayout()

        window.set_window_layout(layout)

        return window

    def _create_windows(self):
        """ Create the initial windows to display from the default layout.
        """
        for layout in self.default_layout:
            window = self.create_window(layout)
            self.add_window(window)
            self.active_window = window

        # -------------------------------------------------------------------------
        # Private interface
        # -------------------------------------------------------------------------

    def _get_task_factory(self, id):
        """ Returns the TaskFactory with the specified ID, or None.
        """
        for factory in self.task_factories:
            if factory.id == id:
                return factory
        return None

    # Destruction utilities ---------------------------------------------------

    @observe("windows:items:closed")
    def _on_window_closed(self, event):
        """ Listener that ensures window handles are released when closed.
        """
        window = event.object
        if getattr(window, "active_task", None) in self.tasks:
            self.tasks.remove(window.active_task)
        super()._on_window_closed(event)

    # Trait initializers and property getters ---------------------------------

    def _window_factory_default(self):
        """ Default to TaskWindow.

        This will be sufficient in many cases as customized behaviour comes
        from the Task and the TaskWindow is just a shell.
        """
        from pyface.tasks.task_window import TaskWindow

        return TaskWindow

    def _default_layout_default(self):
        from pyface.tasks.task_window_layout import TaskWindowLayout

        window_layout = TaskWindowLayout()
        if self.task_factories:
            window_layout.items = [self.task_factories[0].id]
        return [window_layout]

    def _extra_actions_default(self):
        """ Extra application-wide menu items

        This adds a collection of standard Tasks application menu items and
        groups to a Task's set of menus.  Whether or not they actually appear
        depends on whether the appropriate menus are provided by the Task.

        These default additions assume that the window will hold an editor pane
        so that Ctrl-N and Ctrl-W will be bound to creating/closing new editors
        rather than new task windows.
        """
        from pyface.action.api import (
            AboutAction,
            CloseActiveWindowAction,
            ExitAction,
        )
        from pyface.action.schema.api import SMenu, SchemaAddition
        from pyface.tasks.action.api import (
            CreateTaskWindowAction,
            TaskWindowToggleGroup,
        )

        return [
            SchemaAddition(
                factory=CreateTaskWindowAction.factory(
                    application=self, accelerator="Ctrl+Shift+N"
                ),
                path="MenuBar/File/new_group",
            ),
            SchemaAddition(
                id="close_action",
                factory=CloseActiveWindowAction.factory(
                    application=self, accelerator="Ctrl+Shift+W"
                ),
                path="MenuBar/File/close_group",
            ),
            SchemaAddition(
                id="exit_action",
                factory=ExitAction.factory(application=self),
                path="MenuBar/File/close_group",
                absolute_position="last",
            ),
            SchemaAddition(
                # id='Window',
                factory=lambda: SMenu(
                    TaskWindowToggleGroup(application=self),
                    id="Window",
                    name="&Window",
                ),
                path="MenuBar",
                after="View",
                before="Help",
            ),
            SchemaAddition(
                id="about_action",
                factory=AboutAction.factory(application=self),
                path="MenuBar/Help",
                absolute_position="first",
            ),
        ]

    @cached_property
    def _get_active_task(self):
        if self.active_window is not None:
            return getattr(self.active_window, "active_task", None)
        else:
            return None
Пример #20
0
class Mayavi3DScene(Editor):  # pylint: disable=too-many-instance-attributes
    """
    A Pyface Tasks Editor for holding a Mayavi scene
    """
    #: The model object to view. If not specified, the editor is used instead.
    model = Instance(HasTraits)

    #: The UI object associated with the Traits view, if it has been
    #: constructed.
    ui = Instance("traitsui.ui.UI")

    #: The editor's user-visible name.
    name = Str('3D View')

    #: Configuration parser.
    configuration = Instance(ConfigParser)

    #: Current participant ID.
    participant_id = Str()

    #: The :py:class:`EMFields` instance containing the field data.
    fields_model = Instance(EMFields)

    #: Normal vector of the cut plane
    normal = Array()

    #: Origin point of the cut plane
    origin = Array()

    #: The :py:class:`mayavi.core.ui.api.MlabSceneModel` instance
    #: containing the 3D plot.
    scene = Instance(MlabSceneModel, ())

    #: The mayavi pipeline object containing the cut plane.
    data_set_clipper = Instance(DataSetClipper)

    #: The list of points describing the line for the line figure.
    points = List(ArrayClass,
                  value=[
                      ArrayClass(value=np.array([0, 0, -1])),
                      ArrayClass(value=np.array([0, 0, 1]))
                  ])

    #: The 3D surface object for the line.
    line = Instance(Surface)

    #: The field data source.
    src = Instance(ArraySource)

    #: The field cut plane.
    cut = Instance(CutPlane)

    #: The 3D surface for the field data.
    surf = Instance(Surface)

    #: The path to the spinal cord model file.
    csf_model = File()

    #: The mayavi file reader object to read the spinal cord model file.
    csf_model_reader = Any()

    #: The 3D surface object for the cut spinal cord model.
    csf_surface = Instance(Surface)

    #: Show the full spinal cord model?
    show_full_model = Bool()

    #: The 3D surface object for the full spinal cord model.
    full_csf_surface = Instance(Surface)

    #: Use a logarithmic scale for the field data?
    log_scale = Bool()

    #: Current participant ID.
    participant_id = Str()

    def default_traits_view(self):  # pylint: disable=no-self-use
        """
        Create the default traits View object for the model

        Returns
        -------
        default_traits_view : :py:class:`traitsui.view.View`
            The default traits View object for the model
        """
        return View(
            Item('scene',
                 show_label=False,
                 editor=SceneEditor(scene_class=MayaviScene)))

    def create(self, parent):
        """
        Create and set the widget(s) for the Editor.

        Parameters
        ----------
        parent : toolkit-specific widget
            The parent widget for the Editor
        """
        self.ui = self.edit_traits(kind='subpanel', parent=parent)  # pylint: disable=invalid-name
        self.control = self.ui.control  # pylint: disable=attribute-defined-outside-init

    def destroy(self):
        """
        Destroy the Editor and clean up after
        """
        self.control = None  # pylint: disable=attribute-defined-outside-init
        if self.ui is not None:
            self.ui.dispose()
        self.ui = None

    @observe('log_scale', post_init=True)
    def toggle_log_scale(self, event):
        """
        Toggle between using a logarithmic scale and a linear scale

        Parameters
        ----------
        event : A :py:class:`traits.observation.events.TraitChangeEvent` instance
            The trait change event for log_scale
        """
        if event.new:
            self.surf.parent.scalar_lut_manager.lut.scale = 'log10'
        else:
            self.surf.parent.scalar_lut_manager.lut.scale = 'linear'
        self.scene.mlab.draw()

    @observe('origin', post_init=True)
    def update_origin(self, event):
        """
        Update objects when the cut plane origin is changed.

        Parameters
        ----------
        event : A :py:class:`traits.observation.events.TraitChangeEvent` instance
            The trait change event for origin
        """
        if hasattr(self.data_set_clipper, 'widget'):
            self.data_set_clipper.widget.widget.origin = event.new
            self.cut.filters[0].widget.origin = event.new
        self.scene.mlab.draw()

    @observe('normal', post_init=True)
    def update_normal(self, event):
        """
        Update objects when the cut plane normal is changed.

        Parameters
        ----------
        event : A :py:class:`traits.observation.events.TraitChangeEvent` instance
            The trait change event for normal
        """
        if hasattr(self.data_set_clipper, 'widget'):
            self.data_set_clipper.widget.widget.normal = event.new
            self.cut.filters[0].widget.normal = event.new
        self.scene.mlab.draw()

    @observe('show_full_model', post_init=True)
    def toggle_full_model(self, event):
        """
        Toggle between showing the full spinal cord model and showing only below the cut plane.

        Parameters
        ----------
        event : A :py:class:`traits.observation.events.TraitChangeEvent` instance
            The trait change event for show_full_model.
        """
        self.csf_surface.visible = not event.new
        self.full_csf_surface.visible = event.new

        self.scene.mlab.draw()

    def reset_participant_defaults(self):
        self.reset_traits(traits=[
            'csf_model', 'show_full_model', 'log_scale', 'normal', 'origin'
        ])

    @observe('csf_model', post_init=True)
    def change_cord_model(self, event):
        """
        Change the spinal cord model file used for the 3D display.

        Parameters
        ----------
        event : A :py:class:`traits.observation.events.TraitChangeEvent` instance
            The trait change event for csf_model
        """
        if self.csf_model_reader is not None:
            self.csf_model_reader.initialize(event.new)

    @observe('scene.activated')
    def initialize_camera(self, event=None):  # pylint: disable=unused-argument
        """
        Set the camera for the Mayavi scene to a pre-determined perspective.

        Parameters
        ----------
        event : A :py:class:`traits.observation.events.TraitChangeEvent` instance
            The trait change event for scene.activated
        """
        if self.csf_surface is not None:
            self.scene.engine.current_object = self.csf_surface
        self.scene.mlab.view(azimuth=-35, elevation=75)

        self.scene.mlab.draw()

    def create_plot(self):
        """
        Create the 3D objects to be shown.
        """
        normal = self.normal

        max_ind = np.unravel_index(
            np.nanargmax(self.fields_model.masked_grid_data),
            self.fields_model.masked_grid_data.shape)

        self.origin = np.array([
            self.fields_model.masked_gr_x[max_ind],
            self.fields_model.masked_gr_y[max_ind],
            self.fields_model.masked_gr_z[max_ind]
        ])

        self.csf_model_reader = self.scene.engine.open(self.csf_model)
        self.csf_surface = Surface()

        self.data_set_clipper = DataSetClipper()

        self.scene.engine.add_filter(self.data_set_clipper,
                                     self.csf_model_reader)

        self.data_set_clipper.widget.widget_mode = 'ImplicitPlane'
        self.data_set_clipper.widget.widget.normal = normal
        self.data_set_clipper.widget.widget.origin = self.origin
        self.data_set_clipper.widget.widget.enabled = False
        self.data_set_clipper.widget.widget.key_press_activation = False
        self.data_set_clipper.filter.inside_out = True
        self.csf_surface.actor.property.opacity = 0.3
        self.csf_surface.actor.property.specular_color = (0.0, 0.0, 1.0)
        self.csf_surface.actor.property.specular = 1.0
        self.csf_surface.actor.actor.use_bounds = False

        self.scene.engine.add_filter(self.csf_surface, self.data_set_clipper)

        self.full_csf_surface = Surface()
        self.full_csf_surface.actor.property.opacity = 0.3
        self.full_csf_surface.actor.property.specular_color = (0.0, 0.0, 1.0)
        self.full_csf_surface.actor.property.specular = 1.0
        self.full_csf_surface.actor.actor.use_bounds = False
        self.full_csf_surface.visible = False

        self.scene.engine.add_filter(self.full_csf_surface,
                                     self.csf_model_reader)

        self.src = self.scene.mlab.pipeline.scalar_field(
            self.fields_model.masked_gr_x, self.fields_model.masked_gr_y,
            self.fields_model.masked_gr_z, self.fields_model.masked_grid_data)
        self.cut = self.scene.mlab.pipeline.cut_plane(self.src)
        self.cut.filters[0].widget.normal = normal
        self.cut.filters[0].widget.origin = self.origin
        self.cut.filters[0].widget.enabled = False
        self.surf = self.scene.mlab.pipeline.surface(self.cut, colormap='jet')
        self.surf.actor.actor.use_bounds = False
        self.surf.parent.scalar_lut_manager.lut.nan_color = np.array(
            [0, 0, 0, 0])

        self.scene.mlab.draw()

    @observe(ob.trait('points').list_items().trait(
        'value', optional=True).list_items(optional=True),
             post_init=True)
    def draw_line(self, event):
        """
        Create or update the line described by the points in :ref:`line-attributes`.

        Parameters
        ----------
        event : A :py:class:`traits.observation.events.TraitChangeEvent` instance
            The trait change event for points.
        """
        if None in event.new and len(event.old) == len(
                event.new) and None not in event.old:
            self.points = event.old
            return
        points = np.array([
            val.value if val is not None else np.array([0, 0, 0])
            for val in self.points
        ])

        x_positions = []
        y_positions = []
        z_positions = []

        for point in points:
            x_positions.append(point[0])
            y_positions.append(point[1])
            z_positions.append(point[2])

        if not hasattr(self.line, 'mlab_source'):
            self.line = self.scene.mlab.plot3d(x_positions,
                                               y_positions,
                                               z_positions,
                                               tube_radius=0.2,
                                               color=(1, 0, 0),
                                               figure=self.scene.mayavi_scene)
        else:
            self.line.mlab_source.reset(x=x_positions,
                                        y=y_positions,
                                        z=z_positions)

        self.scene.mlab.draw()

    def disable_widgets(self):
        """
        Disable widgets to be hidden and set up color properties.
        """
        if self.data_set_clipper.widget.widget.enabled:
            self.cut.filters[0].widget.enabled = False
            self.data_set_clipper.widget.widget.enabled = False
            if self.log_scale:
                self.surf.parent.scalar_lut_manager.lut.scale = 'log10'
            else:
                self.surf.parent.scalar_lut_manager.lut.scale = 'linear'
            self.surf.parent.scalar_lut_manager.show_legend = True
            self.surf.parent.scalar_lut_manager.use_default_name = False
            self.surf.parent.scalar_lut_manager.data_name = 'J (A/m^2)'
            self.surf.parent.scalar_lut_manager.shadow = True
            self.surf.parent.scalar_lut_manager.use_default_range = False
            self.surf.parent.scalar_lut_manager.data_range = np.array([
                np.nanmin(self.fields_model.masked_grid_data),
                np.nanmax(self.fields_model.masked_grid_data)
            ])
            self.surf.parent.scalar_lut_manager.lut.nan_color = np.array(
                [0, 0, 0, 0])

    def _csf_model_default(self):
        try:
            model = self._get_default_value('csf_model')
        except KeyError:
            model = os.path.join(os.getcwd(), 'CSF.vtk')
        return model

    def _show_full_model_default(self):
        full_model = self.configuration.BOOLEAN_STATES[self._get_default_value(
            'full_model').lower()]
        return full_model

    def _log_scale_default(self):
        log_scale = self.configuration.BOOLEAN_STATES[self._get_default_value(
            'log_scale').lower()]
        return log_scale

    def _normal_default(self):
        normal = self._get_default_value('normal')
        return np.fromstring(normal.strip('()'), sep=',')

    def _origin_default(self):
        origin = self._get_default_value('origin')
        return np.fromstring(origin.strip('()'), sep=',')

    def _get_default_value(self, option):
        if self.participant_id is not None:
            if self.participant_id not in self.configuration:
                self.configuration[self.participant_id] = {}
            val = self.configuration[self.participant_id][option]
        else:
            val = self.configuration[self.participant_id][option]
        return val
Пример #21
0
class RowTableDataModel(AbstractDataModel):
    """ A data model that presents a sequence of objects as rows.

    The data is expected to be a sequence of row objects, each object
    providing values for the columns via an AbstractDataAccessor subclass.
    Concrete implementations can be found in the data_accessors module that
    get data from attributes, indices of sequences, and keys of mappings,
    but for more complex situations, custom accessors can be defined.
    """

    #: A sequence of objects to display as rows.
    data = Instance(
        Sequence,
        comparison_mode=ComparisonMode.identity,
        allow_none=False,
    )

    #: An object which describes how to map data for the row headers.
    row_header_data = Instance(AbstractDataAccessor, allow_none=False)

    #: An object which describes how to map data for each column.
    column_data = List(
        Instance(AbstractDataAccessor, allow_none=False),
        comparison_mode=ComparisonMode.identity,
    )

    #: The index manager that helps convert toolkit indices to data view
    #: indices.
    index_manager = Instance(IntIndexManager, args=(), allow_none=False)

    # Data structure methods

    def get_column_count(self):
        """ How many columns in the data view model.

        Returns
        -------
        column_count : non-negative int
            The number of columns that the data view provides.
        """
        return len(self.column_data)

    def can_have_children(self, row):
        """ Whether or not a row can have child rows.

        Only the root has children.

        Parameters
        ----------
        row : sequence of int
            The indices of the row as a sequence from root to leaf.

        Returns
        -------
        can_have_children : bool
            Whether or not the row can ever have child rows.
        """
        return len(row) == 0

    def get_row_count(self, row):
        """ How many child rows the row currently has.

        Parameters
        ----------
        row : sequence of int
            The indices of the row as a sequence from root to leaf.

        Returns
        -------
        row_count : non-negative int
            The number of child rows that the row has.
        """
        if len(row) == 0:
            return len(self.data)
        else:
            return 0

    # Data value methods

    def get_value(self, row, column):
        """ Return the Python value for the row and column.

        This uses the row_header_data and column_data accessors to extract
        values for the row and column.

        Parameters
        ----------
        row : sequence of int
            The indices of the row as a sequence from root to leaf.
        column : sequence of int
            The indices of the column as a sequence of length 0 or 1.

        Returns
        -------
        value : any
            The value represented by the given row and column.
        """
        if len(column) == 0:
            column_data = self.row_header_data
        else:
            column_data = self.column_data[column[0]]
        if len(row) == 0:
            return column_data.title
        obj = self.data[row[0]]
        return column_data.get_value(obj)

    def can_set_value(self, row, column):
        """ Whether the value in the indicated row and column can be set.

        This uses the row_header_data and column_data accessors to determine
        if the value may be changed.

        Parameters
        ----------
        row : sequence of int
            The indices of the row as a sequence from root to leaf.
        column : sequence of int
            The indices of the column as a sequence of length 0 or 1.

        Returns
        -------
        can_set_value : bool
            Whether or not the value can be set.
        """
        if len(row) == 0:
            return False
        if len(column) == 0:
            column_data = self.row_header_data
        else:
            column_data = self.column_data[column[0]]
        obj = self.data[row[0]]
        return column_data.can_set_value(obj)

    def set_value(self, row, column, value):
        """ Set the Python value for the row and column.

        This uses the row_header_data and column_data accessors to set
        the value.

        Parameters
        ----------
        row : sequence of int
            The indices of the row as a sequence from root to leaf.
        column : sequence of int
            The indices of the column as a sequence of length 0 or 1.
        value : any
            The new value for the given row and column.

        Raises
        -------
        DataViewSetError
            If the value cannot be set.
        """
        if len(row) == 0:
            raise DataViewSetError("Can't set column titles.")
        if len(column) == 0:
            column_data = self.row_header_data
        else:
            column_data = self.column_data[column[0]]
        obj = self.data[row[0]]
        column_data.set_value(obj, value)
        self.values_changed = (row, column, row, column)

    def get_value_type(self, row, column):
        """ Return the value type of the given row and column.

        This uses the row_header_data and column_data accessors to get
        the value type.

        Parameters
        ----------
        row : sequence of int
            The indices of the row as a sequence from root to leaf.
        column : sequence of int
            The indices of the column as a sequence of length 0 or 1.

        Returns
        -------
        value_type : AbstractValueType or None
            The value type of the given row and column, or None if no value
            should be displayed.
        """
        if len(column) == 0:
            column_data = self.row_header_data
        else:
            column_data = self.column_data[column[0]]
        if len(row) == 0:
            return column_data.title_type
        return column_data.value_type

    # data update methods

    @observe("data")
    def _update_data(self, event):
        self.structure_changed = True

    @observe(trait("data", notify=False).list_items(optional=True))
    def _update_data_items(self, event):
        if len(event.added) != len(event.removed):
            # number of rows has changed
            self.structure_changed = True
        else:
            if isinstance(event.index, int):
                start = event.index
                stop = min(event.index + len(event.added), len(self.data)) - 1
            else:
                start = event.index.start
                stop = min(event.index.stop, len(self.data)) - 1
            self.values_changed = ((start, ), (), (stop, ), ())

    @observe('row_header_data')
    def _update_row_header_data(self, event):
        self.values_changed = ((), (), (), ())

    @observe('row_header_data:updated')
    def _update_row_header_data_event(self, event):
        if event.new[1] == 'value':
            if len(self.data) > 0:
                self.values_changed = ((0, ), (), (len(self.data) - 1, ), ())
        else:
            self.values_changed = ((), (), (), ())

    @observe('column_data.items')
    def _update_all_column_data_items(self, event):
        self.structure_changed = True

    @observe('column_data:items:updated')
    def _update_column_data(self, event):
        index = self.column_data.index(event.new[0])
        if event.new[1] == 'value':
            if len(self.data) > 0:
                self.values_changed = ((0, ), (index, ),
                                       (len(self.data) - 1, ), (index, ))
        else:
            self.values_changed = ((), (index, ), (), (index, ))

    # default data value

    def _data_default(self):
        return []
Пример #22
0
class SliceFigureModel(Editor):
    """
    A Pyface Tasks Editor to hold the slice figure.
    """
    #: The model object to view. If not specified, the editor is used instead.
    model = Instance(HasTraits)

    #: The UI object associated with the Traits view, if it has been
    #: constructed.
    ui = Instance("traitsui.ui.UI")

    #: The editor's user-visible name.
    name = Str("Slice Plane")

    #: Configuration parser.
    configuration = Instance(ConfigParser)

    #: Current participant ID.
    participant_id = Str()

    #: The :py:class:`EMFields` instance containing the field data.
    fields_model = Instance(EMFields)

    #: The :py:class:`Mayavi3DScene` instance containing the 3D plot.
    mayavi_scene = Instance(Mayavi3DScene)

    #: The :py:class:`matplotlib.figure.Figure` containing the slice figure.
    figure = Instance(Figure, ())

    #: Use a logarithmic scale for the field data?
    log_scale = Bool()

    #: Matplotlib colormap.
    mycmap = Any()

    #: :py:class:`matplotlib.colors.Normalize` instance for the
    #: field data.
    norm = Any()

    #: :py:class:`matplotlib.collections.QuadMesh` containing the plot data.
    pcm = Any()

    #: :py:class:`matplotlib.colorbar.Colorbar` containing the figure's
    #: colorbar.
    clb = Any()

    #: Draw the line cross marker?
    draw_cross = Bool()

    #: The list of points describing the line for the line figure.
    points = DelegatesTo('mayavi_scene')

    #: List of :py:class:`matplotlib.lines.Line2D` representing the line
    #: cross marker
    line_cross = Any()

    #: The slice figure title.
    figure_title = Str()

    #: Data label.
    data_label = Str()

    #: Use user-input labels?
    use_custom_label = Bool(False)

    def default_traits_view(self):  # pylint: disable=no-self-use
        """
        Create the default traits View object for the model

        Returns
        -------
        default_traits_view : :py:class:`traitsui.view.View`
            The default traits View object for the model
        """
        return View(
            Group(Item('figure', editor=MPLFigureEditor(),
                       show_label=False), ))

    def create(self, parent):
        """
        Create and set the widget(s) for the Editor.

        Parameters
        ----------
        parent : toolkit-specific widget
            The parent widget for the Editor
        """
        self.ui = self.edit_traits(kind='subpanel', parent=parent)  # pylint: disable=invalid-name
        self.control = self.ui.control  # pylint: disable=attribute-defined-outside-init

    def destroy(self):
        """
        Destroy the Editor and clean up after
        """
        self.control = None  # pylint: disable=attribute-defined-outside-init
        if self.ui is not None:
            self.ui.dispose()
        self.ui = None

    def export_slice(self, file_path):
        """
        Export data for slice to Excel or CSV file.

        Parameters
        ----------
        file_path : os.PathLike
            Path to output file
        """
        x_positions, y_positions, data = self._calculate_plane()

        out_df = pd.DataFrame(data=data,
                              index=y_positions,
                              columns=x_positions)

        if file_path.endswith('.xlsx'):
            out_df.to_excel(file_path)
        elif file_path.endswith('.csv') or file_path.endswith('.txt'):
            out_df.to_csv(file_path)

    @observe('log_scale', post_init=True)
    def toggle_log_scale(self, event):
        """
        Toggle between using a logarithmic scale and a linear scale

        Parameters
        ----------
        event : A :py:class:`traits.observation.events.TraitChangeEvent` instance
            The trait change event for log_scale
        """
        if event.new:
            self.norm = LogNorm(
                vmin=np.nanmin(self.fields_model.masked_grid_data),
                vmax=np.nanmax(self.fields_model.masked_grid_data))
        else:
            self.norm = Normalize(
                vmin=np.nanmin(self.fields_model.masked_grid_data),
                vmax=np.nanmax(self.fields_model.masked_grid_data))

        self.clb.update_normal(
            cm.ScalarMappable(norm=self.norm, cmap=self.mycmap))

        self.update_plot(event)

    def create_plot(self):
        """
        Create the slice figure plot.
        """
        true_x, true_y, true_data = self._calculate_plane()
        self.mycmap = copy.copy(cm.get_cmap('jet'))

        self.figure.clear()

        axes = self.figure.add_subplot(111)
        self.figure.subplots_adjust(right=0.75, bottom=0.15)

        if self.log_scale:
            self.norm = LogNorm(
                vmin=np.nanmin(self.fields_model.masked_grid_data),
                vmax=np.nanmax(self.fields_model.masked_grid_data))
        else:
            self.norm = Normalize(
                vmin=np.nanmin(self.fields_model.masked_grid_data),
                vmax=np.nanmax(self.fields_model.masked_grid_data))

        self.pcm = axes.pcolormesh(true_x,
                                   true_y,
                                   true_data,
                                   shading='nearest',
                                   cmap=self.mycmap,
                                   norm=self.norm)

        if self.draw_cross:
            self.line_cross = axes.plot([0], [0], 'rx')
        else:
            self.line_cross = axes.plot([0], [0], '')

        axes.set_ylim(
            bottom=np.nanmin(self.fields_model.masked_gr_y[0, :, 0]) - 2,
            top=np.nanmax(self.fields_model.masked_gr_y[0, :, 0]) + 2)

        axes.set_xlim(
            left=np.nanmin(self.fields_model.masked_gr_x[:, 0, 0]) - 2,
            right=np.nanmax(self.fields_model.masked_gr_x[:, 0, 0]) + 2)

        axes.set_xlabel('X (mm)')
        axes.set_ylabel('Y (mm)')

        axes.set_title(self.figure_title)

        self.clb = self.figure.colorbar(cm.ScalarMappable(norm=self.norm,
                                                          cmap=self.mycmap),
                                        ax=axes)
        self.clb.set_label(self.data_label, rotation=270, labelpad=15)

        self.figure.canvas.draw()

    @observe('fields_model.selected_field_key')
    def _set_figure_labels(self, event):
        if not self.use_custom_label:
            if self.fields_model.selected_field_key.startswith('J'):
                self.figure_title = 'Current Density Magnitude'
                self.data_label = 'Current Density ($A/m^2$)'
            elif self.fields_model.selected_field_key.startswith('EM_E'):
                self.figure_title = 'Electric Field Magnitude'
                self.data_label = 'Electric Field ($V/m$)'
            elif self.fields_model.selected_field_key.startswith('D'):
                self.figure_title = 'Displacement Flux Density Magnitude'
                self.data_label = 'Displacement Flux Density ($C/m^2$)'

            if self.line_cross is not None:
                self.update_line_cross(event=event)
            if self.pcm is not None:
                self.update_plot(event=event)

    def _calculate_plane(self):
        dataset = self.mayavi_scene.cut.outputs[0].output
        datax, datay, dataz = dataset.points.to_array().T  # pylint: disable=unused-variable
        scalar_data = dataset.point_data.scalars.to_array()

        true_x = np.unique(np.floor(
            datax / SCALE_FACTOR).astype(int)) * SCALE_FACTOR
        true_y = np.unique(np.floor(
            datay / SCALE_FACTOR).astype(int)) * SCALE_FACTOR

        true_data = np.empty((true_y.size, true_x.size))
        true_data[:] = np.nan

        for i in range(scalar_data.size):
            true_data[arg_find_nearest(true_y, datay[i]), arg_find_nearest(true_x, datax[i])] =\
                scalar_data[i]

        return true_x, true_y, true_data

    @observe('mayavi_scene:origin')
    @observe('mayavi_scene:normal')
    def update_plot(self, event):  # pylint: disable=unused-argument
        """
        Update the slice figure when the cut plane origin or normal are changed.

        Parameters
        ----------
        event : A :py:class:`traits.observation.events.TraitChangeEvent` instance
            The trait change event for the cut plane origin or normal
        """
        true_x, true_y, true_data = self._calculate_plane()

        self.update_line_cross()

        axes = self.figure.axes[0]
        self.pcm.remove()
        self.pcm = axes.pcolormesh(true_x,
                                   true_y,
                                   true_data,
                                   shading='nearest',
                                   cmap=self.mycmap,
                                   norm=self.norm)

        axes.set_title(self.figure_title)
        self.clb.set_label(self.data_label, rotation=270, labelpad=15)

        canvas = self.figure.canvas
        if canvas is not None:
            canvas.draw()

    @observe('draw_cross', post_init=True)
    @observe(
        ob.trait('points').list_items().trait(
            'value', optional=True).list_items(optional=True))
    def update_line_cross(self, event=None):  # pylint: disable=too-many-locals, unused-argument
        """
        Update the location of the line cross marker when draw_cross is changed or when the points
        are changed.

        Parameters
        ----------
        event : A :py:class:`traits.observation.events.TraitChangeEvent` instance
            The trait change event for draw_cross or points
        """
        if not self.draw_cross and self.line_cross is not None:
            self.line_cross[0].set_marker('')
        elif self.line_cross is not None:
            normal_x, normal_y, normal_z = self.mayavi_scene.normal
            origin_x, origin_y, origin_z = self.mayavi_scene.origin
            plane_z_0 = -1 * (normal_x * origin_x +
                              normal_y * origin_y) / normal_z + origin_z

            points = [
                val.value if val is not None else np.array([0, 0, 0])
                for val in self.points
            ]

            p_under = [val for val in points if val[2] <= plane_z_0]
            p_over = [val for val in points if val[2] > plane_z_0]

            if len(p_under) > 0 and len(p_over) > 0:
                point_1 = p_under[-1]
                point_2 = p_over[0]

                parametric_t = (-1 * normal_x * point_1[0]
                                - normal_y * point_1[1]
                                - normal_z * point_1[2]
                                + normal_x * origin_x
                                + normal_y * origin_y
                                + normal_z * origin_z) /\
                               (normal_x * (point_2[0] - point_1[0])
                                + normal_y * (point_2[1] - point_1[1])
                                + normal_z * (point_2[2] - point_1[2]))
                x_position = point_1[0] + parametric_t * (point_2[0] -
                                                          point_1[0])
                y_position = point_1[1] + parametric_t * (point_2[1] -
                                                          point_1[1])

                self.line_cross[0].set_data([x_position], [y_position])
                self.line_cross[0].set_marker('x')

        self.figure.canvas.draw()

    def _log_scale_default(self):
        log_scale = self.configuration.BOOLEAN_STATES[self._get_default_value(
            'log_scale').lower()]
        return log_scale

    def _draw_cross_default(self):
        line_cross = self.configuration.BOOLEAN_STATES[self._get_default_value(
            'line_cross_marker').lower()]
        return line_cross

    def _get_default_value(self, option):
        if self.participant_id is not None:
            if self.participant_id not in self.configuration:
                self.configuration[self.participant_id] = {}
            val = self.configuration[self.participant_id][option]
        else:
            val = self.configuration[self.participant_id][option]
        return val
Пример #23
0
class LineFigureModel(Editor):
    """
    A Pyface Traits Editor to hold the line figure.
    """
    #: The model object to view. If not specified, the editor is used instead.
    model = Instance(HasTraits)

    #: The UI object associated with the Traits view, if it has been
    #: constructed.
    ui = Instance("traitsui.ui.UI")

    #: The editor's user-visible name.
    name = Str("Line Plot")

    #: The :py:class:`EMFields` instance containing the field data.
    fields_model = Instance(EMFields)

    #: The :py:class:`matplotlib.figure.Figure` containing the line figure.
    figure = Instance(Figure, ())

    #: The list of points describing the line for the line figure.
    points = List(ArrayClass,
                  value=[
                      ArrayClass(value=np.array([0, 0, -1])),
                      ArrayClass(value=np.array([0, 0, 1]))
                  ])

    #: The interpolation function to sample the field data for the line
    #: figure.
    interp_func = Instance(RegularGridInterpolator)

    #: The line figure title.
    figure_title = Str()

    #: The line figure x-axis label.
    x_axis_label = Str('Distance Along Line (mm)')

    #: The line figure y-axis label.
    y_axis_label = Str()

    #: Use user-input labels?
    use_custom_label = Bool(False)

    def default_traits_view(self):  # pylint: disable=no-self-use
        """
        Create the default traits View object for the model

        Returns
        -------
        default_traits_view : :py:class:`traitsui.view.View`
            The default traits View object for the model
        """
        return View(
            Group(Item('figure', editor=MPLFigureEditor(),
                       show_label=False), ))

    def create(self, parent):
        """
        Create and set the widget(s) for the Editor.

        Parameters
        ----------
        parent : toolkit-specific widget
            The parent widget for the Editor
        """
        self.ui = self.edit_traits(kind='subpanel', parent=parent)  # pylint: disable=invalid-name
        self.control = self.ui.control

    def destroy(self):
        """
        Destroy the Editor and clean up after
        """
        self.control = None
        if self.ui is not None:
            self.ui.dispose()
        self.ui = None

    def export_line(self, file_path):
        """
        Export data for line to Excel or CSV file.

        Parameters
        ----------
        file_path : os.PathLike
            Path to output file
        """
        line_pos, line_data = self._fill_data()

        out_df = pd.DataFrame(data=line_data, index=line_pos, columns=['y'])

        if file_path.endswith('.xlsx'):
            out_df.to_excel(file_path)
        elif file_path.endswith('.csv') or file_path.endswith('.txt'):
            out_df.to_csv(file_path)

    def _calculate_between_pair(self, point_1, point_2, prev_line_pos=0):
        x_positions = np.linspace(point_1[0], point_2[0], 1000)
        y_positions = np.linspace(point_1[1], point_2[1], 1000)
        z_positions = np.linspace(point_1[2], point_2[2], 1000)

        line_pos = np.linspace(0, np.linalg.norm(point_2 - point_1),
                               1000) + prev_line_pos
        line_data = self.interp_func((x_positions, y_positions, z_positions))

        return line_pos, line_data

    def _interp_func_default(self):
        func = RegularGridInterpolator(
            (self.fields_model.x_vals, self.fields_model.y_vals,
             self.fields_model.z_vals),
            np.nan_to_num(self.fields_model.data_arr),
            bounds_error=False,
            fill_value=None)
        return func

    def _fill_data(self):
        points = [
            val.value if val is not None else np.array([0, 0, 0])
            for val in self.points
        ]

        line_pos = np.array([])
        line_data = np.array([])
        last_pos = 0
        for i, point in enumerate(points[:-1]):
            pos, data = self._calculate_between_pair(point,
                                                     points[i + 1],
                                                     prev_line_pos=last_pos)
            line_pos = np.append(line_pos, pos)
            line_data = np.append(line_data, data)
            last_pos = line_pos[-1]

        return line_pos, line_data

    @observe(ob.trait('points').list_items().trait(
        'value', optional=True).list_items(optional=True),
             post_init=True)
    def create_plot(self, event):
        """
        Create or update the line figure.

        Parameters
        ----------
        event : A :py:class:`traits.observation.events.TraitChangeEvent` instance
            The trait change event for points
        """
        line_pos, line_data = self._fill_data()

        self.figure.clear()

        axes = self.figure.add_subplot(111)
        axes.plot(line_pos, line_data)
        axes.set_ylabel(self.y_axis_label)
        axes.set_xlabel(self.x_axis_label)

        self.figure.suptitle(self.figure_title)

        self.figure.canvas.draw()

    @observe('fields_model.selected_field_key')
    def _set_figure_labels(self, event):
        if not self.use_custom_label:
            if self.fields_model.selected_field_key.startswith('J'):
                self.figure_title = 'Current Density Magnitude'
                self.y_axis_label = 'Current Density ($A/m^2$)'
            elif self.fields_model.selected_field_key.startswith('EM_E'):
                self.figure_title = 'Electric Field Magnitude'
                self.y_axis_label = 'Electric Field ($V/m$)'
            elif self.fields_model.selected_field_key.startswith('D'):
                self.figure_title = 'Displacement Flux Density Magnitude'
                self.y_axis_label = 'Displacement Flux Density ($C/m^2$)'
            self.create_plot(event)
Пример #24
0
class PersonWithObserve(Person):
    events = List()

    @observe(trait("age"))
    def handler(self, event):
        self.events.append(event)
Пример #25
0
class TableModel(GridModel):
    """Model for table data."""

    # -------------------------------------------------------------------------
    #  Trait definitions:
    # -------------------------------------------------------------------------

    #: The editor that created this model
    editor = Instance(Editor)

    #: The current filter
    filter = Instance(TableFilter, allow_none=True)

    #: Current filter summary message
    filter_summary = Str("All items")

    #: Display the table items in reverse order?
    reverse = Bool(False)

    #: Event fired when the table has been sorted
    sorted = Event()

    #: The current 'auto_add' row
    auto_add_row = Any()

    def __init__(self, **traits):
        """Initializes the object."""
        super().__init__(**traits)

        # Attach trait handlers to the list object:
        editor = self.editor
        object = editor.context_object
        name = " " + editor.extended_name

        # Set up listeners for any of the model data changing:
        object.on_trait_change(self._on_data_changed, name, dispatch="ui")
        object.on_trait_change(self.fire_content_changed,
                               name + ".-",
                               dispatch="ui")

        # Set up listeners for any column definitions changing:
        editor.on_trait_change(self.update_columns, "columns", dispatch="ui")
        editor.on_trait_change(self.update_columns,
                               "columns_items",
                               dispatch="ui")

        # Initialize the current filter from the editor's default filter:
        self.filter = editor.filter

        # If we are using 'auto_add' mode, create the first 'auto_add' row:
        if editor.auto_add:
            self.auto_add_row = row = editor.create_new_row()
            if row is not None:
                row.on_trait_change(self.on_auto_add_row, dispatch="ui")

    # -- TableModel Interface -------------------------------------------------

    def dispose(self):
        """Disposes of the model when it is no longer needed."""
        editor = self.editor
        object = editor.context_object
        name = " " + editor.extended_name

        # Remove listeners for any of the model data changing:
        object.on_trait_change(self._on_data_changed, name, remove=True)
        object.on_trait_change(self.fire_content_changed,
                               name + ".-",
                               remove=True)

        # Remove listeners for any column definitions changing:
        editor.on_trait_change(self.update_columns, "columns", remove=True)
        editor.on_trait_change(self.update_columns,
                               "columns_items",
                               remove=True)

        # Make sure we have removed listeners from the current filter also:
        if self.filter is not None:
            self.filter.on_trait_change(self._filter_modified, remove=True)

        # Clean-up any links that should be broken:
        self.editor = None

    def get_filtered_items(self):
        """Returns all model items matching the current filter."""
        return self.__filtered_items()

    def get_filtered_item(self, index=0):
        """Returns a single specified item from those items matching the
        current filter.
        """
        try:
            return self.__filtered_items()[index]
        except Exception:
            logger.exception(
                "TableModel error: Request for invalid row %d out of %d",
                index,
                len(self.__filtered_items()),
            )
            return None

    def raw_index_of(self, row):
        """Returns the raw, unfiltered index corresponding to a specified
        filtered index.
        """
        if self._filtered_cache is None:
            return row

        return self.editor.filtered_indices[row]

    def insert_filtered_item_after(self, index, item):
        """Inserts an object after a specified filtered index."""
        mapped_index = 0
        n = len(self.editor.filtered_indices)
        if index >= n:
            if (index != 0) or (n != 0):
                raise IndexError
        elif index >= 0:
            mapped_index = self.editor.filtered_indices[index] + 1
        self.__items().insert(mapped_index, item)
        sorted = self._sort_model()
        if sorted:
            mapped_index = self.__items().index(item)
        self._filtered_cache = None
        return (mapped_index, sorted)

    def delete_filtered_item_at(self, index):
        """Deletes the object at the specified filtered index."""
        if index >= len(self.editor.filtered_indices):
            raise IndexError

        mapped_index = self.editor.filtered_indices[index]
        items = self.__items()
        object = items[mapped_index]
        del items[mapped_index]
        self._filtered_cache = None
        return (mapped_index, object)

    def update_columns(self):
        """Updates the table view when columns have been changed."""
        self._columns = None
        self.fire_structure_changed()
        self.editor.refresh()

    def no_column_sort(self):
        """Resets any sorting being performed on the underlying model."""
        self._sorter = self._filtered_cache = None
        self.column_sorted = GridSortEvent(index=-1)
        # self.fire_structure_changed()

    # -- Event Handlers -------------------------------------------------------

    @observe(trait("filter").match(lambda name, ctrait: True))
    def _filter_modified(self, event):
        """Handles the contents of the filter being changed."""
        self._filtered_cache = None
        self.fire_structure_changed()
        self.editor.filter_modified()

    def _click_changed(self, event):
        """Handles the grid firing a 'click' event."""
        row, col = event

        # Fire the same event on the editor after mapping it to a model object
        # and column name:
        object = self.get_filtered_item(row)
        column = self.__get_column(col)
        self.editor.click = (object, column)

        # Check to see if the column has a view to display:
        view = column.get_view(object)
        if view is not None:
            column.get_object(object).edit_traits(view=view,
                                                  parent=self._bounds_for(
                                                      row, col))

        # Invoke the column's click handler:
        column.on_click(object)

    def _dclick_changed(self, event):
        """Handles the grid firing a 'dclick' event."""
        row, col = event

        # Fire the same event on the editor after mapping it to a model object
        # and column name:
        object = self.get_filtered_item(row)
        column = self.__get_column(col)
        self.editor.dclick = (object, column)

        # Invoke the column's double-click handler:
        column.on_dclick(object)

    def on_auto_add_row(self):
        """Handles the user modifying the current 'auto_add' mode row."""
        object = self.auto_add_row
        object.on_trait_change(self.on_auto_add_row, remove=True)

        self.auto_add_row = row = self.editor.create_new_row()
        if row is not None:
            row.on_trait_change(self.on_auto_add_row, dispatch="ui")

        do_later(self.editor.add_row, object,
                 len(self.get_filtered_items()) - 2)

    # -- GridModel Interface --------------------------------------------------

    def get_column_count(self):
        """Returns the number of columns for this table."""
        return len(self.__get_columns())

    def get_column_name(self, index):
        """Returns the label of the column specified by the (zero-based) index."""
        return self.__get_column(index).get_label()

    def get_column_size(self, index):
        """Returns the size in pixels of the column indexed by *index*.
        A value of -1 or None means to use the default.
        """
        return self.__get_column(index).get_width()

    def get_cols_drag_value(self, cols):
        """Returns the value to use when the specified columns are dragged or
        copied and pasted. The parameter *cols* is a list of column indexes.
        """
        return [self.__get_data_column(col) for col in cols]

    def get_cols_selection_value(self, cols):
        """Returns a list of TraitGridSelection objects containing the
        objects corresponding to the grid rows and the traits corresponding
        to the specified columns.
        """
        values = []
        for obj in self.__items(False):
            values.extend([
                TraitGridSelection(obj=obj, name=self.__get_column_name(col))
                for col in cols
            ])
        return values

    def sort_by_column(self, col, reverse=False):
        """Sorts the model data by the column indexed by *col*."""
        # Make sure we allow sorts by column:
        factory = self.editor.factory
        if not factory.sortable:
            return

        # Flush the object cache:
        self._filtered_cache = None

        # Cache the sorting information for later:
        self._sorter = self.__get_column(col).key
        self._reverse = reverse

        # If model sorting is requested, do it now:
        self._sort_model()

        # Indicate the we have been sorted:
        self.sorted = True

        self.column_sorted = GridSortEvent(index=col, reversed=reverse)

    def is_column_read_only(self, index):
        """Returns True if the column specified by the zero-based *index* is
        read-only.
        """
        return not self.__get_column(index).editable

    def get_row_count(self):
        """Return the number of rows for this table."""
        return len(self.__filtered_items())

    def get_row_name(self, index):
        """Return the name of the row specified by the (zero-based) *index*."""
        return "<undefined>"

    def get_rows_drag_value(self, rows):
        """Returns the value to use when the specified rows are dragged or
        copied and pasted. The parameter *rows* is a list of row indexes.
        If there is only one row listed, then return the corresponding trait
        object. If more than one row is listed, then return a list of objects.
        """
        items = self.__filtered_items()
        return [items[row] for row in rows]

    def get_rows_selection_value(self, rows):
        """Returns a list of TraitGridSelection objects containing the
        object corresponding to the selected rows.
        """
        items = self.__filtered_items()
        return [TraitGridSelection(obj=items[row]) for row in rows]

    def is_row_read_only(self, index):
        """Returns True if the row specified by the zero-based *index* is
        read-only.
        """
        return False

    def get_cell_editor(self, row, col):
        """Returns the editor for the specified cell."""

        if self.editor is None:
            return None

        column = self.__get_column(col)
        object = self.get_filtered_item(row)
        editor = column.get_editor(object)
        if editor is None:
            return None

        editor._ui = self.editor.ui

        target, name = column.target_name(object)
        return TraitGridCellAdapter(
            editor,
            target,
            name,
            "",
            context=self.editor.ui.context,
            style=column.get_style(object),
            width=column.get_edit_width(object),
            height=column.get_edit_height(object),
        )

    def get_cell_renderer(self, row, col):
        """Returns the renderer for the specified cell."""
        return self.__get_column(col).get_renderer(self.get_filtered_item(row))

    def get_cell_drag_value(self, row, col):
        """Returns the value to use when the specified cell is dragged or
        copied and pasted.
        """
        return self.__get_column(col).get_drag_value(
            self.get_filtered_item(row))

    def get_cell_selection_value(self, row, col):
        """Returns a TraitGridSelection object specifying the data stored
        in the table at (*row*, *col*).
        """
        return TraitGridSelection(obj=self.get_filtered_item(row),
                                  name=self.__get_column_name(col))

    def resolve_selection(self, selection_list):
        """Returns a list of (row, col) grid-cell coordinates that
        correspond to the objects in *selection_list*. For each coordinate,
        if the row is -1, it indicates that the entire column is selected.
        Likewise coordinates with a column of -1 indicate an entire row
        that is selected. For the TableModel, the objects in
        *selection_list* must be TraitGridSelection objects.
        """
        items = self.__filtered_items()
        cells = []
        for selection in selection_list:
            row = -1
            if selection.obj is not None:
                try:
                    row = items.index(selection.obj)
                except ValueError:
                    continue

            column = -1
            if selection.name != "":
                column = self._get_column_index_by_trait(selection.name)
                if column is None:
                    continue

            cells.append((row, column))

        return cells

    def get_cell_context_menu(self, row, col):
        """Returns a Menu object that generates the appropriate context
        menu for this cell.
        """
        column = self.__get_column(col)
        menu = column.get_menu(self.get_filtered_item(row))
        editor = self.editor

        if menu is None:
            menu = editor.factory.menu

        if menu is None:
            menu_name = editor.factory.menu_name
            if menu_name:
                menu = getattr(self.editor.object, menu_name, None)

        if menu is not None:
            editor.prepare_menu(row, column)

            return (menu, editor)

        return None

    def get_value(self, row, col):
        """Returns the value stored in the table at (*row*, *col*)."""
        object = self.get_filtered_item(row)
        if object is self.auto_add_row:
            return ""

        value = self.__get_column(col).get_value(object)
        formats = self.__get_column_formats(col)

        if (value is not None) and (formats is not None):
            format = formats.get(type(value))
            if format is not None:
                try:
                    if callable(format):
                        value = format(value)
                    else:
                        value = format % value
                except:
                    pass

        return value

    def is_valid_cell_value(self, row, col, value):
        """Tests whether *value* is valid for the cell at (*row*, *col*).
        Returns True if value is acceptable, and False otherwise."""
        return self.__get_column(col).is_droppable(self.get_filtered_item(row),
                                                   value)

    def is_cell_empty(self, row, col):
        """Returns True if the cell at (*row*, *col*) has a None value, and
        False otherwise.
        """
        return self.get_value(row, col) is None

    def is_cell_read_only(self, row, col):
        """Returns True if the cell at (*row*, *col*) is read-only, and False
        otherwise.
        """
        return not self.__get_column(col).is_editable(
            self.get_filtered_item(row))

    def get_cell_bg_color(self, row, col):
        """Returns a wxColour object specifying the background color
        of the specified cell.
        """
        return self.__get_column(col).get_cell_color(
            self.get_filtered_item(row))

    def get_cell_text_color(self, row, col):
        """Returns a wxColour object specifying the text color of the
        specified cell.
        """
        column = self.__get_column(col)
        item = self.get_filtered_item(row)
        return column.get_text_color(item)

    def get_cell_font(self, row, col):
        """Returns a wxFont object specifying the font of the specified cell."""
        return self.__get_column(col).get_text_font(
            self.get_filtered_item(row))

    def get_cell_halignment(self, row, col):
        """Returns a string specifying the horizontal alignment of the
        specified cell.

        Returns 'left' for left alignment, 'right' for right alignment,
        or 'center' for center alignment.
        """
        return self.__get_column(col).get_horizontal_alignment(
            self.get_filtered_item(row))

    def get_cell_valignment(self, row, col):
        """Returns a string specifying the vertical alignment of the
        specified cell.

        Returns 'top' for top alignment, 'bottom' for bottom alignment,
        or 'center' for center alignment.
        """
        return self.__get_column(col).get_vertical_alignment(
            self.get_filtered_item(row))

    def _insert_rows(self, pos, num_rows):
        """Inserts *num_rows* at *pos*; fires an event only if a factory
        method for new rows is defined or the model is not empty. Otherwise,
        it returns 0.
        """
        count = 0

        factory = self.editor.factory.row_factory
        if factory is None:
            items = self.__items(False)
            if len(items) > 0:
                factory = items[0].__class__

        if factory is not None:
            new_data = [
                x for x in [factory() for i in range(num_rows)]
                if x is not None
            ]
            if len(new_data) > 0:
                count = self._insert_rows_into_model(pos, new_data)
                self.rows_added = ("added", pos, new_data)

        return count

    def _delete_rows(self, pos, num_rows):
        """Removes rows *pos* through *pos* + *num_rows* from the model."""
        row_count = self.get_rows_count()
        if (pos + num_rows) > row_count:
            num_rows = row_count - pos

        return self._delete_rows_from_model(pos, num_rows)

    def _set_value(self, row, col, value):
        """Sets the value of the cell at (*row*, *col*) to *value*.

        Raises a ValueError if the value is vetoed or the cell at
        the specified position does not exist.
        """
        new_rows = 0
        column = self.__get_column(col)
        obj = None
        try:
            obj = self.get_filtered_item(row)
        except:
            # Add a new row:
            new_rows = self._insert_rows(self.get_row_count(), 1)
            if new_rows > 0:
                # Now set the value on the new object:
                try:
                    obj = self.get_filtered_item(self.get_row_count() - 1)
                except:
                    # fixme: what do we do in this case? veto the set somehow?
                    # raise an exception?
                    pass

        if obj is not None:
            self._set_data_on_row(obj, column, value)

        return new_rows

    def _move_column(self, frm, to):
        """Moves a specified **frm** column to before the specified **to**
        column. Returns **True** if successful; **False** otherwise.
        """
        to_column = None
        if to < len(self.__get_columns()):
            to_column = self.__get_column(to)

        return self.editor.move_column(self.__get_column(frm), to_column)

    def _set_data_on_row(self, row, column, value):
        """Sets the cell specified by (*row*, *col*) to *value, which
        can be either a member of the row object, or a no-argument method
        on that object.
        """
        column.set_value(row, value)

    def _insert_rows_into_model(self, pos, new_data):
        """Inserts the given new rows into the model."""
        raw_pos = self.raw_index_of(pos)
        self.__items()[raw_pos:raw_pos] = new_data

    def _delete_rows_from_model(self, pos, num_rows):
        """Deletes the specified rows from the model."""
        raw_rows = sorted(
            [self.raw_index_of(i) for i in range(pos, pos + num_rows)])
        raw_rows.reverse()
        items = self.__items()
        for row in raw_rows:
            del items[row]

        return num_rows

    def _on_data_changed(self):
        """Forces the grid to refresh when the underlying list changes."""
        # Invalidate the current cache (if any):
        self._filtered_cache = None

        self.fire_structure_changed()

    def _mouse_cell_changed(self, new):
        """Handles the user mousing over a specified cell."""
        row, col = new
        column = self.__get_column(col)
        object = self.get_filtered_item(row)

        # Update the tooltip if necessary:
        tooltip = column.get_tooltip(object)
        if tooltip != self._tooltip:
            self._tooltip = tooltip
            self.editor.grid._grid_window.SetToolTip(wx.ToolTip(tooltip))

        if column.is_auto_editable(object):
            x, y, dx, dy = self._bounds_for(row, col)
            if column.is_editable(object):
                view = View(
                    Item(
                        name=column.name,
                        editor=column.get_editor(object),
                        style=column.get_style(object),
                        show_label=False,
                        padding=-4,
                    ),
                    kind="info",
                    width=dx,
                    height=dy,
                )
            else:
                view = column.get_view(object)
                if view is None:
                    return

            column.get_object(object).edit_traits(view=view,
                                                  parent=(x, y, dx, dy))

    def _bounds_for(self, row, col):
        """Returns the coordinates and size of the specified cell in the form:
        ( x, y, dx, dy ).
        """
        grid = self.editor.grid
        coords = wxg.GridCellCoords(row, col)
        x, y, dx, dy = grid._grid.BlockToDeviceRect(coords, coords)
        x, y = grid._grid_window.ClientToScreen(x, y)

        return (x, y, dx, dy)

    def _sort_model(self):
        """Sorts the underlying model if that is what the user requested."""
        editor = self.editor
        sorted = editor.factory.sort_model and (self._sorter is not None)
        if sorted:
            items = self.__items(False)[:]
            items.sort(key=self._sorter)
            if self.reverse ^ self._reverse:
                items.reverse()
            editor.value = items
        return sorted

    def __items(self, ordered=True):
        """Returns the raw list of model objects."""
        result = self.editor.value
        if not isinstance(result, SequenceTypes):
            return [result]

        if ordered and self.reverse:
            return ReversedList(result)

        return result

    def __filtered_items(self):
        """Returns the list of all model objects that pass the current filter."""
        fc = self._filtered_cache
        if fc is None:
            items = self.__items()
            filter = self.filter
            if filter is None:
                nitems = [nitem for nitem in enumerate(items)]
                self.filter_summary = "All %s items" % len(nitems)
            else:
                if not callable(filter):
                    filter = filter.filter
                nitems = [
                    nitem for nitem in enumerate(items) if filter(nitem[1])
                ]
                self.filter_summary = "%s of %s items" % (
                    len(nitems),
                    len(items),
                )
            sorter = self._sorter
            if sorter is not None:
                nitems.sort(key=lambda x: sorter(x[1]))
                if self._reverse:
                    nitems.reverse()

            self.editor.filtered_indices = [x[0] for x in nitems]
            self._filtered_cache = fc = [x[1] for x in nitems]
            if self.auto_add_row is not None:
                self._filtered_cache.append(self.auto_add_row)

        return fc

    def __get_data_column(self, col):
        """Returns a list of model data from the column indexed by *col*."""
        column = self.__get_column(col)
        return [column.get_value(item) for item in self.__filtered_items()]

    def __get_columns(self):
        columns = self._columns
        if columns is None:
            self._columns = columns = [
                c for c in self.editor.columns if c.visible
            ]
        return columns

    def __get_column(self, col):
        try:
            return self.__get_columns()[col]
        except:
            return self.__get_columns()[0]

    def __get_column_name(self, col):
        return self.__get_column(col).name

    def __get_column_formats(self, col):
        return None  # Not used/implemented currently

    def _get_column_index_by_trait(self, name):
        for i, col in enumerate(self.__get_columns()):
            if name == col.name:
                return i