Skip to content

Commit

Permalink
Merge pull request #3460 from janezd/pylint-visualize
Browse files Browse the repository at this point in the history
[MNT] Fix pylint issues in visualization widgets and tests
  • Loading branch information
lanzagar authored Dec 14, 2018
2 parents 80d3528 + 840d35c commit 74515ca
Show file tree
Hide file tree
Showing 20 changed files with 105 additions and 118 deletions.
12 changes: 7 additions & 5 deletions Orange/widgets/visualize/owboxplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,8 @@ def layout_changed(self):
return

if not self.is_continuous:
return self.display_changed_disc()
self.display_changed_disc()
return

self.mean_labels = [self.mean_label(stat, attr, lab)
for stat, lab in zip(self.stats, self.label_txts)]
Expand All @@ -502,7 +503,8 @@ def display_changed(self):
return

if not self.is_continuous:
return self.display_changed_disc()
self.display_changed_disc()
return

self.order = list(range(len(self.stats)))
criterion = self._sorting_criteria_attrs[self.compare]
Expand Down Expand Up @@ -578,6 +580,7 @@ def display_changed_disc(self):
self.conts = self.conts[np.sum(np.array(self.conts), axis=1) > 0]

if self.sort_freqs:
# pylint: disable=invalid-unary-operand-type
self.order = sorted(self.order, key=(-np.sum(self.conts, axis=1)).__getitem__)
else:
self.boxes = [self.strudel(self.dist)]
Expand Down Expand Up @@ -1043,7 +1046,7 @@ def line(y0, y1):
if xs[to] - frm_x > 1.5:
to -= 1
break
if last_to == to or frm == to:
if to in (last_to, frm):
continue
for rowi, used in enumerate(used_to):
if used < frm:
Expand All @@ -1059,8 +1062,7 @@ def line(y0, y1):
last_to = to

def get_widget_name_extension(self):
if self.attribute:
return self.attribute.name
return self.attribute.name if self.attribute else None

def send_report(self):
self.report_plot()
Expand Down
52 changes: 28 additions & 24 deletions Orange/widgets/visualize/owdistributions.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
import collections
from xml.sax.saxutils import escape

import numpy
import pyqtgraph as pg

from AnyQt.QtWidgets import QSizePolicy, QLabel, QListView, QToolTip
from AnyQt.QtGui import QColor, QPen, QBrush, QPainter, QPicture, QPalette
from AnyQt.QtCore import Qt, QRectF

import numpy
import pyqtgraph as pg

import Orange.data
from Orange.preprocess import Discretize, EqualWidth
from Orange.statistics import distribution, contingency
Expand Down Expand Up @@ -201,26 +201,26 @@ def __init__(self):
callback=self._on_set_smoothing, createLabel=False)
self.l_smoothing_r = gui.widgetLabel(box2, "Precise")

