Beispiel #1
0
    def test_context_eq(self):
        context1 = Context(x=12, y=["a", "list"], time=3.14)
        context2 = Context(x=12, y=["a", "list"], time=2.71)
        context3 = Context(x=13, y=["a", "list"], time=2.71)
        self.assertTrue(context1 == context2)
        self.assertFalse(context2 == context3)

        self.assertRaises(TypeError, hash, context1)
Beispiel #2
0
    def test_migration_discrete_strings(self):
        v = [DiscreteVariable("Ana", values=tuple("012")),
             ContinuousVariable("Cilka")]
        domain = Domain(v)
        data = Table.from_numpy(domain, [[1, 3.14]])

        settings_w_discrete = {
            "context_settings":
            [Context(
                attributes=dict(Ana=1, Cilka=2), metas={},
                values=dict(
                    descriptors=[
                        ContinuousDescriptor("y", "Ana + int(Cilka)", 1),
                        StringDescriptor("u", "Ana.value + 'X'")
                    ],
                    currentIndex=0)
             )]
        }
        widget = self.create_widget(OWFeatureConstructor, settings_w_discrete)
        self.send_signal(widget.Inputs.data, data)
        self.assertTrue(widget.expressions_with_values)
        self.assertFalse(widget.fix_button.isHidden())
        out = self.get_output(widget.Outputs.data)
        np.testing.assert_almost_equal(out.X, [[1, 3.14, 4]])
        np.testing.assert_equal(out.metas, [["1X"]])

        settings_no_discrete = {
            "context_settings":
            [Context(
                attributes=dict(Ana=1, Cilka=2), metas={},
                values=dict(
                    descriptors=[
                        ContinuousDescriptor("y", "int(Cilka)", 1),
                    ],
                    currentIndex=0)
             )]
        }
        widget = self.create_widget(OWFeatureConstructor, settings_no_discrete)
        self.send_signal(widget.Inputs.data, data)
        self.assertFalse(widget.expressions_with_values)
        self.assertTrue(widget.fix_button.isHidden())
        out = self.get_output(widget.Outputs.data)
        np.testing.assert_almost_equal(out.X, [[1, 3.14, 3]])

        widget = self.create_widget(OWFeatureConstructor, settings_w_discrete)
        self.send_signal(widget.Inputs.data, data)
        self.assertTrue(widget.expressions_with_values)
        self.assertFalse(widget.fix_button.isHidden())
        self.send_signal(widget.Inputs.data, None)
        self.assertFalse(widget.expressions_with_values)
        self.assertTrue(widget.fix_button.isHidden())
Beispiel #3
0
    def test_find_or_create_context(self):
        widget = SimpleWidget()
        handler = ContextHandler()
        handler.match = lambda context, i: (context.i == i) * 2
        handler.clone_context = lambda context, i: copy(context)

        c1, c2, c3, c4, c5, c6, c7, c8, c9 = (Context(i=i)
                                              for i in range(1, 10))

        # finding a perfect match in global_contexts should copy it to
        # the front of context_settings (and leave globals as-is)
        widget.context_settings = [c2, c5]
        handler.global_contexts = [c3, c7]
        context, new = handler.find_or_create_context(widget, 7)
        self.assertEqual(context.i, 7)
        self.assertEqual([c.i for c in widget.context_settings], [7, 2, 5])
        self.assertEqual([c.i for c in handler.global_contexts], [3, 7])

        # finding a perfect match in context_settings should move it to
        # the front of the list
        widget.context_settings = [c2, c5]
        handler.global_contexts = [c3, c7]
        context, new = handler.find_or_create_context(widget, 5)
        self.assertEqual(context.i, 5)
        self.assertEqual([c.i for c in widget.context_settings], [5, 2])
        self.assertEqual([c.i for c in handler.global_contexts], [3, 7])
 def test_settings_migration_to_ver21(self):
     settings = {
         'controlAreaVisible':
         True,
         'savedWidgetGeometry':
         '',
         '__version__':
         1,
         'context_settings': [
             Context(values={
                 'auto_commit': (True, -2),
                 'color_var': ('iris', 101),
                 'selected_rows': [1, 4],
                 'sorting': ((1, 0), -2),
                 '__version__': 1
             },
                     attributes={
                         'petal length': 2,
                         'petal width': 2,
                         'sepal length': 2,
                         'sepal width': 2
                     },
                     metas={'iris': 1})
         ]
     }
     widget = self.create_widget(OWFeatureStatistics,
                                 stored_settings=settings)
     self.send_signal(widget.Inputs.data, self.data1)
     domain = self.data1.domain
     self.assertEqual(widget.selected_vars,
                      [domain["petal width"], domain["iris"]])
