def test_handles_builtins_in_expression(self):
        self.assertTrue(
            FeatureConstructorHandler().is_valid_item(
                OWFeatureConstructor.descriptors,
                StringDescriptor("X", "str(A) + str(B)"),
                {"A": vartype(DiscreteVariable)},
                {"B": vartype(DiscreteVariable)}
            )
        )

        # no variables is also ok
        self.assertTrue(
            FeatureConstructorHandler().is_valid_item(
                OWFeatureConstructor.descriptors,
                StringDescriptor("X", "str('foo')"),
                {},
                {}
            )
        )

        # should fail on unknown variables
        self.assertFalse(
            FeatureConstructorHandler().is_valid_item(
                OWFeatureConstructor.descriptors,
                StringDescriptor("X", "str(X)"),
                {},
                {}
            )
        )
示例#2
0
        def encode(attributes, encode_values):
            if not encode_values:
                return {v.name: vartype(v) for v in attributes}

            is_discrete = lambda x: isinstance(x, DiscreteVariable)
            return {v.name: v.values if is_discrete(v) else vartype(v)
                    for v in attributes}
示例#3
0
    def set_data(self, dataset):
        if dataset is not None and (
                not bool(dataset) or not len(dataset.domain)):
            dataset = None
        self.closeContext()
        self.dataset = dataset
        self.dist = self.stats = self.conts = []
        self.grouping_select = []
        self.attributes_select = []
        self.attr_list_box.clear()
        self.group_list_box.clear()
        if dataset:
            domain = dataset.domain
            self.attributes = [(a.name, vartype(a)) for a in domain.variables +
                               domain.metas if a.is_primitive()]
            self.grouping = ["None"] + [(a.name, vartype(a)) for a in
                                        domain.variables + domain.metas
                                        if a.is_discrete]
            self.grouping_select = [0]
            self.attributes_select = [0]

            self.openContext(self.dataset)

            self.attr_changed()
        else:
            self.reset_all_data()
    def test_encode_list_settings(self):
        setting = ContextSetting(None)

        var1, var2 = self.domain[:2]
        val = self.handler.encode_setting(None, setting, [None, var1, var2])
        self.assertEqual(
            val,
            ([None,
              (var1.name, 100 + vartype(var1)),
              (var2.name, 100 + vartype(var2))], -3))

        a_list = [1, 2, 3]
        val = self.handler.encode_setting(None, setting, a_list)
        self.assertEqual(val, [1, 2, 3])
        self.assertIsNot(val, a_list)

        a_list = []
        val = self.handler.encode_setting(None, setting, a_list)
        self.assertEqual(val, [])
        self.assertIsNot(val, a_list)

        a_list = [None, None]
        val = self.handler.encode_setting(None, setting, a_list)
        self.assertEqual(val, [None, None])
        self.assertIsNot(val, a_list)
示例#5
0
    def encode_variables(attributes, encode_values):
        """Encode variables to a list mapping name to variable type
        or a list of values."""

        if not encode_values:
            return {v.name: vartype(v) for v in attributes}

        return {v.name: v.values if v.is_discrete else vartype(v) for v in attributes}
    def test_encode_setting(self):
        setting = ContextSetting(None)

        var = self.domain[0]
        val = self.handler.encode_setting(None, setting, var)
        self.assertEqual(val, (var.name, 100 + vartype(var)))

        # Should not crash on anonymous variables
        var.name = ""
        val = self.handler.encode_setting(None, setting, var)
        self.assertEqual(val, (var.name, 100 + vartype(var)))
示例#7
0
 def new_context(self, domain, attributes, metas):
     """Create a new context."""
     context = super().new_context()
     context.attributes = attributes
     context.metas = metas
     context.ordered_domain = []
     if self.has_ordinary_attributes:
         context.ordered_domain += [(attr.name, vartype(attr)) for attr in domain]
     if self.has_meta_attributes:
         context.ordered_domain += [(attr.name, vartype(attr)) for attr in domain.metas]
     return context
    def test_decode_setting(self):
        setting = ContextSetting(None)

        var = self.domain[0]
        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),
                                          self.domain)
        self.assertIs(val, var)

        all_metas_domain = Domain([], metas=[var])
        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),
                                          all_metas_domain)
        self.assertIs(val, var)
    def test_decode_list_setting(self):
        setting = ContextSetting(None)

        var1, var2 = self.domain[:2]
        val = self.handler.decode_setting(
            setting,
            ([None,
              (var1.name, 100 + vartype(var1)),
              (var2.name, 100 + vartype(var2))], -3),
            self.domain)
        self.assertEqual(val, [None, var1, var2])

        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)
        self.assertEqual(val, [1, 2, 3])
示例#10
0
 def load_features(self):
     self.selected_features = []
     if self.corpus is not None:
         domain = self.corpus.domain
         self.features = [(var.name, vartype(var))
                          for var in chain(domain.variables, domain.metas)]
         self.selected_features = list(range(len(self.features)))  # FIXME: Select features based on ContextSetting
