forked from biolab/orange3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathowscatterplot.py
More file actions
516 lines (445 loc) · 19.7 KB
/
owscatterplot.py
File metadata and controls
516 lines (445 loc) · 19.7 KB
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
from itertools import chain
from xml.sax.saxutils import escape
import numpy as np
from scipy.stats import linregress
from sklearn.neighbors import NearestNeighbors
from sklearn.metrics import r2_score
from AnyQt.QtCore import Qt, QTimer, QPointF, Signal
from AnyQt.QtGui import QColor
import pyqtgraph as pg
from Orange.data import Table, Domain, DiscreteVariable, Variable, \
ContinuousVariable
from Orange.data.sql.table import SqlTable, AUTO_DL_LIMIT
from Orange.preprocess.score import ReliefF, RReliefF
from Orange.widgets import gui
from Orange.widgets.io import MatplotlibFormat, MatplotlibPDFFormat
from Orange.widgets.settings import (
Setting, ContextSetting, SettingProvider, IncompatibleContext)
from Orange.widgets.utils.itemmodels import DomainModel
from Orange.widgets.utils.widgetpreview import WidgetPreview
from Orange.widgets.visualize.owscatterplotgraph import OWScatterPlotBase
from Orange.widgets.visualize.utils import VizRankDialogAttrPair
from Orange.widgets.visualize.utils.widget import OWDataProjectionWidget
from Orange.widgets.widget import AttributeList, Msg, Input, Output
class ScatterPlotVizRank(VizRankDialogAttrPair):
captionTitle = "Score Plots"
minK = 10
attr_color = None
def __init__(self, master):
super().__init__(master)
self.attr_color = self.master.attr_color
def initialize(self):
self.attr_color = self.master.attr_color
super().initialize()
def check_preconditions(self):
self.Information.add_message(
"color_required", "Color variable must be selected")
self.Information.color_required.clear()
if not super().check_preconditions():
return False
if not self.attr_color:
self.Information.color_required()
return False
return True
def iterate_states(self, initial_state):
# If we put initialization of `self.attrs` to `initialize`,
# `score_heuristic` would be run on every call to `set_data`.
if initial_state is None: # on the first call, compute order
self.attrs = self.score_heuristic()
yield from super().iterate_states(initial_state)
def compute_score(self, state):
# pylint: disable=invalid-unary-operand-type
attrs = [self.attrs[i] for i in state]
data = self.master.data
data = data.transform(Domain(attrs, self.attr_color))
data = data[~np.isnan(data.X).any(axis=1) & ~np.isnan(data.Y).T]
if len(data) < self.minK:
return None
n_neighbors = min(self.minK, len(data) - 1)
knn = NearestNeighbors(n_neighbors=n_neighbors).fit(data.X)
ind = knn.kneighbors(return_distance=False)
if data.domain.has_discrete_class:
return -np.sum(data.Y[ind] == data.Y.reshape(-1, 1)) / \
n_neighbors / len(data.Y)
else:
return -r2_score(data.Y, np.mean(data.Y[ind], axis=1)) * \
(len(data.Y) / len(self.master.data))
def bar_length(self, score):
return max(0, -score)
def score_heuristic(self):
assert self.attr_color is not None
master_domain = self.master.data.domain
vars = [v for v in chain(master_domain.variables, master_domain.metas)
if v is not self.attr_color and v.is_continuous]
domain = Domain(attributes=vars, class_vars=self.attr_color)
data = self.master.data.transform(domain)
relief = ReliefF if isinstance(domain.class_var, DiscreteVariable) \
else RReliefF
weights = relief(n_iterations=100, k_nearest=self.minK)(data)
attrs = sorted(zip(weights, domain.attributes),
key=lambda x: (-x[0], x[1].name))
return [a for _, a in attrs]
class OWScatterPlotGraph(OWScatterPlotBase):
show_reg_line = Setting(False)
orthonormal_regression = Setting(False)
def __init__(self, scatter_widget, parent):
super().__init__(scatter_widget, parent)
self.reg_line_items = []
def clear(self):
super().clear()
self.reg_line_items.clear()
def update_coordinates(self):
super().update_coordinates()
self.update_axes()
# Don't update_regression line here: update_coordinates is always
# followed by update_point_props, which calls update_colors
def update_colors(self):
super().update_colors()
self.update_regression_line()
def update_axes(self):
for axis, title in self.master.get_axes().items():
self.plot_widget.setLabel(axis=axis, text=title or "")
if title is None:
self.plot_widget.hideAxis(axis)
@staticmethod
def _orthonormal_line(x, y, color, width):
# https://en.wikipedia.org/wiki/Deming_regression, with δ=0.
pen = pg.mkPen(color=color, width=width)
xm = np.mean(x)
ym = np.mean(y)
sxx, sxy, _, syy = np.cov(x, y, ddof=1).flatten()
if sxy != 0: # also covers sxx != 0 and syy != 0
slope = (syy - sxx + np.sqrt((syy - sxx) ** 2 + 4 * sxy ** 2)) \
/ (2 * sxy)
intercept = ym - slope * xm
xmin = x.min()
return pg.InfiniteLine(
QPointF(xmin, xmin * slope + intercept),
np.degrees(np.arctan(slope)),
pen)
elif (sxx == 0) == (syy == 0): # both zero or non-zero -> can't draw
return None
elif sxx != 0:
return pg.InfiniteLine(QPointF(x.min(), ym), 0, pen)
else:
return pg.InfiniteLine(QPointF(xm, y.min()), 90, pen)
@staticmethod
def _regression_line(x, y, color, width):
min_x, max_x = np.min(x), np.max(x)
if min_x == max_x:
return None
slope, intercept, rvalue, _, _ = linregress(x, y)
angle = np.degrees(np.arctan(slope))
start_y = min_x * slope + intercept
rotate = 135 < angle % 360 < 315
l_opts = dict(color=color, position=abs(rotate - 0.85),
rotateAxis=(1, 0), movable=True)
reg_line_item = pg.InfiniteLine(
pos=QPointF(min_x, start_y), angle=angle,
pen=pg.mkPen(color=color, width=width),
label=f"r = {rvalue:.2f}", labelOpts=l_opts)
if rotate:
reg_line_item.label.angle = 180
reg_line_item.label.updateTransform()
return reg_line_item
def _add_line(self, x, y, color, width):
if self.orthonormal_regression:
line = self._orthonormal_line(x, y, color, width)
else:
line = self._regression_line(x, y, color, width)
if line is None:
return
self.plot_widget.addItem(line)
self.reg_line_items.append(line)
def update_regression_line(self):
for line in self.reg_line_items:
self.plot_widget.removeItem(line)
self.reg_line_items.clear()
if not self.show_reg_line:
return
x, y = self.master.get_coordinates_data()
if x is None:
return
self._add_line(x, y, QColor("#505050"), width=2)
if self.master.is_continuous_color() or self.palette is None:
return
c_data = self.master.get_color_data()
if c_data is None:
return
c_data = c_data.astype(int)
for val in range(c_data.max() + 1):
mask = c_data == val
if mask.sum() > 1:
self._add_line(x[mask], y[mask], self.palette[val], width=2)
class OWScatterPlot(OWDataProjectionWidget):
"""Scatterplot visualization with explorative analysis and intelligent
data visualization enhancements."""
name = 'Scatter Plot'
description = "Interactive scatter plot visualization with " \
"intelligent data visualization enhancements."
icon = "icons/ScatterPlot.svg"
priority = 140
keywords = []
class Inputs(OWDataProjectionWidget.Inputs):
features = Input("Features", AttributeList)
class Outputs(OWDataProjectionWidget.Outputs):
features = Output("Features", AttributeList, dynamic=False)
settings_version = 4
auto_sample = Setting(True)
attr_x = ContextSetting(None)
attr_y = ContextSetting(None)
tooltip_shows_all = Setting(True)
GRAPH_CLASS = OWScatterPlotGraph
graph = SettingProvider(OWScatterPlotGraph)
embedding_variables_names = None
xy_changed_manually = Signal(Variable, Variable)
class Warning(OWDataProjectionWidget.Warning):
missing_coords = Msg(
"Plot cannot be displayed because '{}' or '{}' "
"is missing for all data points")
no_continuous_vars = Msg("Data has no continuous variables")
class Information(OWDataProjectionWidget.Information):
sampled_sql = Msg("Large SQL table; showing a sample.")
missing_coords = Msg(
"Points with missing '{}' or '{}' are not displayed")
def __init__(self):
self.sql_data = None # Orange.data.sql.table.SqlTable
self.attribute_selection_list = None # list of Orange.data.Variable
self.__timer = QTimer(self, interval=1200)
self.__timer.timeout.connect(self.add_data)
super().__init__()
# manually register Matplotlib file writers
self.graph_writers = self.graph_writers.copy()
for w in [MatplotlibFormat, MatplotlibPDFFormat]:
self.graph_writers.append(w)
def _add_controls(self):
self._add_controls_axis()
self._add_controls_sampling()
super()._add_controls()
self.gui.add_widgets(
[self.gui.ShowGridLines,
self.gui.ToolTipShowsAll,
self.gui.RegressionLine],
self._plot_box)
gui.checkBox(
gui.indentedBox(self._plot_box), self,
value="graph.orthonormal_regression",
label="Treat variables as independent",
callback=self.graph.update_regression_line,
tooltip=
"If checked, fit line to group (minimize distance from points);\n"
"otherwise fit y as a function of x (minimize vertical distances)")
def _add_controls_axis(self):
common_options = dict(
labelWidth=50, orientation=Qt.Horizontal, sendSelectedValue=True,
valueType=str, contentsLength=14
)
box = gui.vBox(self.controlArea, True)
dmod = DomainModel
self.xy_model = DomainModel(dmod.MIXED, valid_types=ContinuousVariable)
self.cb_attr_x = gui.comboBox(
box, self, "attr_x", label="Axis x:",
callback=self.set_attr_from_combo,
model=self.xy_model, **common_options)
self.cb_attr_y = gui.comboBox(
box, self, "attr_y", label="Axis y:",
callback=self.set_attr_from_combo,
model=self.xy_model, **common_options)
vizrank_box = gui.hBox(box)
self.vizrank, self.vizrank_button = ScatterPlotVizRank.add_vizrank(
vizrank_box, self, "Find Informative Projections", self.set_attr)
def _add_controls_sampling(self):
self.sampling = gui.auto_commit(
self.controlArea, self, "auto_sample", "Sample", box="Sampling",
callback=self.switch_sampling, commit=lambda: self.add_data(1))
self.sampling.setVisible(False)
@property
def effective_variables(self):
return [self.attr_x, self.attr_y] if self.attr_x and self.attr_y else []
def _vizrank_color_change(self):
self.vizrank.initialize()
is_enabled = self.data is not None and not self.data.is_sparse() and \
len(self.xy_model) > 2 and len(self.data[self.valid_data]) > 1 \
and np.all(np.nan_to_num(np.nanstd(self.data.X, 0)) != 0)
self.vizrank_button.setEnabled(
is_enabled and self.attr_color is not None and
not np.isnan(self.data.get_column_view(
self.attr_color)[0].astype(float)).all())
text = "Color variable has to be selected." \
if is_enabled and self.attr_color is None else ""
self.vizrank_button.setToolTip(text)
def set_data(self, data):
super().set_data(data)
def findvar(name, iterable):
"""Find a Orange.data.Variable in `iterable` by name"""
for el in iterable:
if isinstance(el, Variable) and el.name == name:
return el
return None
# handle restored settings from < 3.3.9 when attr_* were stored
# by name
if isinstance(self.attr_x, str):
self.attr_x = findvar(self.attr_x, self.xy_model)
if isinstance(self.attr_y, str):
self.attr_y = findvar(self.attr_y, self.xy_model)
if isinstance(self.attr_label, str):
self.attr_label = findvar(self.attr_label, self.gui.label_model)
if isinstance(self.attr_color, str):
self.attr_color = findvar(self.attr_color, self.gui.color_model)
if isinstance(self.attr_shape, str):
self.attr_shape = findvar(self.attr_shape, self.gui.shape_model)
if isinstance(self.attr_size, str):
self.attr_size = findvar(self.attr_size, self.gui.size_model)
def check_data(self):
super().check_data()
self.__timer.stop()
self.sampling.setVisible(False)
self.sql_data = None
if isinstance(self.data, SqlTable):
if self.data.approx_len() < 4000:
self.data = Table(self.data)
else:
self.Information.sampled_sql()
self.sql_data = self.data
data_sample = self.data.sample_time(0.8, no_cache=True)
data_sample.download_data(2000, partial=True)
self.data = Table(data_sample)
self.sampling.setVisible(True)
if self.auto_sample:
self.__timer.start()
if self.data is not None:
if not self.data.domain.has_continuous_attributes(True, True):
self.Warning.no_continuous_vars()
self.data = None
if self.data is not None and (len(self.data) == 0 or
len(self.data.domain) == 0):
self.data = None
def get_embedding(self):
self.valid_data = None
if self.data is None:
return None
x_data = self.get_column(self.attr_x, filter_valid=False)
y_data = self.get_column(self.attr_y, filter_valid=False)
if x_data is None or y_data is None:
return None
self.Warning.missing_coords.clear()
self.Information.missing_coords.clear()
self.valid_data = np.isfinite(x_data) & np.isfinite(y_data)
if self.valid_data is not None and not np.all(self.valid_data):
msg = self.Information if np.any(self.valid_data) else self.Warning
msg.missing_coords(self.attr_x.name, self.attr_y.name)
return np.vstack((x_data, y_data)).T
# Tooltip
def _point_tooltip(self, point_id, skip_attrs=()):
point_data = self.data[point_id]
xy_attrs = (self.attr_x, self.attr_y)
text = "<br/>".join(
escape('{} = {}'.format(var.name, point_data[var]))
for var in xy_attrs)
if self.tooltip_shows_all:
others = super()._point_tooltip(point_id, skip_attrs=xy_attrs)
if others:
text = "<b>{}</b><br/><br/>{}".format(text, others)
return text
def add_data(self, time=0.4):
if self.data and len(self.data) > 2000:
self.__timer.stop()
return
data_sample = self.sql_data.sample_time(time, no_cache=True)
if data_sample:
data_sample.download_data(2000, partial=True)
data = Table(data_sample)
self.data = Table.concatenate((self.data, data), axis=0)
self.handleNewSignals()
def init_attr_values(self):
super().init_attr_values()
data = self.data
domain = data.domain if data and len(data) else None
self.xy_model.set_domain(domain)
self.attr_x = self.xy_model[0] if self.xy_model else None
self.attr_y = self.xy_model[1] if len(self.xy_model) >= 2 \
else self.attr_x
def switch_sampling(self):
self.__timer.stop()
if self.auto_sample and self.sql_data:
self.add_data()
self.__timer.start()
def set_subset_data(self, subset_data):
self.warning()
if isinstance(subset_data, SqlTable):
if subset_data.approx_len() < AUTO_DL_LIMIT:
subset_data = Table(subset_data)
else:
self.warning("Data subset does not support large Sql tables")
subset_data = None
super().set_subset_data(subset_data)
# called when all signals are received, so the graph is updated only once
def handleNewSignals(self):
if self.attribute_selection_list and self.data is not None and \
self.data.domain is not None and \
all(attr in self.data.domain for attr
in self.attribute_selection_list):
self.attr_x, self.attr_y = self.attribute_selection_list[:2]
self.attribute_selection_list = None
super().handleNewSignals()
if self._domain_invalidated:
self.graph.update_axes()
self._domain_invalidated = False
self._vizrank_color_change()
@Inputs.features
def set_shown_attributes(self, attributes):
if attributes and len(attributes) >= 2:
self.attribute_selection_list = attributes[:2]
self._invalidated = self._invalidated \
or self.attr_x != attributes[0] \
or self.attr_y != attributes[1]
else:
self.attribute_selection_list = None
def set_attr(self, attr_x, attr_y):
if attr_x != self.attr_x or attr_y != self.attr_y:
self.attr_x, self.attr_y = attr_x, attr_y
self.attr_changed()
def set_attr_from_combo(self):
self.attr_changed()
self.xy_changed_manually.emit(self.attr_x, self.attr_y)
def attr_changed(self):
self.setup_plot()
self.commit()
def get_axes(self):
return {"bottom": self.attr_x, "left": self.attr_y}
def colors_changed(self):
super().colors_changed()
self._vizrank_color_change()
def commit(self):
super().commit()
self.send_features()
def send_features(self):
features = [attr for attr in [self.attr_x, self.attr_y] if attr]
self.Outputs.features.send(features or None)
def get_widget_name_extension(self):
if self.data is not None:
return "{} vs {}".format(self.attr_x.name, self.attr_y.name)
return None
@classmethod
def migrate_settings(cls, settings, version):
if version < 2 and "selection" in settings and settings["selection"]:
settings["selection_group"] = [(a, 1) for a in settings["selection"]]
if version < 3:
if "auto_send_selection" in settings:
settings["auto_commit"] = settings["auto_send_selection"]
if "selection_group" in settings:
settings["selection"] = settings["selection_group"]
@classmethod
def migrate_context(cls, context, version):
values = context.values
if version < 3:
values["attr_color"] = values["graph"]["attr_color"]
values["attr_size"] = values["graph"]["attr_size"]
values["attr_shape"] = values["graph"]["attr_shape"]
values["attr_label"] = values["graph"]["attr_label"]
if version < 4:
if values["attr_x"][1] % 100 == 1 or values["attr_y"][1] % 100 == 1:
raise IncompatibleContext()
if __name__ == "__main__": # pragma: no cover
data = Table("iris")
WidgetPreview(OWScatterPlot).run(set_data=data, set_subset_data=data[:30])