def _handleHelpEvent(self, event): # Handle a help event for the plot viewbox = self.graph.getViewBox() pos = viewbox.mapToView(viewbox.mapFromScene(event.scenePos())) logr = pos.x() logp = pos.y() text = "" points = [] if self.graph._item is not None: points = self.graph._item.pointsAt(pos) if points: point = points[0] pos = point.pos() logr, logp = pos.x(), pos.y() index = point.data() text = ("<b>{index}</b><hr/>" "log<sub>2</sub>(ratio): {logr:.5f}<br/>" "p-value: {p:.5f}").format(logr=logr, p=10 ** -logp, index=index) if len(points) > 1: text += "<br/>... (and {} not shown)".format(len(points) - 1) else: text = "" QToolTip.showText(event.screenPos(), text, widget=self.graph) return True
def help_event(self, event): if self.scatterplot_item is None: return False act_pos = self.scatterplot_item.mapFromScene(event.scenePos()) points = self.scatterplot_item.pointsAt(act_pos) text = "" vars = self.master.model_selected if len(points): for i, p in enumerate(points): index = p.data() text += "Attributes:\n" text += "".join( " {} = {}\n".format(attr.name, self.data[index][attr]) for attr in vars) if len(vars[:]) > 10: text += " ... and {} others\n\n".format(len(vars[:]) - 12) # class_var is always: text += "Class:\n {} = {}\n".format(self.domain.class_var.name, self.data[index][self.data.domain.class_var]) if i < len(points) - 1: text += '------------------\n' text = ('<span style="white-space:pre">{}</span>'.format(escape(text))) QToolTip.showText(event.screenPos(), text, widget=self.plot_widget) return True return False
def help_event(self, event): if self.scatterplot_item is None: return False domain = self.data.domain PARTS = (("Class", "Classes", 4, domain.class_vars), ("Meta", "Metas", 4, domain.metas), ("Feature", "Features", 10, domain.attributes)) def format_val(var, point_data, bold=False): text = escape('{} = {}'.format(var.name, point_data[var])) if bold: text = "<b>{}</b>".format(text) return text def show_part(point_data, singular, plural, max_shown, vars): cols = [format_val(var, point_data) for var in vars[:max_shown + 2] if vars == domain.class_vars or var not in (self.shown_x, self.shown_y)][:max_shown] if not cols: return "" n_vars = len(vars) if n_vars > max_shown: cols[-1] = "... and {} others".format(n_vars - max_shown + 1) return \ "<br/><b>{}</b>:<br/>".format(singular if n_vars < 2 else plural) \ + "<br/>".join(cols) def point_data(p): point_data = self.data[p.data()] text = "<br/>".join( format_val(var, point_data, bold=self.tooltip_shows_all) for var in (self.shown_x, self.shown_y)) if self.tooltip_shows_all: text += "<br/>" + \ "".join(show_part(point_data, *columns) for columns in PARTS) return text act_pos = self.scatterplot_item.mapFromScene(event.scenePos()) points = self.scatterplot_item.pointsAt(act_pos) if len(points): if len(points) > MAX_POINTS_IN_TOOLTIP: text = "{} instances<hr/>{}<hr/>...".format( len(points), "<hr/>".join(point_data(point) for point in points[:MAX_POINTS_IN_TOOLTIP]) ) else: text = "<hr/>".join(point_data(point) for point in points) QToolTip.showText(event.screenPos(), text, widget=self.plot_widget) return True else: return False
def help_event(self, ev): in_graph_coor = self.plot.mapSceneToView(ev.scenePos()) ctooltip = [] for vb, item in self.tooltip_items: if isinstance(item, pg.PlotCurveItem) and item.mouseShape().contains(vb.mapSceneToView(ev.scenePos())): ctooltip.append(item.tooltip) elif isinstance(item, DistributionBarItem) and item.boundingRect().contains(vb.mapSceneToView(ev.scenePos())): ctooltip.append(item.tooltip) if ctooltip: QToolTip.showText(ev.screenPos(), "\n\n".join(ctooltip), widget=self.plotview) return True return False
def helpEvent(self, event, view, option, index): # reimplemented # NOTE: This is a slot in Qt4, but is a virtual func in Qt5 value = index.data(Qt.EditRole) if isinstance(value, tuple) and len(value) == 2: try: tooltip = tool_tip(value) except ValueError: return False QToolTip.showText(event.globalPos(), tooltip, view) return True else: return super().helpEvent(event, view, option, index)
def help_event(self, event): """ Create a `QToolTip` for the point hovered by the mouse """ if self.scatterplot_item is None: return False act_pos = self.scatterplot_item.mapFromScene(event.scenePos()) point_data = [p.data() for p in self.scatterplot_item.pointsAt(act_pos)] text = self.master.get_tooltip(point_data) if text: QToolTip.showText(event.screenPos(), text, widget=self.plot_widget) return True else: return False
def event(self, event): # type: (QEvent) -> bool if event.type() == QEvent.ToolTip and self.toolTip(): action = self.defaultAction() if action is not None: text = "<span>{}</span> <kbd>{}</kbd>".format( action.toolTip(), action.shortcut().toString(QKeySequence.NativeText) ) QToolTip.showText(event.globalPos(), text) else: QToolTip.hideText() return True else: return super().event(event)
def help_event(self, ev): pos = self.plot.vb.mapSceneToView(ev.scenePos()) sel = self._points_at_pos(pos) prepared = [] if sel is not None: data, vals, points = self.data[sel], self.data_values[sel], self.data_points[sel] for d, v, p in zip(data, vals, points): basic = "({}, {}): {}".format(p[0], p[1], v) variables = [v for v in self.data.domain.metas + self.data.domain.class_vars if v not in [self.attr_x, self.attr_y]] features = ['{} = {}'.format(attr.name, d[attr]) for attr in variables] prepared.append("\n".join([basic] + features)) text = "\n\n".join(prepared) if text: text = ('<span style="white-space:pre">{}</span>' .format(escape(text))) QToolTip.showText(ev.screenPos(), text, widget=self.plotview) return True else: return False
def help_event(self, ev): pos = self.plot.vb.mapSceneToView(ev.scenePos()) sel, wavenumber_ind = self._points_at_pos(pos) prepared = [] if sel is not None: prepared.append(str(self.wavenumbers[wavenumber_ind])) for d in self.data[sel]: variables = [v for v in self.data.domain.metas + self.data.domain.class_vars if v not in [self.attr_x]] features = ['{} = {}'.format(attr.name, d[attr]) for attr in variables] features.append('value = {}'.format(d[wavenumber_ind])) prepared.append("\n".join(features)) text = "\n\n".join(prepared) if text: text = ('<span style="white-space:pre">{}</span>' .format(escape(text))) QToolTip.showText(ev.screenPos(), text, widget=self.plotview) return True else: return False
def mouseDragEvent(self, ev, axis=None): master = self.graph.master if master.data is None or master.graph.data is None: super().mouseDragEvent(ev, axis) return pos = self.childGroup.mapFromParent(ev.pos()) points = master.plotdata.points np_pos = np.array([[pos.x(), pos.y()]]) distances = distance.cdist(np_pos, points[:, :2]) is_near = np.min(distances) < 0.1 if ev.button() != Qt.LeftButton or (ev.start and not is_near): self.mouse_state = 2 if self.mouse_state == 2: if ev.finish: self.mouse_state = 0 super().mouseDragEvent(ev, axis) return ev.accept() if ev.start: self.setCursor(Qt.ClosedHandCursor) self.mouse_state = 1 self.point_i = np.argmin(distances) master.randomize_indices() if self.mouse_state == 1: if ev.finish: self.setCursor(Qt.ArrowCursor) self.mouse_state = 0 angle = np.arctan2(pos.y(), pos.x()) QToolTip.showText( QPoint(ev.screenPos().x(), ev.screenPos().y()), "{:.2f}".format(np.rad2deg(angle))) points[self.point_i][0] = np.cos(angle) points[self.point_i][1] = np.sin(angle) if ev.finish: master.setup_plot() master.commit() else: master.manual_move() self.graph.show_arc_arrow(pos.x(), pos.y())
def mouseMoveEvent(self, e): if hasattr(self, "pressed_arrow"): canvas_position = self.mapToScene(e.pos()) y = min(1, max(0, self.inv_transform(yLeft, canvas_position.y()))) index, pos = self.pressed_arrow attr = self.domain[self.attributes[index]] old_condition = self.selection_conditions.get(attr.name, [0, 1]) old_condition[pos] = y self.selection_conditions[attr.name] = old_condition self.update_data(self.attributes, self.visualized_mid_labels) if attr.is_continuous: val = self.attr_values[attr][0] + old_condition[pos] * ( self.attr_values[attr][1] - self.attr_values[attr][0]) strVal = attr.name + "= %.2f" % val QToolTip.showText(e.globalPos(), strVal) if self.sendSelectionOnUpdate and self.auto_send_selection_callback: self.auto_send_selection_callback() else: OWPlot.mouseMoveEvent(self, e)
def event(self, ev): if ev.type() == QEvent.ToolTip: x = self.inv_transform(xBottom, ev.pos().x()) y = self.inv_transform(yLeft, ev.pos().y()) canvas_position = self.mapToScene(ev.pos()) x_float = self.inv_transform(xBottom, canvas_position.x()) contact, (index, pos) = self.testArrowContact(int(round(x_float)), canvas_position.x(), canvas_position.y()) if contact: attr = self.domain[self.attributes[index]] if attr.is_continuous: condition = self.selection_conditions.get(attr.name, [0, 1]) val = self.attr_values[attr][0] + condition[pos] * ( self.attr_values[attr][1] - self.attr_values[attr][0]) str_val = attr.name + "= %%.%df" % attr.number_of_decimals % val QToolTip.showText(ev.globalPos(), str_val) else: for curve in self.items(): if type(curve) == PolygonCurve and \ curve.boundingRect().contains(x, y) and \ getattr(curve, "tooltip", None): (name, value, total, dist) = curve.tooltip count = sum([v[1] for v in dist]) if count == 0: continue tooltip_text = "Attribute: <b>%s</b><br>Value: <b>%s</b><br>" \ "Total instances: <b>%i</b> (%.1f%%)<br>" \ "Class distribution:<br>" % ( name, value, count, 100.0 * count / float(total)) for (val, n) in dist: tooltip_text += " <b>%s</b> : <b>%i</b> (%.1f%%)<br>" % ( val, n, 100.0 * float(n) / float(count)) QToolTip.showText(ev.globalPos(), tooltip_text[:-4]) elif ev.type() == QEvent.MouseMove: QToolTip.hideText() return OWPlot.event(self, ev)
def help_event(self, event): if self.scatterplot_item is None: return False act_pos = self.scatterplot_item.mapFromScene(event.scenePos()) points = self.scatterplot_item.pointsAt(act_pos) text = "" if len(points): for i, p in enumerate(points): index = p.data() text += "Attributes:\n" if self.tooltip_shows_all and \ len(self.domain.attributes) < 30: text += "".join( ' {} = {}\n'.format(attr.name, self.data[index][attr]) for attr in self.domain.attributes) else: text += ' {} = {}\n {} = {}\n'.format( self.shown_x, self.data[index][self.shown_x], self.shown_y, self.data[index][self.shown_y]) if self.tooltip_shows_all: text += " ... and {} others\n\n".format( len(self.domain.attributes) - 2) if self.domain.class_var: text += 'Class:\n {} = {}\n'.format( self.domain.class_var.name, self.data[index][self.data.domain.class_var]) if i < len(points) - 1: text += '------------------\n' text = ('<span style="white-space:pre">{}</span>' .format(escape(text))) QToolTip.showText(event.screenPos(), text, widget=self.plot_widget) return True else: return False
def help_event(self, ev): pos = self.plot.vb.mapSceneToView(ev.scenePos()) sel, wavenumber_ind = self._points_at_pos(pos) prepared = [] if sel is not None: prepared.append(str(self.wavenumbers[wavenumber_ind])) for d in self.data[sel]: variables = [ v for v in self.data.domain.metas + self.data.domain.class_vars if v not in [self.attr_x] ] features = [ '{} = {}'.format(attr.name, d[attr]) for attr in variables ] features.append('value = {}'.format(d[wavenumber_ind])) prepared.append("\n".join(features)) text = "\n\n".join(prepared) if text: text = ('<span style="white-space:pre">{}</span>'.format( escape(text))) QToolTip.showText(ev.screenPos(), text, widget=self.plotview) return True else: return False
def _on_mouse_moved(self, pos): target = self.target_index selected = self.selected_classifiers curves = [(clf_idx, self.plot_curves(target, clf_idx)) for clf_idx in selected ] # type: List[Tuple[int, PlotCurves]] valid_thresh, valid_clf = [], [] pt, ave_mode = None, self.roc_averaging for clf_idx, crv in curves: if self.roc_averaging == OWROCAnalysis.Merge: curve = crv.merge() elif self.roc_averaging == OWROCAnalysis.Vertical: curve = crv.avg_vertical() elif self.roc_averaging == OWROCAnalysis.Threshold: curve = crv.avg_threshold() else: # currently not implemented for 'Show Individual Curves' return sp = curve.curve_item.childItems()[0] # type: pg.ScatterPlotItem act_pos = sp.mapFromScene(pos) pts = sp.pointsAt(act_pos) if pts: mouse_pt = pts[0].pos() if self._tooltip_cache: cache_pt, cache_thresh, cache_clf, cache_ave = self._tooltip_cache curr_thresh, curr_clf = [], [] if np.linalg.norm(mouse_pt - cache_pt) < 10e-6 \ and cache_ave == self.roc_averaging: mask = np.equal(cache_clf, clf_idx) curr_thresh = np.compress(mask, cache_thresh).tolist() curr_clf = np.compress(mask, cache_clf).tolist() else: QToolTip.showText(QCursor.pos(), "") self._tooltip_cache = None if curr_thresh: valid_thresh.append(*curr_thresh) valid_clf.append(*curr_clf) pt = cache_pt continue curve_pts = curve.curve.points roc_points = np.column_stack((curve_pts.fpr, curve_pts.tpr)) diff = np.subtract(roc_points, mouse_pt) # Find closest point on curve and save the corresponding threshold idx_closest = np.argmin(np.linalg.norm(diff, axis=1)) thresh = curve_pts.thresholds[idx_closest] if not np.isnan(thresh): valid_thresh.append(thresh) valid_clf.append(clf_idx) pt = [ curve_pts.fpr[idx_closest], curve_pts.tpr[idx_closest] ] if valid_thresh: clf_names = self.classifier_names msg = "Thresholds:\n" + "\n".join([ "({:s}) {:.3f}".format(clf_names[i], thresh) for i, thresh in zip(valid_clf, valid_thresh) ]) QToolTip.showText(QCursor.pos(), msg) self._tooltip_cache = (pt, valid_thresh, valid_clf, ave_mode)
def is_valid_url(self, url): if is_valid_url(url): self.Error.invalid_url.clear() return True self.Error.invalid_url() QToolTip.showText(self.combo.mapToGlobal(QPoint(0, 0)), self.combo.toolTip())
def _show_tooltip(self, ev): pos = self.childGroup.mapFromParent(ev.pos()) angle = np.arctan2(pos.y(), pos.x()) point = QPoint(ev.screenPos().x(), ev.screenPos().y()) QToolTip.showText(point, "{:.2f}".format(np.rad2deg(angle)))
def _on_mouse_moved(self, pos): target = self.target_index selected = self.selected_classifiers curves = [(clf_idx, self.plot_curves(target, clf_idx)) for clf_idx in selected] # type: List[Tuple[int, plot_curves]] valid_thresh, valid_clf = [], [] pt, ave_mode = None, self.roc_averaging for clf_idx, crv in curves: if self.roc_averaging == OWROCAnalysis.Merge: curve = crv.merge() elif self.roc_averaging == OWROCAnalysis.Vertical: curve = crv.avg_vertical() elif self.roc_averaging == OWROCAnalysis.Threshold: curve = crv.avg_threshold() else: # currently not implemented for 'Show Individual Curves' return sp = curve.curve_item.childItems()[0] # type: pg.ScatterPlotItem act_pos = sp.mapFromScene(pos) pts = sp.pointsAt(act_pos) if len(pts) > 0: mouse_pt = pts[0].pos() if self._tooltip_cache: cache_pt, cache_thresh, cache_clf, cache_ave = self._tooltip_cache curr_thresh, curr_clf = [], [] if numpy.linalg.norm(mouse_pt - cache_pt) < 10e-6 \ and cache_ave == self.roc_averaging: mask = numpy.equal(cache_clf, clf_idx) curr_thresh = numpy.compress(mask, cache_thresh).tolist() curr_clf = numpy.compress(mask, cache_clf).tolist() else: QToolTip.showText(QCursor.pos(), "") self._tooltip_cache = None if curr_thresh: valid_thresh.append(*curr_thresh) valid_clf.append(*curr_clf) pt = cache_pt continue curve_pts = curve.curve.points roc_points = numpy.column_stack((curve_pts.fpr, curve_pts.tpr)) diff = numpy.subtract(roc_points, mouse_pt) # Find closest point on curve and save the corresponding threshold idx_closest = numpy.argmin(numpy.linalg.norm(diff, axis=1)) thresh = curve_pts.thresholds[idx_closest] if not numpy.isnan(thresh): valid_thresh.append(thresh) valid_clf.append(clf_idx) pt = [curve_pts.fpr[idx_closest], curve_pts.tpr[idx_closest]] if valid_thresh: clf_names = self.classifier_names msg = "Thresholds:\n" + "\n".join(["({:s}) {:.3f}".format(clf_names[i], thresh) for i, thresh in zip(valid_clf, valid_thresh)]) QToolTip.showText(QCursor.pos(), msg) self._tooltip_cache = (pt, valid_thresh, valid_clf, ave_mode)