示例#11
0
    def shown_attributes(self, value):
        shown = []
        hidden = []

        domain = self.get_data_domain()
        attr_info = lambda a: (a.name, vartype(a))
        if domain:
            if value:
                shown = value if isinstance(value[0], tuple) else [attr_info(domain[a]) for a in value]
                hidden = [x for x in [attr_info(domain[a]) for a in domain.attributes] if x not in shown]
            else:
                shown = [attr_info(a) for a in domain.attributes]
                if not self.show_all_attributes:
                    hidden = shown[10:]
                    shown = shown[:10]

            if domain.class_var and attr_info(domain.class_var) not in shown:
                hidden += [attr_info(domain.class_var)]

        self._shown_attributes = shown
        self._hidden_attributes = hidden
        self.selected_hidden = []
        self.selected_shown = []

        self.trigger_attributes_changed()
示例#12
0
 def __model_selected_changed(self):
     self.selected_vars = [(var.name, vartype(var)) for var
                           in self.model_selected]
     self.projection = None
     self._check_options()
     self.init_projection()
     self.setup_plot()
     self.commit()
示例#13
0
 def encode_setting(self, context, setting, value):
     if setting.name == 'conditions':
         CONTINUOUS = vartype(ContinuousVariable())
         for i, (attr, op, values) in enumerate(value):
             if context.attributes.get(attr) == CONTINUOUS:
                 if values and isinstance(values[0], str):
                     values = [QLocale().toDouble(v)[0] for v in values]
                     value[i] = (attr, op, values)
     return super().encode_setting(context, setting, value)
示例#14
0
 def update_domain_role_hints(self):
     """ Update the domain hints to be stored in the widgets settings.
     """
     hints_from_model = lambda role, model: [((attr.name, vartype(attr)), (role, i)) for i, attr in enumerate(model)]
     hints = dict(hints_from_model("available", self.available_attrs))
     hints.update(hints_from_model("attribute", self.used_attrs))
     hints.update(hints_from_model("class", self.class_attrs))
     hints.update(hints_from_model("meta", self.meta_attrs))
     self.domain_role_hints = hints
 def test_handles_special_characters_in_var_names(self):
     self.assertTrue(
         FeatureConstructorHandler().is_valid_item(
             OWFeatureConstructor.descriptors,
             StringDescriptor("X", "A_2_f"),
             {"A.2 f": vartype(DiscreteVariable)},
             {}
         )
     )
示例#16
0
 def mimeData(self, indexlist):
     descriptors = []
     vars = []
     for index in indexlist:
         var = self[index.row()]
         descriptors.append((var.name, vartype(var)))
         vars.append(var)
     mime = QtCore.QMimeData()
     mime.setData(self.MIME_TYPE, QtCore.QByteArray(str(descriptors)))
     mime._vars = vars
     return mime
示例#17
0
    def find_or_create_context(self, widget, domain):
        if not domain:
            return None, False

        if not isinstance(domain, Domain):
            domain = domain.domain

        encoded_domain = self.encode_domain(domain)
        context, is_new = \
            super().find_or_create_context(widget, domain, *encoded_domain)

        context.attributes, context.metas = encoded_domain

        if self.has_ordinary_attributes:
            context.ordered_domain = [(v.name, vartype(v)) for v in domain]
        else:
            context.ordered_domain = []
        if self.has_meta_attributes:
            context.ordered_domain += [(v.name, vartype(v))
                                       for v in domain.metas]
        return context, is_new
示例#18
0
    def __model_selected_changed(self):
        self.selected_vars = [(var.name, vartype(var)) for var
                              in self.model_selected]

        self.Warning.no_features.clear()
        if len(self.model_selected) < 2:
            self.Warning.no_features()
            return

        self.init_projection()
        self.setup_plot()
        self.commit()
示例#19
0
 def encode_setting(self, context, setting, value):
     if isinstance(value, list):
         return copy.copy(value)
     elif isinstance(setting, ContextSetting):
         if isinstance(value, str):
             if not setting.exclude_attributes and value in context.attributes:
                 return value, context.attributes[value]
             if not setting.exclude_metas and value in context.metas:
                 return value, context.metas[value]
         elif isinstance(value, Variable):
             return value.name, 100 + vartype(value)
     return copy.copy(value), -2
示例#20
0
 def data(self, dataset):
     if dataset is not None and (
             not bool(dataset) or not len(dataset.domain)):
         dataset = None
     self.closeContext()
     self.ddataset = dataset
     self.grouping_select = []
     self.attributes_select = []
     self.attr_list_box.clear()
     self.attrCombo.clear()
     if dataset:
         self.openContext(self.ddataset)
         self.attributes = [(a.name, vartype(a)) for a in dataset.domain]
         self.grouping = ["None"] + [(a.name, vartype(a))
                                     for a in dataset.domain
                                     if isinstance(a, DiscreteVariable)]
         self.grouping_select = [0]
         self.attributes_select = [0]
         self.attr_changed()
     else:
         self.reset_all_data()