self.cb_disc_cont = gui.checkBox(
gui.checkBox(
gui.indentedBox(box, sep=4),
self, "disc_cont", "Bin numeric variables",
callback=self._on_groupvar_idx_changed,
tooltip="Show numeric variables as categorical.")

box = gui.vBox(self.controlArea, "Group by")
self.icons = gui.attributeIconDict
self.groupvarview = gui.comboBox(
gui.comboBox(
box, self, "groupvar_idx",
callback=self._on_groupvar_idx_changed,
valueType=str, contentsLength=12)
box2 = gui.indentedBox(box, sep=4)
self.cb_rel_freq = gui.checkBox(
gui.checkBox(
box2, self, "relative_freq", "Show relative frequencies",
callback=self._on_relative_freq_changed,
tooltip="Normalize probabilities so that probabilities "
"for each group-by value sum to 1.")
gui.separator(box2)
self.cb_prob = gui.comboBox(
gui.comboBox(
box2, self, "show_prob", label="Show probabilities:",
orientation=Qt.Horizontal,
callback=self._on_relative_freq_changed,
Expand Down Expand Up @@ -289,13 +289,14 @@ def set_data(self, data):
self.varmodel[:] = list(domain.variables) + \
[meta for meta in domain.metas
if meta.is_continuous or meta.is_discrete]
self.groupvarview.clear()
groupvarview = self.controls.groupvar_idx
groupvarview.clear()
self.groupvarmodel = \
["(None)"] + [var for var in domain.variables if var.is_discrete] + \
[meta for meta in domain.metas if meta.is_discrete]
self.groupvarview.addItem("(None)")
groupvarview.addItem("(None)")
for var in self.groupvarmodel[1:]:
self.groupvarview.addItem(self.icons[var], var.name)
groupvarview.addItem(self.icons[var], var.name)
if domain.has_discrete_class:
self.groupvar_idx = \
self.groupvarmodel[1:].index(domain.class_var) + 1
Expand All @@ -316,17 +317,18 @@ def clear(self):
self.groupvar_idx = 0
self._legend.clear()
self._legend.hide()
self.groupvarview.clear()
self.cb_prob.clear()
self.controls.groupvar_idx.clear()
self.controls.show_prob.clear()

def _setup_smoothing(self):
if not self.disc_cont and self.var and self.var.is_continuous:
self.cb_disc_cont.setText("Bin numeric variables")
self.controls.disc_cont.setText("Bin numeric variables")
self.l_smoothing_l.setText("Smooth")
self.l_smoothing_r.setText("Precise")
else:
self.cb_disc_cont.setText("Bin numeric variables into {} bins".
format(self.bins[self.smoothing_index]))
self.controls.disc_cont.setText(
"Bin numeric variables into {} bins".
format(self.bins[self.smoothing_index]))
self.l_smoothing_l.setText(" " + str(self.bins[0]))
self.l_smoothing_r.setText(" " + str(self.bins[-1]))

Expand All @@ -346,10 +348,11 @@ def _setup(self):
self.var = self.varmodel[varidx]
if self.groupvar_idx > 0:
self.cvar = self.groupvarmodel[self.groupvar_idx]
self.cb_prob.clear()
self.cb_prob.addItem("(None)")
self.cb_prob.addItems(self.cvar.values)
self.cb_prob.addItem("(All)")
prob = self.controls.show_prob
prob.clear()
prob.addItem("(None)")
prob.addItems(self.cvar.values)
prob.addItem("(All)")
self.show_prob = min(max(self.show_prob, 0),
len(self.cvar.values) + 1)
data = self.data
Expand Down Expand Up @@ -617,9 +620,9 @@ def set_left_axis_name(self):
leftaxis.resizeEvent()

def enable_disable_rel_freq(self):
self.cb_prob.setDisabled(self.var is None or self.cvar is None)
self.cb_rel_freq.setDisabled(
self.var is None or self.cvar is None)
disable = self.var is None or self.cvar is None
self.controls.show_prob.setDisabled(disable)
self.controls.relative_freq.setDisabled(disable)

def _on_variable_idx_changed(self):
self.variable_idx = selected_index(self.varview)
Expand All @@ -638,6 +641,7 @@ def onDeleteWidget(self):
def get_widget_name_extension(self):
if self.variable_idx >= 0:
return self.varmodel[self.variable_idx]
return None

def send_report(self):
self.plotview.scene().setSceneRect(self.plotview.sceneRect())
Expand All @@ -648,7 +652,7 @@ def send_report(self):
self.varmodel[self.variable_idx])
if self.groupvar_idx:
group_var = self.groupvarmodel[self.groupvar_idx]
prob = self.cb_prob
prob = self.controls.show_prob
indiv_probs = 0 < prob.currentIndex() < prob.count() - 1
if not indiv_probs or self.relative_freq:
text += " grouped by '{}'".format(group_var)
Expand Down Expand Up @@ -773,7 +777,7 @@ def weighted_std(a, axis=None, weights=None, ddof=0):
return numpy.sqrt(mean_sq_diff)


def weighted_quantiles(a, prob=[0.25, 0.5, 0.75], alphap=0.4, betap=0.4,
def weighted_quantiles(a, prob=(0.25, 0.5, 0.75), alphap=0.4, betap=0.4,
axis=None, weights=None):
a = numpy.asarray(a)
prob = numpy.asarray(prob)
Expand Down
43 changes: 8 additions & 35 deletions Orange/widgets/visualize/owheatmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ def gamma_fun(x, gamma):
)


class RowPart(RowPart):
class RowPart(RowPart): # pylint: disable=function-redefined
"""
A row group
Expand Down Expand Up @@ -336,7 +336,7 @@ def cluster_ord(self):
)


class ColumnPart(ColumnPart):
class ColumnPart(ColumnPart): # pylint: disable=function-redefined
"""
A column group
Expand Down Expand Up @@ -450,7 +450,7 @@ def __init__(self):
super().__init__()

# set default settings
self.SpaceX = 10
self.space_x = 10

self.colorSettings = None
self.selectedSchemaIndex = 0
Expand Down Expand Up @@ -943,7 +943,7 @@ def setup_scene(self, parts, data):
widget.layoutDidActivate.connect(self.__update_selection_geometry)

grid = QGraphicsGridLayout()
grid.setSpacing(self.SpaceX)
grid.setSpacing(self.space_x)
self.heatmap_scene.addItem(widget)

N, M = len(parts.rows), len(parts.columns)
Expand Down Expand Up @@ -1250,14 +1250,6 @@ def offset(hm):
annot[1].setContentsMargins(left_offset, top, right, bottom)

def __update_clustering_enable_state(self, data):
def enable(item, state):
"""Set QStandardItem's enabled state to `state`."""
flags = item.flags()
if state:
item.setFlags(flags | Qt.ItemIsEnabled)
else:
item.setFlags(flags & ~Qt.ItemIsEnabled)

if data is not None:
N = len(data)
M = len(data.domain.attributes)
Expand Down Expand Up @@ -1333,7 +1325,7 @@ def update_grid_spacing(self):
"""
if self.scene.widget:
layout = self.scene.widget.layout()
layout.setSpacing(self.SpaceX)
layout.setSpacing(self.space_x)
self.__fixup_grid_layout()

def update_lowslider(self):
Expand Down Expand Up @@ -1870,7 +1862,6 @@ def select_from_dendrogram(self, dendrogram, key):
append = (key & Qt.ControlModifier)
self.selection_manager.selection_add(
start, end, heatmap, clear=clear, remove=remove, append=append)
return

def mousePressEvent(self, event):
pos = event.scenePos()
Expand All @@ -1895,7 +1886,6 @@ def mouseReleaseEvent(self, event):
pos = event.scenePos()
heatmap = self.heatmap_at_pos(pos)
if heatmap and event.button() == Qt.LeftButton and self.__selecting:
row, _ = heatmap.cell_at(heatmap.mapFromScene(pos))
self.selection_manager.selection_finish(heatmap, event)

if event.button() == Qt.LeftButton and self.__selecting:
Expand Down Expand Up @@ -1956,7 +1946,7 @@ def setText(self, text):

class GraphicsSimpleTextList(QGraphicsWidget):
"""A simple text list widget."""
def __init__(self, labels=[], orientation=Qt.Vertical, parent=None):
def __init__(self, labels=(), orientation=Qt.Vertical, parent=None):
super().__init__(parent)
self.label_items = []
self.orientation = orientation
Expand Down Expand Up @@ -2310,22 +2300,6 @@ def combined_to_ranges(self, comb_ranges):
def update_selection_rects(self):
""" Update the selection rects.
"""
def continuous_ranges(selections):
""" Group continuous ranges
"""
selections = iter(selections)
start = end = next(selections)
try:
while True:
new_end = next(selections)
if new_end > end + 1:
yield start, end
start = end = new_end
else:
end = new_end
except StopIteration:
yield start, end

def group_selections(selections):
"""Group selections along with heatmaps.
"""
Expand Down Expand Up @@ -2385,16 +2359,15 @@ def generate(sep, ellidetemplate, values):
yield i, itertools.islice(parts, i + 1), length, ellide

best = None
for i, parts, length, ellide in generate(sep, ellidetemplate, values):
for _, parts, length, ellide in generate(sep, ellidetemplate, values):
if length > maxlen:
if best is None:
best = sep.join(parts) + ellide
return best
fulllen = length + len(ellide)
if fulllen < maxlen or best is None:
best = sep.join(parts) + ellide
else:
return best
return best


if __name__ == "__main__": # pragma: no cover
Expand Down
1 change: 1 addition & 0 deletions Orange/widgets/visualize/owlinearprojection.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ def compute_score(self, state):
n_neighbors = min(self.minK, len(ec) - 1)
knn = NearestNeighbors(n_neighbors=n_neighbors).fit(ec)
ind = knn.kneighbors(return_distance=False)
# pylint: disable=invalid-unary-operand-type
if self.attr_color.is_discrete:
return -np.sum(y[ind] == y.reshape(-1, 1)) / n_neighbors / len(y)
return -r2_score(y, np.mean(y[ind], axis=1)) * (len(y) / len(data))
Expand Down
11 changes: 7 additions & 4 deletions Orange/widgets/visualize/ownomogram.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ def _get_tooltip_labels_with_percentages(self):
for i, val in enumerate(self.tooltip_values):
if val > self.value:
break
# pylint: disable=undefined-loop-variable
diff = self.tooltip_values[i] - self.tooltip_values[i - 1]
p1 = 0 if diff < 1e-6 else (-self.value + self.tooltip_values[i]) / diff
return [(self.tooltip_labels[i - 1].replace("<", "&lt;"), abs(p1)),
Expand Down Expand Up @@ -1007,14 +1008,15 @@ def key(x):

def create_footer_nomogram(self, probs_text, d, minimums,
max_width, name_offset):
# pylint: disable=invalid-unary-operand-type
eps, d_ = 0.05, 1
k = - np.log(self.p / (1 - self.p)) if self.p is not None else - self.b0
min_sum = k[self.target_class_index] - np.log((1 - eps) / eps)
max_sum = k[self.target_class_index] - np.log(eps / (1 - eps))
if self.align == OWNomogram.ALIGN_LEFT:
max_sum = max_sum - sum(minimums)
min_sum = min_sum - sum(minimums)
for i in range(len(k)):
for i in range(len(k)): # pylint: disable=consider-using-enumerate
k[i] = k[i] - sum([min(q) for q in [p[i] for p in self.points]])
if self.scale == OWNomogram.POINT_SCALE:
min_sum *= d
Expand Down Expand Up @@ -1080,13 +1082,13 @@ def set_feature_marker_values(self):
marker_values = self.scale_marker_values(self.feature_marker_values)

invisible_sum = 0
for i in range(len(marker_values)):
for i, marker in enumerate(marker_values):
try:
item = self.feature_items[i]
except KeyError:
invisible_sum += marker_values[i]
invisible_sum += marker
else:
item.dot.move_to_val(marker_values[i])
item.dot.move_to_val(marker)

item.dot.probs_dot.move_to_sum(invisible_sum)

Expand Down Expand Up @@ -1171,6 +1173,7 @@ def get_ruler_values(start, stop, max_width, round_to_nearest=True):
def get_points_from_coeffs(current_value, coefficients, possible_values):
if np.isnan(possible_values).any():
return 0
# pylint: disable=undefined-loop-variable
indices = np.argsort(possible_values)
sorted_values = possible_values[indices]
sorted_coefficients = coefficients[indices]
Expand Down
2 changes: 0 additions & 2 deletions Orange/widgets/visualize/owpythagorastree.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,12 +403,10 @@ class TreeGraphicsView(
):
"""QGraphicsView that contains all functionality we will use to display
tree."""
pass


class TreeGraphicsScene(UpdateItemsOnSelectGraphicsScene):
"""QGraphicsScene that the tree uses."""
pass


if __name__ == "__main__": # pragma: no cover
Expand Down
Loading

0 comments on commit 74515ca

Please sign in to comment.