File: test_owtreegraph.py

package info (click to toggle)
orange3 3.40.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 15,908 kB
  • sloc: python: 162,745; ansic: 622; makefile: 322; sh: 93; cpp: 77
file content (346 lines) | stat: -rw-r--r-- 12,947 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# Test methods with long descriptive names can omit docstrings
# pylint: disable=missing-docstring, protected-access
from os import path
import unittest
from unittest.mock import Mock
import numpy as np

from Orange.classification import TreeLearner
from Orange.data import Table, ContinuousVariable, DiscreteVariable, Domain
from Orange.tree import DiscreteNode, MappedDiscreteNode, Node, NumericNode, \
    TreeModel
from Orange.widgets.tests.base import WidgetTest, WidgetOutputsTestMixin
from Orange.widgets.visualize.owtreeviewer import OWTreeGraph


class TestOWTreeGraph(WidgetTest, WidgetOutputsTestMixin):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        WidgetOutputsTestMixin.init(cls)

        tree = TreeLearner()
        cls.model = tree(cls.data)
        cls.model.instances = cls.data

        cls.signal_name = OWTreeGraph.Inputs.tree
        cls.signal_data = cls.model

        # Load a dataset that contains two variables with the same entropy
        data_same_entropy = Table(path.join(
            path.dirname(path.dirname(path.dirname(__file__))), "tests",
            "datasets", "same_entropy.tab"))
        cls.data_same_entropy = tree(data_same_entropy)
        cls.data_same_entropy.instances = data_same_entropy

        vara = DiscreteVariable("aaa", values=("e", "f", "g"))
        root = DiscreteNode(vara, 0, np.array([42, 8]))
        root.subset = np.arange(50)

        varb = DiscreteVariable("bbb", values=tuple("ijkl"))
        child0 = MappedDiscreteNode(varb, 1, np.array([0, 1, 0, 0]), (38, 5))
        child0.subset = np.arange(16)
        child1 = Node(None, 0, (13, 3))
        child1.subset = np.arange(16, 30)
        varc = ContinuousVariable("ccc")
        child2 = NumericNode(varc, 2, 42, (78, 12))
        child2.subset = np.arange(30, 50)
        root.children = (child0, child1, child2)

        child00 = Node(None, 0, (15, 4))
        child00.subset = np.arange(10)
        child01 = Node(None, 0, (10, 5))
        child01.subset = np.arange(10, 16)
        child0.children = (child00, child01)

        child20 = Node(None, 0, (90, 4))
        child20.subset = np.arange(30, 35)
        child21 = Node(None, 0, (70, 9))
        child21.subset = np.arange(35, 50)
        child2.children = (child20, child21)

        domain = Domain([vara, varb, varc], ContinuousVariable("y"))
        t = [[i, j, k]
             for i in range(3)
             for j in range(4)
             for k in (40, 44)]
        x = np.array((t * 3)[:50])
        data = Table.from_numpy(
            domain, x, np.arange(len(x)))
        cls.tree = TreeModel(data, root)

    def setUp(self):
        self.widget = self.create_widget(OWTreeGraph)

    def _select_data(self):
        node = self.widget.scene.nodes()[0]
        node.setSelected(True)
        return self.model.get_indices([node.node_inst])

    def test_target_class_changed(self):
        """Check if node content has changed after selecting target class"""
        w = self.widget
        self.send_signal(w.Inputs.tree, self.signal_data)
        nodes = w.scene.nodes()
        text = nodes[0].toPlainText()
        w.color_combo.activated.emit(1)
        w.color_combo.setCurrentIndex(1)
        self.assertNotEqual(nodes[0].toPlainText(), text)

    def test_tree_determinism(self):
        """Check that the tree is drawn identically upon receiving the same
        dataset with no parameter changes."""
        w = self.widget
        n_tries = 10

        def _check_all_same(data):
            """Check that all the elements within an iterable are identical."""
            iterator = iter(data)
            try:
                first = next(iterator)
            except StopIteration:
                return True
            return all(first == rest for rest in iterator)

        # Make sure the tree are deterministic for iris
        scene_nodes = []
        for _ in range(n_tries):
            self.send_signal(w.Inputs.tree, self.signal_data)
            scene_nodes.append([n.pos() for n in w.scene.nodes()])
        for node_row in zip(*scene_nodes):
            self.assertTrue(
                _check_all_same(node_row),
                "The tree was not drawn identically in the %d times it was "
                "sent to widget after receiving the iris dataset." % n_tries
            )

        # Make sure trees are deterministic with data where some variables have
        # the same entropy
        scene_nodes = []
        for _ in range(n_tries):
            self.send_signal(w.Inputs.tree, self.data_same_entropy)
            scene_nodes.append([n.pos() for n in w.scene.nodes()])
        for node_row in zip(*scene_nodes):
            self.assertTrue(
                _check_all_same(node_row),
                "The tree was not drawn identically in the %d times it was "
                "sent to widget after receiving a dataset with variables with "
                "same entropy." % n_tries
            )

    def test_update_node_info(self):
        widget = self.widget
        self.send_signal(widget.Inputs.tree, self.signal_data)

        node = Mock()

        widget.tree_adapter = Mock()
        widget.tree_adapter.attribute = lambda *_: ContinuousVariable("foo")
        widget.node_content_cls = lambda *_: "bar<br/>ban"

        widget.tree_adapter.has_children = lambda *_: True
        widget.show_intermediate = False
        widget.update_node_info(node)
        args = node.setHtml.call_args[0][0]
        self.assertIn("foo", args)
        self.assertNotIn("bar", args)

        widget.tree_adapter.has_children = lambda *_: True
        widget.show_intermediate = True
        widget.update_node_info(node)
        args = node.setHtml.call_args[0][0]
        self.assertIn("bar<br/>ban<hr/>foo", args)

        widget.tree_adapter.has_children = lambda *_: False
        widget.show_intermediate = True
        widget.update_node_info(node)
        args = node.setHtml.call_args[0][0]
        self.assertIn("bar<br/>ban<hr/>foo", args)

        widget.tree_adapter.has_children = lambda *_: False
        widget.show_intermediate = False
        widget.update_node_info(node)
        args = node.setHtml.call_args[0][0]
        self.assertIn("bar<br/>ban<hr/>foo", args)

    def test_tree_labels(self):
        w = self.widget
        w.show_intermediate = True

        self.send_signal(w.Inputs.tree, self.tree)

        txt = w.root_node.toPlainText()
        self.assertIn("42.0 ± 8.0", txt)
        self.assertIn("50 instances", txt)
        self.assertIn("aaa", txt)

        children = [edge.node2
                    for edge in w.root_node.graph_edges()]

        txt = children[0].toPlainText()
        self.assertIn("38.0 ± 5.0", txt)
        self.assertIn("16 instances", txt)
        self.assertIn("bbb", txt)

        txt = children[1].toPlainText()
        self.assertIn("13.0 ± 3.0", txt)
        self.assertIn("14 instances", txt)

        txt = children[2].toPlainText()
        self.assertIn("78.0 ± 12.0", txt)
        self.assertIn("20 instances", txt)
        self.assertIn("ccc", txt)

        w.controls.show_intermediate.click()

        txt = w.root_node.toPlainText()
        self.assertNotIn("42.0 ± 8.0", txt)
        self.assertNotIn("50 instances", txt)
        self.assertIn("aaa", txt)

        children = [edge.node2
                    for edge in w.root_node.graph_edges()]

        txt = children[0].toPlainText()
        self.assertNotIn("38.0 ± 5.0", txt)
        self.assertNotIn("16 instances", txt)
        self.assertIn("bbb", txt)

        txt = children[1].toPlainText()
        self.assertIn("13.0 ± 3.0", txt)
        self.assertIn("14 instances", txt)

        txt = children[2].toPlainText()
        self.assertNotIn("78.0 ± 12.0", txt)
        self.assertNotIn("20 instances", txt)
        self.assertIn("ccc", txt)

    def test_select_node_labels(self):
        widget = self.widget
        combo = self.widget.controls.node_labels

        def check_labels(attr):
            column = widget.dataset.get_column(attr)
            to_str = widget.domain[attr].str_val
            for node in widget.scene.nodes():
                if widget.tree_adapter.has_children(node.node_inst):
                    continue
                subset = node.node_inst.subset
                exp = ", ".join(map(to_str, column[subset[:4]]))
                if len(subset) > 4:
                    exp += ", …"
                self.assertIn(exp, node.toHtml())

        def switch_to(attr):
            idx = combo.model().indexOf(attr and widget.domain[attr])
            combo.setCurrentIndex(idx)
            combo.activated[int].emit(idx)

        zoo = Table("zoo")
        iris = Table("iris")
        zootree = TreeLearner()(zoo)
        iristree = TreeLearner()(iris)

        self.assertIsNone(widget.node_labels)

        # Default label is a string variable (with most unique values)
        self.send_signal(widget.Inputs.tree, zootree)
        self.assertIs(widget.node_labels, zootree.domain["name"])
        check_labels("name")

        # Change to another variable
        switch_to("hair")
        check_labels("hair")

        # See that losing the data for a while keeps the label
        self.send_signal(widget.Inputs.tree, None)
        self.assertIsNone(widget.node_labels)
        self.send_signal(widget.Inputs.tree, zootree)
        check_labels("hair")

        self.send_signal(widget.Inputs.tree, iristree)
        self.assertIsNone(widget.node_labels)
        switch_to("petal length")
        check_labels("petal length")
        self.send_signal(widget.Inputs.tree, None)
        self.assertIsNone(widget.node_labels)
        self.send_signal(widget.Inputs.tree, iristree)
        self.assertEqual(widget.node_labels, iristree.domain["petal length"])
        check_labels("petal length")

        instances = zootree.instances
        zootree.instances = None
        self.send_signal(widget.Inputs.tree, zootree)
        self.assertIsNone(widget.node_labels)
        self.assertEqual(list(widget.label_model), [None])

        zootree.instances = instances
        widget.node_labels_hint = ""  # Reset to no hint
        self.send_signal(widget.Inputs.tree, zootree)
        self.assertIs(widget.node_labels, zootree.domain["name"])
        check_labels("name")

    def test_select_node_many_labels(self):
        zoo = Table("zoo")
        zootree = TreeLearner()(zoo)

        self.send_signal(self.widget.Inputs.tree, zootree)

        ta = self.widget.tree_adapter
        node = next(node for node in self.widget.scene.nodes()
                    if not ta.has_children(node.node_inst))

        var = zoo.domain["name"]
        values = zoo.get_column(var)
        ta.get_instances_in_nodes = lambda *_: zoo[[0, 50]]
        self.widget.update_node_info(node)
        self.assertIn(", ".join(map(var.str_val, values[[0, 50]])),
                      node.toHtml())

        ta.get_instances_in_nodes = lambda *_: zoo[[0, 50, 75]]
        self.widget.update_node_info(node)
        self.assertIn(", ".join(map(var.str_val, values[[0, 50, 75]])),
                      node.toHtml())

        ta.get_instances_in_nodes = lambda *_: zoo[[0, 50, 75, 11]]
        self.widget.update_node_info(node)
        self.assertIn(", ".join(map(var.str_val, values[[0, 50, 75, 11]])),
                      node.toHtml())

        ta.get_instances_in_nodes = lambda *_: zoo[[0, 50, 75, 11, 3]]
        self.widget.update_node_info(node)
        self.assertIn(", ".join(map(var.str_val, values[[0, 50, 75, 11]])) + ", …",
                      node.toHtml())

        var = zoo.domain["legs"]
        values = zoo.get_column(var)
        self.widget.node_labels = var
        ta.get_instances_in_nodes = lambda *_: zoo[[0, 50, 75, 11]]
        self.widget.update_node_info(node)
        self.assertIn(", ".join(map(var.str_val, values[[0, 50, 75, 11]])),
                      node.toHtml())

        ta.get_instances_in_nodes = lambda *_: zoo[[0, 50, 75, 11, 3]]
        self.widget.update_node_info(node)
        self.assertIn(", ".join(map(var.str_val, values[[0, 50, 75, 11]])) + ", …",
                      node.toHtml())

        iris = Table("iris")
        iristree = TreeLearner()(iris)
        self.send_signal(self.widget.Inputs.tree, iristree)
        var = iris.domain["petal length"]
        values = iris.get_column(var)
        self.widget.node_labels = var
        ta = self.widget.tree_adapter
        node = next(node for node in self.widget.scene.nodes()
                    if not ta.has_children(node.node_inst))

        ta.get_instances_in_nodes = lambda *_: iris[[0, 50, 75, 11, 13,
                                                     14, 15, 16]]
        self.widget.update_node_info(node)
        self.assertIn(", ".join(map(var.str_val, values[[0, 50, 75, 11]])) + ", …",
                      node.toHtml())


if __name__ == "__main__":
    unittest.main()