示例#21
0
    def set_data(self, data=None):
        self.update_domain_role_hints()
        self.closeContext()
        self.data = data
        if data is not None:
            self.openContext(data)
            all_vars = data.domain.variables + data.domain.metas

            var_sig = lambda attr: (attr.name, vartype(attr))

            domain_hints = {var_sig(attr): ("attribute", i)
                            for i, attr in enumerate(data.domain.attributes)}

            domain_hints.update({var_sig(attr): ("meta", i)
                                for i, attr in enumerate(data.domain.metas)})

            if data.domain.class_vars:
                domain_hints.update(
                    {var_sig(attr): ("class", i)
                     for i, attr in enumerate(data.domain.class_vars)})

            # update the hints from context settings
            domain_hints.update(self.domain_role_hints)

            attrs_for_role = lambda role: [
                (domain_hints[var_sig(attr)][1], attr)
                for attr in all_vars if domain_hints[var_sig(attr)][0] == role]

            attributes = [
                attr for place, attr in sorted(attrs_for_role("attribute"),
                                               key=lambda a: a[0])]
            classes = [
                attr for place, attr in sorted(attrs_for_role("class"),
                                               key=lambda a: a[0])]
            metas = [
                attr for place, attr in sorted(attrs_for_role("meta"),
                                               key=lambda a: a[0])]
            available = [
                attr for place, attr in sorted(attrs_for_role("available"),
                                               key=lambda a: a[0])]

            self.used_attrs[:] = attributes
            self.class_attrs[:] = classes
            self.meta_attrs[:] = metas
            self.available_attrs[:] = available
        else:
            self.used_attrs[:] = []
            self.class_attrs[:] = []
            self.meta_attrs[:] = []
            self.available_attrs[:] = []

        self.unconditional_commit()
示例#22
0
 def clone_context(self, context, domain, attrs, metas):
     context = copy.deepcopy(context)
     for name, setting in self.settings.items():
         if not isinstance(setting, ContextSetting):
             continue
         value = context.values.get(name, None)
         if value is None:
             continue
         if isinstance(value, dict):
             for item, category in value.items():
                 if not self._var_exists(setting, value, attrs, metas):
                     del value[item]
     context.attributes, context.metas = attrs, metas
     context.ordered_domain = [(attr.name, vartype(attr)) for attr in itertools.chain(domain, domain.metas)]
     return context
示例#23
0
    def clone_context(self, context, domain, attrs, metas):
        context = copy.deepcopy(context)

        for setting, data, instance in self.provider.traverse_settings(data=context.values):
            if not isinstance(setting, ContextSetting):
                continue

            value = data.get(setting.name, None)
            if isinstance(value, list):
                sel_name = getattr(setting, "selected", None)
                if sel_name is not None:
                    selected = data.get(sel_name, [])
                    selected.sort()
                    next_sel = selected and selected[0] or -1
                else:
                    selected = None
                    next_sel = -1
                i = j = realI = 0
                while i < len(value):
                    if self._var_exists(setting, value[i], attrs, metas):
                        if next_sel == realI:
                            selected[j] -= realI - i
                            j += 1
                            next_sel = j < len(selected) and selected[j] or -1
                        i += 1
                    else:
                        del value[i]
                        if next_sel == realI:
                            del selected[j]
                            next_sel = j < len(selected) and selected[j] or -1
                    realI += 1
                if sel_name is not None:
                    data[sel_name] = selected[:j]
            elif value is not None:
                if (value[1] >= 0 and
                        not self._var_exists(setting, value, attrs, metas)):
                    del data[setting.name]

        context.attributes, context.metas = attrs, metas
        context.ordered_domain = [(attr.name, vartype(attr)) for attr in
                                  itertools.chain(domain, domain.metas)]
        return context
示例#24
0
 def encode_variable(var):
     return var.name, 100 + vartype(var)
示例#25
0
            filter(None, [v.replace(r"\,", ",").strip() for v in values]))
        return DiscreteDescriptor(name=self.nameedit.text(),
                                  values=values,
                                  base_value=-1,
                                  ordered=False,
                                  expression=self.expressionedit.text())


class StringFeatureEditor(FeatureEditor):
    def editorData(self):
        return StringDescriptor(name=self.nameedit.text(),
                                expression=self.expressionedit.text())


_VarMap = {
    DiscreteDescriptor: vartype(Orange.data.DiscreteVariable()),
    ContinuousDescriptor: vartype(Orange.data.ContinuousVariable()),
    StringDescriptor: vartype(Orange.data.StringVariable())
}


@functools.lru_cache(20)
def variable_icon(dtype):
    vtype = _VarMap.get(dtype, dtype)
    try:
        return gui.attributeIconDict[vtype]
    except Exception:
        return QIcon()


class FeatureItemDelegate(QStyledItemDelegate):
示例#26
0
def variable_key(var):
    return vartype(var), var.name
示例#27
0
 def encode(attrs):
     return tuple((v.name, vartype(v)) for v in attrs)
