File: owaggregatecolumns.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 (265 lines) | stat: -rw-r--r-- 9,778 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
from itertools import chain
from typing import List, NamedTuple, Callable

import numpy as np

from AnyQt.QtWidgets import QSizePolicy, QStyle, \
    QButtonGroup, QRadioButton, QComboBox
from AnyQt.QtCore import Qt

from Orange.data import Variable, Table, ContinuousVariable, TimeVariable
from Orange.data.util import get_unique_names
from Orange.widgets import gui, widget
from Orange.widgets.settings import (
    ContextSetting, Setting, DomainContextHandler
)
from Orange.widgets.utils.signals import AttributeList
from Orange.widgets.utils.widgetpreview import WidgetPreview
from Orange.widgets.widget import Input, Output
from Orange.widgets.utils.itemmodels import DomainModel


class OpDesc(NamedTuple):
    name: str
    func: Callable[[np.ndarray], np.ndarray]
    time_preserving: bool = False


def nancount_nonzero(a, axis=None):
    return np.count_nonzero(np.nan_to_num(a), axis=axis)


class OWAggregateColumns(widget.OWWidget):
    name = "Aggregate Columns"
    description = "Compute a sum, max, min ... of selected columns."
    category = "Transform"
    icon = "icons/AggregateColumns.svg"
    priority = 1200
    keywords = "aggregate columns, aggregate, sum, product, max, min, mean, median, variance"

    class Inputs:
        data = Input("Data", Table, default=True)
        features = Input("Features", AttributeList)

    class Outputs:
        data = Output("Data", Table)

    class Warning(widget.OWWidget.Warning):
        discrete_features = widget.Msg("Some input features are categorical:\n{}")
        missing_features = widget.Msg("Some input features are missing:\n{}")

    want_main_area = False

    Operations = {"Sum": OpDesc("Sum", np.nansum),
                  "Product": OpDesc("Product", np.nanprod),
                  "Min": OpDesc("Minimal value", np.nanmin, True),
                  "Max": OpDesc("Maximal value", np.nanmax, True),
                  "Mean": OpDesc("Mean value", np.nanmean, True),
                  "Variance": OpDesc("Variance", np.nanvar),
                  "Median": OpDesc("Median", np.nanmedian, True),
                  "Count non-zero": OpDesc("Count non-zero", nancount_nonzero)}
    KeyFromDesc = {op.name: key for key, op in Operations.items()}

    SelectAll, SelectAllAndMeta, InputFeatures, SelectManually = range(4)

    settingsHandler = DomainContextHandler()
    variables: List[Variable] = ContextSetting([])
    selection_method: int = Setting(SelectManually, schema_only=True)
    operation = ContextSetting("Sum")
    var_name = Setting("agg", schema_only=True)
    auto_apply = Setting(True)

    def __init__(self):
        super().__init__()
        self.data = None
        self.features = None

        self.selection_box = gui.vBox(self.controlArea, "Variable selection")
        self.selection_group = QButtonGroup(self.selection_box)
        for i, label in enumerate(("All",
                                   "All, including meta attributes",
                                   "Features from separate input signal",
                                   "Selected variables")):
            button = QRadioButton(label)
            if i == self.selection_method:
                button.setChecked(True)
            self.selection_group.addButton(button, id=i)
            self.selection_box.layout().addWidget(button)
        self.selection_group.idClicked.connect(self._on_sel_method_changed)

        self.variable_model = DomainModel(
            order=(DomainModel.ATTRIBUTES, DomainModel.METAS),
            valid_types=ContinuousVariable)
        pixm: QStyle = self.style().pixelMetric
        ind_width = pixm(QStyle.PM_ExclusiveIndicatorWidth) + \
                    pixm(QStyle.PM_RadioButtonLabelSpacing)
        var_list = gui.listView(
            gui.indentedBox(self.selection_box, ind_width), self, "variables",
            model=self.variable_model,
            callback=self.commit.deferred
        )
        var_list.setSelectionMode(var_list.ExtendedSelection)

        box = gui.vBox(self.controlArea, box="Operation")
        combo = self.operation_combo = QComboBox()
        combo.addItems([op.name for op in self.Operations.values()])
        combo.textActivated[str].connect(self._on_operation_changed)
        combo.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        combo.setCurrentText(self.Operations[self.operation].name)
        box.layout().addWidget(combo)

        gui.lineEdit(
            box, self, "var_name",
            label="Output variable name: ", orientation=Qt.Horizontal,
            callback=self.commit.deferred
        )

        gui.auto_apply(self.buttonsArea, self)

        self._update_selection_buttons()


    @Inputs.data
    def set_data(self, data: Table = None):
        self.closeContext()
        self.variables.clear()
        self.data = data
        if self.data:
            self.variable_model.set_domain(data.domain)
            self.openContext(data)
            self.operation_combo.setCurrentText(self.Operations[self.operation].name)
        else:
            self.variable_model.set_domain(None)

    @Inputs.features
    def set_features(self, features):
        if features is None:
            self.features = None
            missing = []
        else:
            self.features = [attr for attr in features if attr.is_continuous]
            missing = self._missing(features, self.features)
        self.Warning.discrete_features(missing, shown=bool(missing))

    def _update_selection_buttons(self):
        if self.features is not None:
            for i, button in enumerate(self.selection_group.buttons()):
                button.setChecked(i == self.InputFeatures)
                button.setEnabled(i == self.InputFeatures)
            self.controls.variables.setEnabled(False)
        else:
            for i, button in enumerate(self.selection_group.buttons()):
                button.setChecked(i == self.selection_method)
                button.setEnabled(i != self.InputFeatures)
            self.controls.variables.setEnabled(
                self.selection_method == self.SelectManually)

    def handleNewSignals(self):
        self._update_selection_buttons()
        self.commit.now()

    def _on_sel_method_changed(self, i):
        self.selection_method = i
        self._update_selection_buttons()
        self.commit.deferred()

    def _on_operation_changed(self, oper):
        self.operation = self.KeyFromDesc[oper]
        self.commit.deferred()

    @gui.deferred
    def commit(self):
        augmented = self._compute_data()
        self.Outputs.data.send(augmented)

    def _compute_data(self):
        self.Warning.missing_features.clear()
        if not self.data:
            return self.data

        variables = self._variables()
        if not self.data or not variables:
            return self.data

        new_col = self._compute_column(variables)
        new_var = self._new_var(variables)
        return self.data.add_column(new_var, new_col)

    def _variables(self):
        self.Warning.missing_features.clear()
        if self.features is not None:
            selected = [attr for attr in self.features
                        if attr in self.data.domain]
            missing = self._missing(self.features, selected)
            self.Warning.missing_features(missing, shown=bool(missing))
            return selected

        assert self.data

        domain = self.data.domain
        if self.selection_method == self.SelectAll:
            return [attr for attr in domain.attributes
                    if attr.is_continuous]
        if self.selection_method == self.SelectAllAndMeta:
            # skip separators
            return [attr for attr in chain(domain.attributes, domain.metas)
                    if attr.is_continuous]

        assert self.selection_method == self.SelectManually
        return self.variables

    def _compute_column(self, variables):
        arr = np.empty((len(self.data), len(variables)))
        for i, var in enumerate(variables):
            arr[:, i] = self.data.get_column(var)
        func = self.Operations[self.operation].func
        return func(arr, axis=1)

    def _new_var_name(self):
        return get_unique_names(self.data.domain, self.var_name)

    def _new_var(self, variables):
        name = self._new_var_name()
        if self.Operations[self.operation].time_preserving \
                and all(isinstance(var, TimeVariable) for var in variables):
            return TimeVariable(name)
        return ContinuousVariable(name)

    def send_report(self):
        if not self.data:
            return
        variables = self._variables()
        if not variables:
            return
        var_list = self._and_others(variables, 30)
        self.report_items((
            ("Output:",
             f"'{self._new_var_name()}' as {self.operation.lower()} of {var_list}"
            ),
        ))

    @staticmethod
    def _and_others(variables, limit):
        if len(variables) == 1:
            return f"'{variables[0].name}'"
        var_list = ", ".join(f"'{var.name}'"
                             for var in variables[:limit + 1][:-1])
        if len(variables) > limit:
            var_list += f" and {len(variables) - limit} more"
        else:
            var_list += f" and '{variables[-1].name}'"
        return var_list

    @classmethod
    def _missing(cls, given, used):
        if len(given) == len(used):
            return ""
        used = set(used)
        # Don't use set difference because it loses order
        missing = [attr for attr in given if attr not in used]
        return cls._and_others(missing, 5)


if __name__ == "__main__":  # pragma: no cover
    brown = Table("brown-selected")
    WidgetPreview(OWAggregateColumns).run(set_data=brown)