Beispiel #5
0
    def test_report(self):
        settings = {
            "context_settings":
                [Context(
                    attributes=dict(x=2, y=2, z=2), metas={},
                    values=dict(
                        descriptors=[
                            ContinuousDescriptor("a", "x + 2", 1),
                            DiscreteDescriptor("b", "x < 3", (), False),
                            DiscreteDescriptor("c", "x > 15", (), True),
                            DiscreteDescriptor("d", "y > x", ("foo", "bar"), False),
                            DiscreteDescriptor("e", "x ** 2 + y == 5", ("foo", "bar"), True),
                            StringDescriptor("f", "str(x)"),
                            DateTimeDescriptor("g", "z")
                        ],
                        currentIndex=0)
                )]
        }

        w = self.create_widget(OWFeatureConstructor, settings)
        v = [ContinuousVariable(name) for name in "xyz"]
        domain = Domain(v, [])
        self.send_signal(w.Inputs.data, Table.from_numpy(domain, [[0, 1, 2]]))
        w.report_items = Mock()
        w.send_report()
        args = w.report_items.call_args[0][1]
        self.assertEqual(list(args), list("abcdefg"))
Beispiel #6
0
    def test_migrate_settings(self):
        # any context settings are removed
        settings = {"context_settings": []}
        self.widget.migrate_settings(settings, 1)
        self.assertEqual(len(settings), 0)

        # context settings become ordinary settings
        settings = {
            "context_settings": [
                Context(
                    values={
                        '__version__': 1,
                        'apply_pca': (True, -2),
                        'k_neighbors': (29, -2),
                        'metric_idx': (1, -2),
                        'normalize': (False, -2),
                        'pca_components': (10, -2),
                        'resolution': (1.0, -2)
                    })
            ]
        }
        self.widget.migrate_settings(settings, 1)
        correct = {
            'apply_pca': True,
            'k_neighbors': 29,
            'metric_idx': 1,
            'normalize': False,
            'pca_components': 10,
            'resolution': 1.0
        }
        self.assertEqual(sorted(settings.items()), sorted(correct.items()))
Beispiel #7
0
    def test_formats_contexts(self):
        settings = dict(key1=1, key2=2,
                        context_settings=[
                            Context(param1=1, param2=2,
                                    values=dict(value1=1,
                                                value2=2)),
                            Context(param1=3, param2=4,
                                    values=dict(value1=5,
                                                value2=6))
                        ])
        pp = SettingsPrinter()

        output = pp.pformat(settings)
        # parameter of all contexts should be visible in the output
        self.assertIn("param1=1", output)
        self.assertIn("param2=2", output)
        self.assertIn("param1=3", output)
        self.assertIn("param2=4", output)