示例#28
0
    def set_new_values(self, oper_combo, adding_all, selected_values=None):
        # def remove_children():
        #     for child in box.children()[1:]:
        #         box.layout().removeWidget(child)
        #         child.setParent(None)

        def add_textual(contents):
            le = gui.lineEdit(box,
                              self,
                              None,
                              sizePolicy=QSizePolicy(QSizePolicy.Expanding,
                                                     QSizePolicy.Expanding))
            if contents:
                le.setText(contents)
            le.setAlignment(Qt.AlignRight)
            le.editingFinished.connect(self.conditions_changed)
            return le

        def add_numeric(contents):
            le = add_textual(contents)
            le.setValidator(OWSelectRows.QDoubleValidatorEmpty())
            return le

        def add_datetime(contents):
            le = add_textual(contents)
            le.setValidator(QRegExpValidator(QRegExp(TimeVariable.REGEX)))
            return le

        box = self.cond_list.cellWidget(oper_combo.row, 2)
        lc = ["", ""]
        oper = oper_combo.currentIndex()
        attr_name = oper_combo.attr_combo.currentText()
        if attr_name in self.AllTypes:
            vtype = self.AllTypes[attr_name]
            var = None
        else:
            var = self.data.domain[attr_name]
            vtype = vartype(var)
            if selected_values is not None:
                lc = list(selected_values) + ["", ""]
                lc = [str(x) for x in lc[:2]]
        if box and vtype == box.var_type:
            lc = self._get_lineedit_contents(box) + lc

        if oper_combo.currentText().endswith(" defined"):
            label = QLabel()
            label.var_type = vtype
            self.cond_list.setCellWidget(oper_combo.row, 2, label)
        elif var is not None and var.is_discrete:
            if oper_combo.currentText().endswith(" one of"):
                if selected_values:
                    lc = [x for x in list(selected_values)]
                button = DropDownToolButton(self, var, lc)
                button.var_type = vtype
                self.cond_list.setCellWidget(oper_combo.row, 2, button)
            else:
                combo = ComboBoxSearch()
                combo.addItems(("", ) + var.values)
                if lc[0]:
                    combo.setCurrentIndex(int(lc[0]))
                else:
                    combo.setCurrentIndex(0)
                combo.var_type = vartype(var)
                self.cond_list.setCellWidget(oper_combo.row, 2, combo)
                combo.currentIndexChanged.connect(self.conditions_changed)
        else:
            box = gui.hBox(self, addToLayout=False)
            box.var_type = vtype
            self.cond_list.setCellWidget(oper_combo.row, 2, box)
            if vtype in (2, 4):  # continuous, time:
                validator = add_datetime if isinstance(
                    var, TimeVariable) else add_numeric
                box.controls = [validator(lc[0])]
                if oper > 5:
                    gui.widgetLabel(box, " and ")
                    box.controls.append(validator(lc[1]))
            elif vtype == 3:  # string:
                box.controls = [add_textual(lc[0])]
                if oper in [6, 7]:
                    gui.widgetLabel(box, " and ")
                    box.controls.append(add_textual(lc[1]))
            else:
                box.controls = []
        if not adding_all:
            self.conditions_changed()
示例#29
0
 def encode(attrs):
     return tuple(
         (v.name,
          v.values if isinstance(v, DiscreteVariable)
          else vartype(v))
         for v in attrs)
