source: orange/Orange/OrangeWidgets/Data/OWEditDomain.py @ 11430:f9e572f80f4e

Revision 11430:f9e572f80f4e, 20.8 KB checked in by Ales Erjavec <ales.erjavec@…>, 13 months ago (diff)

Edit Domain widget code style fix.

Empty and trailing line whitespace.

Line 
1"""
2<name>Edit Domain</name>
3<description>Edit domain variables</description>
4<icon>icons/EditDomain.svg</icon>
5<contact>Ales Erjavec (ales.erjavec(@ at @)fri.uni-lj.si)</contact>
6<priority>3125</priority>
7<keywords>change,name,variable,domain</keywords>
8"""
9
10from OWWidget import *
11from OWItemModels import VariableListModel, PyListModel
12
13import OWGUI
14
15import Orange
16
17
18def is_discrete(var):
19    return isinstance(var, Orange.feature.Discrete)
20
21
22def is_continuous(var):
23    return isinstance(var, Orange.feature.Continuous)
24
25
26def get_qualified(module, name):
27    """Return a qualified module member ``name`` inside the named
28    ``module``.
29
30    The module (or package) first gets imported and the name
31    is retrieved from the module's global namespace.
32
33    """
34    # see __import__.__doc__ for why 'fromlist' is used
35    module = __import__(module, fromlist=[name])
36    return getattr(module, name)
37
38
39def variable_description(var):
40    """Return a variable descriptor.
41
42    A descriptor is a hashable tuple which should uniquely define
43    the variable i.e. (module, type_name, variable_name,
44    any_kwargs, sorted-attributes-items).
45
46    """
47    var_type = type(var)
48    if is_discrete(var):
49        return (var_type.__module__,
50                var_type.__name__,
51                var.name,
52                (("values", tuple(var.values)),),
53                tuple(sorted(var.attributes.items())))
54    else:
55        return (var_type.__module__,
56                var_type.__name__,
57                var.name,
58                (),
59                tuple(sorted(var.attributes.items())))
60
61
62def variable_from_description(description):
63    """Construct a variable from its description (see
64    :func:`variable_description`).
65
66    """
67    module, type_name, name, kwargs, attrs = description
68    try:
69        type = get_qualified(module, type_name)
70    except (ImportError, AttributeError), ex:
71        raise ValueError("Invalid descriptor type '{}.{}"
72                         "".format(module, type_name))
73
74    var = type(name, **dict(list(kwargs)))
75    var.attributes.update(attrs)
76    return var
77
78from PyQt4 import QtCore, QtGui
79
80QtCore.Slot = QtCore.pyqtSlot
81QtCore.Signal = QtCore.pyqtSignal
82
83
84class PyStandardItem(QStandardItem):
85    def __lt__(self, other):
86        return id(self) < id(other)
87
88
89class DictItemsModel(QStandardItemModel):
90    """A Qt Item Model class displaying the contents of a python
91    dictionary.
92
93    """
94    # Implement a proper model with in-place editing.
95    # (Maybe it should be a TableModel with 2 columns)
96    def __init__(self, parent=None, dict={}):
97        QStandardItemModel.__init__(self, parent)
98        self.setHorizontalHeaderLabels(["Key", "Value"])
99        self.set_dict(dict)
100
101    def set_dict(self, dict):
102        self._dict = dict
103        self.clear()
104        self.setHorizontalHeaderLabels(["Key", "Value"])
105        for key, value in sorted(dict.items()):
106            key_item = PyStandardItem(QString(key))
107            value_item = PyStandardItem(QString(value))
108            key_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
109            value_item.setFlags(value_item.flags() | Qt.ItemIsEditable)
110            self.appendRow([key_item, value_item])
111
112    def get_dict(self):
113        dict = {}
114        for row in range(self.rowCount()):
115            key_item = self.item(row, 0)
116            value_item = self.item(row, 1)
117            dict[str(key_item.text())] = str(value_item.text())
118        return dict
119
120
121class VariableEditor(QWidget):
122    """An editor widget for a variable.
123
124    Can edit the variable name, and its attributes dictionary.
125
126    """
127    def __init__(self, parent=None):
128        QWidget.__init__(self, parent)
129        self.setup_gui()
130
131    def setup_gui(self):
132        layout = QVBoxLayout()
133        self.setLayout(layout)
134
135        self.main_form = QFormLayout()
136        self.main_form.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
137        layout.addLayout(self.main_form)
138
139        self._setup_gui_name()
140        self._setup_gui_labels()
141
142    def _setup_gui_name(self):
143        self.name_edit = QLineEdit()
144        self.main_form.addRow("Name", self.name_edit)
145        self.name_edit.editingFinished.connect(self.on_name_changed)
146
147    def _setup_gui_labels(self):
148        vlayout = QVBoxLayout()
149        vlayout.setContentsMargins(0, 0, 0, 0)
150        vlayout.setSpacing(1)
151
152        self.labels_edit = QTreeView()
153        self.labels_edit.setEditTriggers(QTreeView.CurrentChanged)
154        self.labels_edit.setRootIsDecorated(False)
155
156        self.labels_model = DictItemsModel()
157        self.labels_edit.setModel(self.labels_model)
158
159        self.labels_edit.selectionModel().selectionChanged.connect(\
160                                    self.on_label_selection_changed)
161
162        # Necessary signals to know when the labels change
163        self.labels_model.dataChanged.connect(self.on_labels_changed)
164        self.labels_model.rowsInserted.connect(self.on_labels_changed)
165        self.labels_model.rowsRemoved.connect(self.on_labels_changed)
166
167        vlayout.addWidget(self.labels_edit)
168        hlayout = QHBoxLayout()
169        hlayout.setContentsMargins(0, 0, 0, 0)
170        hlayout.setSpacing(1)
171        self.add_label_action = QAction("+", self,
172                        toolTip="Add a new label.",
173                        triggered=self.on_add_label,
174                        enabled=False,
175                        shortcut=QKeySequence(QKeySequence.New))
176
177        self.remove_label_action = QAction("-", self,
178                        toolTip="Remove selected label.",
179                        triggered=self.on_remove_label,
180                        enabled=False,
181                        shortcut=QKeySequence(QKeySequence.Delete))
182
183        button_size = OWGUI.toolButtonSizeHint()
184        button_size = QSize(button_size, button_size)
185
186        button = QToolButton(self)
187        button.setFixedSize(button_size)
188        button.setDefaultAction(self.add_label_action)
189        hlayout.addWidget(button)
190
191        button = QToolButton(self)
192        button.setFixedSize(button_size)
193        button.setDefaultAction(self.remove_label_action)
194        hlayout.addWidget(button)
195        hlayout.addStretch(10)
196        vlayout.addLayout(hlayout)
197
198        self.main_form.addRow("Labels", vlayout)
199
200    def set_data(self, var):
201        """Set the variable to edit.
202        """
203        self.clear()
204        self.var = var
205
206        if var is not None:
207            self.name_edit.setText(var.name)
208            self.labels_model.set_dict(dict(var.attributes))
209            self.add_label_action.setEnabled(True)
210        else:
211            self.add_label_action.setEnabled(False)
212            self.remove_label_action.setEnabled(False)
213
214    def get_data(self):
215        """Retrieve the modified variable.
216        """
217        name = str(self.name_edit.text())
218        labels = self.labels_model.get_dict()
219
220        # Is the variable actually changed.
221        if not self.is_same():
222            var = type(self.var)(name)
223            var.attributes.update(labels)
224            self.var = var
225        else:
226            var = self.var
227
228        return var
229
230    def is_same(self):
231        """Is the current model state the same as the input.
232        """
233        name = str(self.name_edit.text())
234        labels = self.labels_model.get_dict()
235
236        return self.var and name == self.var.name and labels == self.var.attributes
237
238    def clear(self):
239        """Clear the editor state.
240        """
241        self.var = None
242        self.name_edit.setText("")
243        self.labels_model.set_dict({})
244
245    def maybe_commit(self):
246        if not self.is_same():
247            self.commit()
248
249    def commit(self):
250        """Emit a ``variable_changed()`` signal.
251        """
252        self.emit(SIGNAL("variable_changed()"))
253
254    @QtCore.Slot()
255    def on_name_changed(self):
256        self.maybe_commit()
257
258    @QtCore.Slot()
259    def on_labels_changed(self, *args):
260        self.maybe_commit()
261
262    @QtCore.Slot()
263    def on_add_label(self):
264        self.labels_model.appendRow([PyStandardItem(""), PyStandardItem("")])
265        row = self.labels_model.rowCount() - 1
266        index = self.labels_model.index(row, 0)
267        self.labels_edit.edit(index)
268
269    @QtCore.Slot()
270    def on_remove_label(self):
271        rows = self.labels_edit.selectionModel().selectedRows()
272        if rows:
273            row = rows[0]
274            self.labels_model.removeRow(row.row())
275
276    @QtCore.Slot()
277    def on_label_selection_changed(self):
278        selected = self.labels_edit.selectionModel().selectedRows()
279        self.remove_label_action.setEnabled(bool(len(selected)))
280
281
282class DiscreteVariableEditor(VariableEditor):
283    """An editor widget for editing a discrete variable.
284
285    Extends the :class:`VariableEditor` to enable editing of
286    variables values.
287
288    """
289    def setup_gui(self):
290        layout = QVBoxLayout()
291        self.setLayout(layout)
292
293        self.main_form = QFormLayout()
294        self.main_form.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
295        layout.addLayout(self.main_form)
296
297        self._setup_gui_name()
298        self._setup_gui_values()
299        self._setup_gui_labels()
300
301    def _setup_gui_values(self):
302        self.values_edit = QListView()
303        self.values_edit.setEditTriggers(QTreeView.CurrentChanged)
304        self.values_model = PyListModel(flags=Qt.ItemIsSelectable | \
305                                        Qt.ItemIsEnabled | Qt.ItemIsEditable)
306        self.values_edit.setModel(self.values_model)
307
308        self.values_model.dataChanged.connect(self.on_values_changed)
309        self.main_form.addRow("Values", self.values_edit)
310
311    def set_data(self, var):
312        """Set the variable to edit
313        """
314        VariableEditor.set_data(self, var)
315        self.values_model.wrap([])
316        if var is not None:
317            for v in var.values:
318                self.values_model.append(v)
319
320    def get_data(self):
321        """Retrieve the modified variable
322        """
323        name = str(self.name_edit.text())
324        labels = self.labels_model.get_dict()
325        values = map(str, self.values_model)
326
327        if not self.is_same():
328            var = type(self.var)(name, values=values)
329            var.attributes.update(labels)
330            self.var = var
331        else:
332            var = self.var
333
334        return var
335
336    def is_same(self):
337        """Is the current model state the same as the input.
338        """
339        values = map(str, self.values_model)
340        return VariableEditor.is_same(self) and self.var.values == values
341
342    def clear(self):
343        """Clear the model state.
344        """
345        VariableEditor.clear(self)
346        self.values_model.wrap([])
347
348    @QtCore.Slot()
349    def on_values_changed(self):
350        self.maybe_commit()
351
352
353class ContinuousVariableEditor(VariableEditor):
354    # TODO: enable editing of number_of_decimals, scientific format ...
355    pass
356
357
358class OWEditDomain(OWWidget):
359    contextHandlers = {
360        "": DomainContextHandler(
361            "",
362            ["domain_change_hints", "selected_index"]
363        )
364    }
365    settingsList = ["auto_commit"]
366
367    def __init__(self, parent=None, signalManager=None, title="Edit Domain"):
368        OWWidget.__init__(self, parent, signalManager, title)
369
370        self.inputs = [("Data", Orange.data.Table, self.set_data)]
371        self.outputs = [("Data", Orange.data.Table)]
372
373        # Settings
374
375        # Domain change hints maps from input variables description to
376        # the modified variables description as returned by
377        # `variable_description` function
378        self.domain_change_hints = {}
379        self.selected_index = 0
380        self.auto_commit = False
381        self.changed_flag = False
382
383        self.loadSettings()
384
385        #####
386        # GUI
387        #####
388
389        # The list of domain's variables.
390        box = OWGUI.widgetBox(self.controlArea, "Domain Features")
391        self.domain_view = QListView()
392        self.domain_view.setSelectionMode(QListView.SingleSelection)
393
394        self.domain_model = VariableListModel()
395
396        self.domain_view.setModel(self.domain_model)
397
398        self.connect(self.domain_view.selectionModel(),
399                     SIGNAL("selectionChanged(QItemSelection, QItemSelection)"),
400                     self.on_selection_changed)
401
402        box.layout().addWidget(self.domain_view)
403
404        # A stack for variable editor widgets.
405        box = OWGUI.widgetBox(self.mainArea, "Edit Feature")
406        self.editor_stack = QStackedWidget()
407        box.layout().addWidget(self.editor_stack)
408
409        box = OWGUI.widgetBox(self.controlArea, "Reset")
410
411        OWGUI.button(box, self, "Reset selected",
412                     callback=self.reset_selected,
413                     tooltip="Reset changes made to the selected feature"
414                     )
415
416        OWGUI.button(box, self, "Reset all",
417                     callback=self.reset_all,
418                     tooltip="Reset all changes made to the domain"
419                     )
420
421        box = OWGUI.widgetBox(self.controlArea, "Commit")
422
423        b = OWGUI.button(box, self, "&Commit",
424                         callback=self.commit,
425                         tooltip="Commit the data with the changed domain",
426                         )
427
428        cb = OWGUI.checkBox(box, self, "auto_commit",
429                            label="Commit automatically",
430                            tooltip="Commit the changed domain on any change",
431                            callback=self.commit_if)
432
433        OWGUI.setStopper(self, b, cb, "changed_flag",
434                         callback=self.commit)
435
436        self._editor_cache = {}
437
438        self.resize(600, 500)
439
440    def clear(self):
441        """Clear the widget state.
442        """
443        self.data = None
444        self.domain_model[:] = []
445        self.domain_change_hints = {}
446        self.clear_editor()
447
448    def clear_editor(self):
449        """Clear the current editor widget
450        """
451        current = self.editor_stack.currentWidget()
452        if current:
453            QObject.disconnect(current, SIGNAL("variable_changed()"),
454                               self.on_variable_changed)
455            current.set_data(None)
456
457    def set_data(self, data=None):
458        self.closeContext("")
459        self.clear()
460        self.data = data
461        if data is not None:
462            input_domain = data.domain
463            all_vars = list(input_domain.variables) + \
464                       input_domain.getmetas().values()
465
466            self.openContext("", data)
467
468            edited_vars = []
469
470            # Apply any saved transformations as listed in
471            # `domain_change_hints`
472
473            for var in all_vars:
474                desc = variable_description(var)
475                changed = self.domain_change_hints.get(desc, None)
476                if changed is not None:
477                    try:
478                        new = variable_from_description(changed)
479                    except ValueError, ex:
480#                        print ex
481                        new = None
482
483                    if new is not None:
484                        # Make sure orange's domain transformations will work.
485                        new.source_variable = var
486                        new.get_value_from = Orange.core.ClassifierFromVar(whichVar=var)
487                        var = new
488
489                edited_vars.append(var)
490
491            self.all_vars = all_vars
492            self.input_domain = input_domain
493
494            # Sets the model to display in the 'Domain Features' view
495            self.domain_model[:] = edited_vars
496
497            # Try to restore the variable selection
498            index = self.selected_index
499            if self.selected_index >= len(all_vars):
500                index = 0 if len(all_vars) else -1
501            if index >= 0:
502                self.select_variable(index)
503
504            self.changed_flag = True
505            self.commit_if()
506        else:
507            # To force send None on output
508            self.commit()
509
510    def on_selection_changed(self, *args):
511        """When selection in 'Domain Features' view changes.
512        """
513        i = self.selected_var_index()
514        if i is not None:
515            self.open_editor(i)
516            self.selected_index = i
517
518    def selected_var_index(self):
519        """Return the selected row in 'Domain Features' view or None
520        if no row is selected.
521
522        """
523        rows = self.domain_view.selectionModel().selectedRows()
524        if rows:
525            return rows[0].row()
526        else:
527            return None
528
529    def select_variable(self, index):
530        """Select the variable with ``index`` in the 'Domain Features'
531        view.
532
533        """
534        sel_model = self.domain_view.selectionModel()
535        sel_model.select(self.domain_model.index(index, 0),
536                         QItemSelectionModel.ClearAndSelect)
537
538    def open_editor(self, index):
539        """Open the editor for variable at ``index`` and move it
540        to the top if the stack.
541
542        """
543        # First remove and clear the current editor if any
544        self.clear_editor()
545
546        var = self.domain_model[index]
547
548        editor = self.editor_for_variable(var)
549        editor.set_data(var)
550        self.edited_variable_index = index
551
552        QObject.connect(editor, SIGNAL("variable_changed()"),
553                        self.on_variable_changed)
554        self.editor_stack.setCurrentWidget(editor)
555
556    def editor_for_variable(self, var):
557        """Return the editor for ``var``'s variable type.
558
559        The editors are cached and reused by type.
560
561        """
562        editor = None
563        if is_discrete(var):
564            editor = DiscreteVariableEditor
565        elif is_continuous(var):
566            editor = ContinuousVariableEditor
567        else:
568            editor = VariableEditor
569
570        if type(var) not in self._editor_cache:
571            editor = editor()
572            self._editor_cache[type(var)] = editor
573            self.editor_stack.addWidget(editor)
574
575        return self._editor_cache[type(var)]
576
577    def on_variable_changed(self):
578        """When the user edited the current variable in editor.
579        """
580        var = self.domain_model[self.edited_variable_index]
581        editor = self.editor_stack.currentWidget()
582        new_var = editor.get_data()
583
584        # Replace the variable in the 'Domain Features' view/model
585        self.domain_model[self.edited_variable_index] = new_var
586        old_var = self.all_vars[self.edited_variable_index]
587
588        # Store the transformation hint.
589        self.domain_change_hints[variable_description(old_var)] = \
590                    variable_description(new_var)
591
592        # Make orange's domain transformation work.
593        new_var.source_variable = old_var
594        new_var.get_value_from = Orange.core.ClassifierFromVar(whichVar=old_var)
595
596        self.commit_if()
597
598    def reset_all(self):
599        """Reset all variables to the input state.
600        """
601        self.domain_change_hints = {}
602        if self.data is not None:
603            # To invalidate stored hints
604            self.closeContext("")
605            self.openContext("", self.data)
606            self.domain_model[:] = self.all_vars
607            self.select_variable(self.selected_index)
608            self.commit_if()
609
610    def reset_selected(self):
611        """Reset the currently selected variable to its original
612        state.
613
614        """
615        if self.data is not None:
616            var = self.all_vars[self.selected_index]
617            desc = variable_description(var)
618            if desc in self.domain_change_hints:
619                del self.domain_change_hints[desc]
620
621            # To invalidate stored hints
622            self.closeContext("")
623            self.openContext("", self.data)
624
625            self.domain_model[self.selected_index] = var
626            self.editor_stack.currentWidget().set_data(var)
627            self.commit_if()
628
629    def commit_if(self):
630        if self.auto_commit:
631            self.commit()
632        else:
633            self.changed_flag = True
634
635    def commit(self):
636        """Commit the changed data to output.
637        """
638        new_data = None
639        if self.data is not None:
640            new_vars = list(self.domain_model)
641            variables = new_vars[: len(self.input_domain.variables)]
642            class_var = None
643            if self.input_domain.class_var:
644                class_var = variables[-1]
645                variables = variables[:-1]
646
647            new_metas = new_vars[len(self.input_domain.variables):]
648            new_domain = Orange.data.Domain(variables, class_var)
649
650            # Assumes getmetas().items() order has not changed.
651            # TODO: store metaids in set_data method
652            for (mid, _), new in zip(self.input_domain.getmetas().items(),
653                                       new_metas):
654                new_domain.addmeta(mid, new)
655
656            new_data = Orange.data.Table(new_domain, self.data)
657
658        self.send("Data", new_data)
659        self.changed_flag = False
660
661
662def main():
663    import sys
664    app = QApplication(sys.argv)
665    w = OWEditDomain()
666    data = Orange.data.Table("iris")
667#    data = Orange.data.Table("rep:GDS636.tab")
668    w.set_data(data)
669    w.show()
670    rval = app.exec_()
671    w.set_data(None)
672    w.saveSettings()
673    return rval
674
675if __name__ == "__main__":
676    import sys
677    sys.exit(main())
Note: See TracBrowser for help on using the repository browser.