Beispiel #8
0
    def test_rename_settings(self):
        some_settings = dict(foo=42, bar=13)
        rename_setting(some_settings, "foo", "baz")
        self.assertDictEqual(some_settings, dict(baz=42, bar=13))

        self.assertRaises(KeyError, rename_setting, some_settings, "qux", "quux")

        context = Context(values=dict(foo=42, bar=13))
        rename_setting(context, "foo", "baz")
        self.assertDictEqual(context.values, dict(baz=42, bar=13))
    def test_migration(self):
        enc_domain = dict(
            attributes=(('foo', 1), ('bar', 1), ('baz', 1), ('bax', 1),
                        ('cfoo', 1), ('mbaz', 1)))

        # No annotation
        context = Context(
            values=dict(cluster_var_idx=(0, -2), annotation_var_idx=(0, -2)),
            **enc_domain
        )
        OWSilhouettePlot.migrate_context(context, 1)
        values = context.values
        self.assertNotIn("cluster_var_idx", values)
        self.assertNotIn("annotation_var_idx", values)
        self.assertEqual(values["cluster_var"], ("foo", 101))
        self.assertEqual(values["annotation_var"], None)

        # We have annotation
        context = Context(
            values=dict(cluster_var_idx=(2, -2), annotation_var_idx=(4, -2)),
            **enc_domain
        )
        OWSilhouettePlot.migrate_context(context, 1)
        self.assertNotIn("cluster_var_idx", values)
        self.assertNotIn("annotation_var_idx", values)
        self.assertEqual(context.values["cluster_var"], ("baz", 101))
        self.assertEqual(context.values["annotation_var"], ("bax", 101))

        # We thought was had annotation, but the index is wrong due to
        # incorrect domain
        context = Context(
            values=dict(cluster_var_idx=(4, -2), annotation_var_idx=(7, -2)),
            **enc_domain
        )
        OWSilhouettePlot.migrate_context(context, 1)
        self.assertEqual(context.values["cluster_var"], ("cfoo", 101))
        self.assertNotIn("annotation_var_idx", values)
Beispiel #10
0
    def test_migration_2_3(self):
        # Obsolete, don't want to cause confusion by public import
        # pylint: disable=import-outside-toplevel
        from Orange.widgets.data.owdiscretize import \
            Default, EqualFreq, Leave, Custom, MDL, EqualWidth, DState
        context_values = {
            'saved_var_states': ({
                (2, 'age'):
                DState(method=Leave()),
                (2, 'rest SBP'):
                DState(method=EqualWidth(k=4)),
                (2, 'cholesterol'):
                DState(method=EqualFreq(k=6)),
                (4, 'max HR'):
                DState(method=Custom(points=(1.0, 2.0, 3.0))),
                (2, 'ST by exercise'):
                DState(method=MDL()),
                (2, 'major vessels colored'):
                DState(method=Default(method=EqualFreq(k=3)))
            }, -2),
            '__version__':
            2
        }

        settings = {
            'autosend': True,
            'controlAreaVisible': True,
            'default_cutpoints': (),
            'default_k': 3,
            'default_method_name': 'EqualFreq',
            '__version__': 2,
            "context_settings": [Context(values=context_values)]
        }

        OWDiscretize.migrate_settings(settings, 2)
        self.assertNotIn("default_method_name", settings)
        self.assertNotIn("default_k", settings)
        self.assertNotIn("default_cutpoints", settings)
        self.assertNotIn("context_settings", settings)
        self.assertEqual(
            settings["var_hints"], {
                None: VarHint(Methods.EqualFreq, (3, )),
                ('ST by exercise', False): VarHint(Methods.MDL, ()),
                ('age', False): VarHint(Methods.Keep, ()),
                ('cholesterol', False): VarHint(Methods.EqualFreq, (6, )),
                ('max HR', True): VarHint(Methods.Custom, (('1, 2, 3'), )),
                ('rest SBP', False): VarHint(Methods.EqualWidth, (4, ))
            })
Beispiel #11
0
    def test_migrates_settings_removes_incompatible(self):
        handler = ContextHandler()
        handler.bind(SimpleWidget)

        widget = SimpleWidget()

        contexts = [Context(foo=i) for i in (13, 13, 0, 1, 13, 2, 13)]

        def migrate_context(context, _):
            if context.foo == 13:
                raise IncompatibleContext()

        with patch.object(SimpleWidget, "migrate_context", migrate_context):
            handler.initialize(widget, dict(context_settings=contexts))
            contexts = widget.context_settings
            self.assertEqual(len(contexts), 3)
            self.assertTrue(
                all(context.foo == i for i, context in enumerate(contexts)))
Beispiel #12
0
 def test_discard_settings_before_v3(self):
     for version in (None, 1, 2):
         self.assertRaises(IncompatibleContext,
                           OWRank.migrate_context,
                           Context(),
                           version=version)