示例#30
0
    def commit(self):
        matching_output = self.data
        non_matching_output = None
        annotated_output = None

        self.Error.clear()
        if self.data:
            domain = self.data.domain
            conditions = []
            for attr_name, oper_idx, values in self.conditions:
                if attr_name in self.AllTypes:
                    attr_index = attr = None
                    attr_type = self.AllTypes[attr_name]
                    operators = self.Operators[attr_name]
                else:
                    attr_index = domain.index(attr_name)
                    attr = domain[attr_index]
                    attr_type = vartype(attr)
                    operators = self.Operators[type(attr)]
                opertype, _ = operators[oper_idx]
                if attr_type == 0:
                    filter = data_filter.IsDefined()
                elif attr_type in (2, 4):  # continuous, time
                    try:
                        floats = self._values_to_floats(attr, values)
                    except ValueError as e:
                        self.Error.parsing_error(e.args[0])
                        return
                    if floats is None:
                        continue
                    filter = data_filter.FilterContinuous(
                        attr_index, opertype, *floats)
                elif attr_type == 3:  # string
                    filter = data_filter.FilterString(
                        attr_index, opertype, *[str(v) for v in values])
                else:
                    if opertype == FilterDiscreteType.IsDefined:
                        f_values = None
                    else:
                        if not values or not values[0]:
                            continue
                        values = [attr.values[i - 1] for i in values]
                        if opertype == FilterDiscreteType.Equal:
                            f_values = {values[0]}
                        elif opertype == FilterDiscreteType.NotEqual:
                            f_values = set(attr.values)
                            f_values.remove(values[0])
                        elif opertype == FilterDiscreteType.In:
                            f_values = set(values)
                        else:
                            raise ValueError("invalid operand")
                    filter = data_filter.FilterDiscrete(attr_index, f_values)
                conditions.append(filter)

            if conditions:
                self.filters = data_filter.Values(conditions)
                matching_output = self.filters(self.data)
                self.filters.negate = True
                non_matching_output = self.filters(self.data)

                row_sel = np.in1d(self.data.ids, matching_output.ids)
                annotated_output = create_annotated_table(self.data, row_sel)

            # if hasattr(self.data, "name"):
            #     matching_output.name = self.data.name
            #     non_matching_output.name = self.data.name

            purge_attrs = self.purge_attributes
            purge_classes = self.purge_classes
            if (purge_attrs or purge_classes) and \
                    not isinstance(self.data, SqlTable):
                attr_flags = sum([
                    Remove.RemoveConstant * purge_attrs,
                    Remove.RemoveUnusedValues * purge_attrs
                ])
                class_flags = sum([
                    Remove.RemoveConstant * purge_classes,
                    Remove.RemoveUnusedValues * purge_classes
                ])
                # same settings used for attributes and meta features
                remover = Remove(attr_flags, class_flags, attr_flags)

                matching_output = remover(matching_output)
                non_matching_output = remover(non_matching_output)
                annotated_output = remover(annotated_output)

        if matching_output is not None and not len(matching_output):
            matching_output = None
        if non_matching_output is not None and not len(non_matching_output):
            non_matching_output = None
        if annotated_output is not None and not len(annotated_output):
            annotated_output = None

        self.Outputs.matching_data.send(matching_output)
        self.Outputs.unmatched_data.send(non_matching_output)
        self.Outputs.annotated_data.send(annotated_output)

        self.match_desc = report.describe_data_brief(matching_output)
        self.nonmatch_desc = report.describe_data_brief(non_matching_output)

        summary = matching_output.approx_len() if matching_output else \
            self.info.NoOutput
        details = format_summary_details(
            matching_output) if matching_output else ""
        self.info.set_output_summary(summary, details)
示例#31
0
def variable_key(variable):
    return (vartype(variable), variable.name)
示例#32
0
 def encode_variables(variables):
     return [(v.name, 100 + vartype(v)) if isinstance(v, Variable) else
             (v, 100) for v in variables]
示例#33
0
 def encode_setting(self, context, setting, value):
     if setting.name == 'domain_role_hints':
         value = {(var.name, vartype(var)): role_i
                  for var, role_i in value.items()}
     return super().encode_setting(context, setting, value)
示例#34
0
 def __model_selected_changed(self):
     self.selected_vars = [(var.name, vartype(var))
                           for var in self.model_selected]
     self.init_projection()
     self.setup_plot()
     self.commit()
示例#35
0
def variable_key(variable):
    return (vartype(variable), variable.name)
 def _encode(attrs):
     return tuple(
         (v.name, list(v.values) if v.is_discrete else vartype(v))
         for v in attrs)
import warnings
from unittest import TestCase
from unittest.mock import Mock
from Orange.data import Domain, DiscreteVariable
from Orange.data import ContinuousVariable
from Orange.util import OrangeDeprecationWarning
from Orange.widgets.settings import DomainContextHandler, ContextSetting
from Orange.widgets.utils import vartype

Continuous = vartype(ContinuousVariable())
Discrete = vartype(DiscreteVariable())


class TestDomainContextHandler(TestCase):
    def setUp(self):
        self.domain = Domain(attributes=[
            ContinuousVariable('c1'),
            DiscreteVariable('d1', values='abc'),
            DiscreteVariable('d2', values='def')
        ],
                             class_vars=[DiscreteVariable('d3', values='ghi')],
                             metas=[
                                 ContinuousVariable('c2'),
                                 DiscreteVariable('d4', values='jkl')
                             ])
        self.args = (self.domain, {
            'c1': Continuous,
            'd1': Discrete,
            'd2': Discrete,
            'd3': Discrete
        }, {
    def set_new_values(self, oper_combo, adding_all, selected_values=None):
        # def remove_children():
        #     for child in box.children()[1:]:
        #         box.layout().removeWidget(child)
        #         child.setParent(None)

        def add_textual(contents):
            le = gui.lineEdit(box, self, None,
                              sizePolicy=QSizePolicy(QSizePolicy.Expanding,
                                                     QSizePolicy.Expanding))
            if contents:
                le.setText(contents)
            le.setAlignment(Qt.AlignRight)
            le.editingFinished.connect(self.conditions_changed)
            return le

        def add_numeric(contents):
            le = add_textual(contents)
            le.setValidator(OWSelectRows.QDoubleValidatorEmpty())
            return le

        box = self.cond_list.cellWidget(oper_combo.row, 2)
        lc = ["", ""]
        oper = oper_combo.currentIndex()
        attr_name = oper_combo.attr_combo.currentText()
        if attr_name in self.AllTypes:
            vtype = self.AllTypes[attr_name]
            var = None
        else:
            var = self.data.domain[attr_name]
            var_idx = self.data.domain.index(attr_name)
            vtype = vartype(var)
            if selected_values is not None:
                lc = list(selected_values) + ["", ""]
                lc = [str(x) if vtype != 4 else x for x in lc[:2]]
        if box and vtype == box.var_type:
            lc = self._get_lineedit_contents(box) + lc

        if oper_combo.currentText().endswith(" defined"):
            label = QLabel()
            label.var_type = vtype
            self.cond_list.setCellWidget(oper_combo.row, 2, label)
        elif var is not None and var.is_discrete:
            if oper_combo.currentText().endswith(" one of"):
                if selected_values:
                    lc = list(selected_values)
                button = DropDownToolButton(self, var, lc)
                button.var_type = vtype
                self.cond_list.setCellWidget(oper_combo.row, 2, button)
            else:
                combo = ComboBoxSearch()
                combo.addItems(("", ) + var.values)
                if lc[0]:
                    combo.setCurrentIndex(int(lc[0]))
                else:
                    combo.setCurrentIndex(0)
                combo.var_type = vartype(var)
                self.cond_list.setCellWidget(oper_combo.row, 2, combo)
                combo.currentIndexChanged.connect(self.conditions_changed)
        else:
            box = gui.hBox(self, addToLayout=False)
            box.var_type = vtype
            self.cond_list.setCellWidget(oper_combo.row, 2, box)
            if vtype == 2:  # continuous:
                box.controls = [add_numeric(lc[0])]
                if oper > 5:
                    gui.widgetLabel(box, " and ")
                    box.controls.append(add_numeric(lc[1]))
            elif vtype == 3:  # string:
                box.controls = [add_textual(lc[0])]
                if oper in [6, 7]:
                    gui.widgetLabel(box, " and ")
                    box.controls.append(add_textual(lc[1]))
            elif vtype == 4:  # time:
                def invalidate_datetime():
                    if w_:
                        if w.dateTime() > w_.dateTime():
                            w_.setDateTime(w.dateTime())
                        if w.format == (1, 1):
                            w.calendarWidget.timeedit.setTime(w.time())
                            w_.calendarWidget.timeedit.setTime(w_.time())
                    elif w.format == (1, 1):
                        w.calendarWidget.timeedit.setTime(w.time())

                def datetime_changed():
                    self.conditions_changed()
                    invalidate_datetime()

                datetime_format = (var.have_date, var.have_time)
                column = self.data.get_column_view(var_idx)[0]
                w = DateTimeWidget(self, column, datetime_format)
                w.set_datetime(lc[0])
                box.controls = [w]
                box.layout().addWidget(w)
                w.dateTimeChanged.connect(datetime_changed)
                if oper > 5:
                    gui.widgetLabel(box, " and ")
                    w_ = DateTimeWidget(self, column, datetime_format)
                    w_.set_datetime(lc[1])
                    box.layout().addWidget(w_)
                    box.controls.append(w_)
                    invalidate_datetime()
                    w_.dateTimeChanged.connect(datetime_changed)
                else:
                    w_ = None
            else:
                box.controls = []
        if not adding_all:
            self.conditions_changed()
示例#39
0
    def send_report(self):
        if not self.data:
            self.report_paragraph("No data.")
            return

        pdesc = None
        describe_domain = False
        for d in (self.data_desc, self.match_desc, self.nonmatch_desc):
            if not d or not d["Data instances"]:
                continue
            ndesc = d.copy()
            del ndesc["Data instances"]
            if pdesc is not None and pdesc != ndesc:
                describe_domain = True
            pdesc = ndesc

        conditions = []
        domain = self.data.domain
        for attr_name, oper, values in self.conditions:
            if attr_name in self.AllTypes:
                attr = attr_name
                names = self.operator_names[attr_name]
                var_type = self.AllTypes[attr_name]
            else:
                attr = domain[attr_name]
                var_type = vartype(attr)
                names = self.operator_names[type(attr)]
            name = names[oper]
            if oper == len(names) - 1:
                conditions.append("{} {}".format(attr, name))
            elif var_type == 1:  # discrete
                if name == "is one of":
                    valnames = [attr.values[v - 1] for v in values]
                    if not valnames:
                        continue
                    if len(valnames) == 1:
                        valstr = valnames[0]
                    else:
                        valstr = f"{', '.join(valnames[:-1])} or {valnames[-1]}"
                    conditions.append(f"{attr} is {valstr}")
                elif values and values[0]:
                    value = values[0] - 1
                    conditions.append(f"{attr} {name} {attr.values[value]}")
            elif var_type == 3:  # string variable
                conditions.append(
                    f"{attr} {name} {' and '.join(map(repr, values))}")
            elif all(x for x in values):  # numeric variable
                conditions.append(f"{attr} {name} {' and '.join(values)}")
        items = OrderedDict()
        if describe_domain:
            items.update(self.data_desc)
        else:
            items["Instances"] = self.data_desc["Data instances"]
        items["Condition"] = " AND ".join(conditions) or "no conditions"
        self.report_items("Data", items)
        if describe_domain:
            self.report_items("Matching data", self.match_desc)
            self.report_items("Non-matching data", self.nonmatch_desc)
        else:
            match_inst = \
                bool(self.match_desc) and \
                self.match_desc["Data instances"]
            nonmatch_inst = \
                bool(self.nonmatch_desc) and \
                self.nonmatch_desc["Data instances"]
            self.report_items(
                "Output",
                (("Matching data",
                  "{} instances".format(match_inst) if match_inst else "None"),
                 ("Non-matching data", nonmatch_inst > 0
                  and "{} instances".format(nonmatch_inst))))
示例#40
0
 def migrate_context(cls, context, version):
     if version < 2:
         sel = context.values["selection"]
         context.values["selection"] = ([(var.name, vartype(var))
                                         for var in sel[0]], sel[1])
示例#41
0
import warnings
from distutils.version import LooseVersion
from unittest import TestCase
from unittest.mock import Mock

import Orange
from Orange.data import Domain, DiscreteVariable
from Orange.data import ContinuousVariable
from Orange.util import OrangeDeprecationWarning
from Orange.widgets.settings import DomainContextHandler, ContextSetting
from Orange.widgets.utils import vartype

Continuous = 100 + vartype(ContinuousVariable("x"))
Discrete = 100 + vartype(DiscreteVariable("x"))


class TestDomainContextHandler(TestCase):
    def setUp(self):
        self.domain = Domain(attributes=[
            ContinuousVariable('c1'),
            DiscreteVariable('d1', values='abc'),
            DiscreteVariable('d2', values='def')
        ],
                             class_vars=[DiscreteVariable('d3', values='ghi')],
                             metas=[
                                 ContinuousVariable('c2'),
                                 DiscreteVariable('d4', values='jkl')
                             ])
        self.args = (self.domain, {
            'c1': Continuous - 100,
            'd1': Discrete - 100,
示例#42
0
        return DiscreteDescriptor(name=self.nameedit.text(),
                                  values=values,
                                  ordered=False,
                                  expression=self.expressionedit.text())


class StringFeatureEditor(FeatureEditor):
    ExpressionTooltip = "A string expression"

    def editorData(self):
        return StringDescriptor(name=self.nameedit.text(),
                                expression=self.expressionedit.text())


_VarMap = {
    DiscreteDescriptor: vartype(Orange.data.DiscreteVariable("d")),
    ContinuousDescriptor: vartype(Orange.data.ContinuousVariable("c")),
    DateTimeDescriptor: vartype(Orange.data.TimeVariable("t")),
    StringDescriptor: vartype(Orange.data.StringVariable("s"))
}


@functools.lru_cache(20)
def variable_icon(dtype):
    vtype = _VarMap.get(dtype, dtype)
    return gui.attributeIconDict[vtype]


class FeatureItemDelegate(QStyledItemDelegate):
    @staticmethod
    def displayText(value, _):
示例#43
0
 def load_features(self):
     self.selected_features = []
     if self.corpus is not None:
         self.features = [(meta.name, vartype(meta)) for meta in self.corpus.domain.metas] + \
                         [(attr.name, vartype(attr)) for attr in self.corpus.domain.attributes]
         self.selected_features = [0]  # Select the first feature.
示例#44
0
    def set_new_values(self, oper_combo, adding_all, selected_values=None):
        # def remove_children():
        #     for child in box.children()[1:]:
        #         box.layout().removeWidget(child)
        #         child.setParent(None)

        def add_textual(contents):
            le = gui.lineEdit(box, self, None)
            if contents:
                le.setText(contents)
            le.setAlignment(QtCore.Qt.AlignRight)
            le.editingFinished.connect(self.conditions_changed)
            return le

        def add_numeric(contents):
            le = add_textual(contents)
            le.setValidator(OWSelectRows.QDoubleValidatorEmpty())
            return le

        var = self.data.domain[oper_combo.attr_combo.currentText()]
        box = self.cond_list.cellWidget(oper_combo.row, 2)
        if selected_values is not None:
            lc = list(selected_values) + ["", ""]
            lc = [str(x) for x in lc[:2]]
        else:
            lc = ["", ""]
        if box and vartype(var) == box.var_type:
            lc = self._get_lineedit_contents(box) + lc
        oper = oper_combo.currentIndex()

        if oper == oper_combo.count() - 1:
            self.cond_list.removeCellWidget(oper_combo.row, 2)
        elif var.is_discrete:
            if oper_combo.currentText() == "is one of":
                if selected_values:
                    lc = [x for x in list(selected_values)]
                button = DropDownToolButton(self, var, lc)
                button.var_type = vartype(var)
                self.cond_list.setCellWidget(oper_combo.row, 2, button)
            else:
                combo = QtGui.QComboBox()
                combo.addItems([""] + var.values)
                if lc[0]:
                    combo.setCurrentIndex(int(lc[0]))
                else:
                    combo.setCurrentIndex(0)
                combo.var_type = vartype(var)
                self.cond_list.setCellWidget(oper_combo.row, 2, combo)
                combo.currentIndexChanged.connect(self.conditions_changed)
        else:
            box = gui.widgetBox(self,
                                orientation="horizontal",
                                addToLayout=False)
            box.var_type = vartype(var)
            self.cond_list.setCellWidget(oper_combo.row, 2, box)
            if var.is_continuous:
                box.controls = [add_numeric(lc[0])]
                if oper > 5:
                    gui.widgetLabel(box, " and ")
                    box.controls.append(add_numeric(lc[1]))
                gui.rubber(box)
            elif var.is_string:
                box.controls = [add_textual(lc[0])]
                if oper in [6, 7]:
                    gui.widgetLabel(box, " and ")
                    box.controls.append(add_textual(lc[1]))
            else:
                box.controls = []
        if not adding_all:
            self.conditions_changed()
示例#45
0
 def encode(attrs):
     return tuple((v.name, v.values if v.is_discrete else vartype(v))
                  for v in attrs)
示例#46
0
 def encode(attrs):
     return tuple((v.name, vartype(v)) for v in attrs)
示例#47
0
def variable_key(var):
    return vartype(var), var.name
    def set_data(self, data=None):
        self.update_domain_role_hints()
        self.closeContext()
        self.data = data
        if data is not None:
            self.openContext(data)
            all_vars = data.domain.variables + data.domain.metas

            var_sig = lambda attr: (attr.name, vartype(attr))

            domain_hints = {
                var_sig(attr): ("attribute", i)
                for i, attr in enumerate(data.domain.attributes)
            }

            domain_hints.update({
                var_sig(attr): ("meta", i)
                for i, attr in enumerate(data.domain.metas)
            })

            if data.domain.class_vars:
                domain_hints.update({
                    var_sig(attr): ("class", i)
                    for i, attr in enumerate(data.domain.class_vars)
                })

            # update the hints from context settings
            domain_hints.update(self.domain_role_hints)

            attrs_for_role = lambda role: [
                (domain_hints[var_sig(attr)][1], attr) for attr in all_vars
                if domain_hints[var_sig(attr)][0] == role
            ]

            attributes = [
                attr for place, attr in sorted(attrs_for_role("attribute"),
                                               key=lambda a: a[0])
            ]
            classes = [
                attr for place, attr in sorted(attrs_for_role("class"),
                                               key=lambda a: a[0])
            ]
            metas = [
                attr for place, attr in sorted(attrs_for_role("meta"),
                                               key=lambda a: a[0])
            ]
            available = [
                attr for place, attr in sorted(attrs_for_role("available"),
                                               key=lambda a: a[0])
            ]

            self.used_attrs[:] = attributes
            self.class_attrs[:] = classes
            self.meta_attrs[:] = metas
            self.available_attrs[:] = available
        else:
            self.used_attrs[:] = []
            self.class_attrs[:] = []
            self.meta_attrs[:] = []
            self.available_attrs[:] = []

        self.unconditional_commit()
# Test methods with descriptive names can omit docstrings
# pylint: disable=missing-docstring

from unittest import TestCase
from unittest.mock import Mock

from Orange.data import ContinuousVariable, DiscreteVariable, Domain
from Orange.widgets.settings import ContextSetting, PerfectDomainContextHandler, Context, Setting
from Orange.widgets.utils import vartype

Continuous = vartype(ContinuousVariable())
Discrete = vartype(DiscreteVariable())


class TestPerfectDomainContextHandler(TestCase):
    def setUp(self):
        self.domain = Domain(
            attributes=[ContinuousVariable('c1'),
                        DiscreteVariable('d1', values='abc'),
                        DiscreteVariable('d2', values='def')],
            class_vars=[DiscreteVariable('d3', values='ghi')],
            metas=[ContinuousVariable('c2'),
                   DiscreteVariable('d4', values='jkl')]
        )
        self.args = (self.domain,
                     (('c1', Continuous), ('d1', Discrete), ('d2', Discrete)),
                     (('d3', Discrete),),
                     (('c2', Continuous), ('d4', Discrete)))
        self.args_match_all = (self.domain,
                               (('c1', Continuous), ('d1', list('abc')), ('d2', list('def'))),
                               (('d3', list('ghi')),),
示例#50
0
 def test_handles_special_characters_in_var_names(self):
     self.assertTrue(FeatureConstructorHandler().is_valid_item(
         OWFeatureConstructor.descriptors, StringDescriptor("X", "A_2_f"),
         {"A.2 f": vartype(DiscreteVariable)}, {}))
示例#51
0
 def encode(attrs):
     return tuple(
         (v.name, v.values if isinstance(v, DiscreteVariable
                                         ) else vartype(v))
         for v in attrs)
示例#52
0
 def _vizrank_selection_changed(self, *args):
     self.selection = [(var.name, vartype(var)) for var in args]
     self.commit()