Exemple #1
0
 def strudel(self, dist):
     attr = self.attribute
     ss = np.sum(dist)
     box = QGraphicsItemGroup()
     if ss < 1e-6:
         QGraphicsRectItem(0, -10, 1, 10, box)
     cum = 0
     for i, v in enumerate(dist):
         if v < 1e-6:
             continue
         if self.stretched:
             v /= ss
         v *= self.scale_x
         rect = QGraphicsRectItem(cum + 1, -6, v - 2, 12, box)
         rect.setBrush(QBrush(QColor(*attr.colors[i])))
         rect.setPen(QPen(Qt.NoPen))
         if self.stretched:
             tooltip = "{}: {:.2f}%".format(attr.values[i],
                                            100 * dist[i] / sum(dist))
         else:
             tooltip = "{}: {}".format(attr.values[i], int(dist[i]))
         rect.setToolTip(tooltip)
         text = QGraphicsTextItem(attr.values[i])
         box.addToGroup(text)
         cum += v
     return box
    def set_data(self, x_data: float, std: float):
        self._x_data = x_data
        self._std = std

        item = QGraphicsRectItem(0, 0, 0, self._height * self.MEAN_RATIO)
        item.setPen(self._pen)
        item.setBrush(QBrush(QColor("#1f77b4")))
        self._group.addToGroup(item)

        item = QGraphicsRectItem(0, 0, 0, self._height * self.STD_RATIO)
        item.setPen(self._pen)
        item.setBrush(QBrush(QColor("#444")))
        self._group.addToGroup(item)

        self.set_height(0)
Exemple #3
0
    def __init__(self, palette, parent, orientation):
        super().__init__(parent)

        self.__gradient = QLinearGradient()
        num_colors = len(palette)
        for idx, stop in enumerate(palette):
            self.__gradient.setColorAt(idx * (1. / (num_colors - 1)), stop)

        # We need to tell the gradient where it's start and stop points are
        self.__gradient.setStart(QPointF(0, 0))
        if orientation == Qt.Vertical:
            final_stop = QPointF(0, self.GRADIENT_HEIGHT)
        else:
            final_stop = QPointF(self.GRADIENT_HEIGHT, 0)
        self.__gradient.setFinalStop(final_stop)

        # Get the appropriate rectangle dimensions based on orientation
        if orientation == Qt.Vertical:
            width, height = self.GRADIENT_WIDTH, self.GRADIENT_HEIGHT
        elif orientation == Qt.Horizontal:
            width, height = self.GRADIENT_HEIGHT, self.GRADIENT_WIDTH

        self.__rect_item = QGraphicsRectItem(0, 0, width, height, self)
        self.__rect_item.setPen(QPen(QColor(0, 0, 0, 0)))
        self.__rect_item.setBrush(QBrush(self.__gradient))
        self._size_hint = QSizeF(self.__rect_item.boundingRect().size())
Exemple #4
0
    def _create_drag_tooltip(self, scene):
        tip_parts = [(Qt.ShiftModifier, "Shift: Add group"),
                     (Qt.ShiftModifier + Qt.ControlModifier,
                      "Shift-{}: Append to group".format(
                          "Cmd" if sys.platform == "darwin" else "Ctrl")),
                     (Qt.AltModifier, "Alt: Remove")]
        all_parts = ", ".join(part for _, part in tip_parts)
        self.tiptexts = {
            int(modifier): all_parts.replace(part, "<b>{}</b>".format(part))
            for modifier, part in tip_parts
        }
        self.tiptexts[0] = all_parts

        self.tip_textitem = text = QGraphicsTextItem()
        # Set to the longest text
        text.setHtml(self.tiptexts[Qt.ShiftModifier + Qt.ControlModifier])
        text.setPos(4, 2)
        r = text.boundingRect()
        rect = QGraphicsRectItem(0, 0, r.width() + 8, r.height() + 4)
        rect.setBrush(QColor(224, 224, 224, 212))
        rect.setPen(QPen(Qt.NoPen))
        self.update_tooltip(Qt.NoModifier)

        scene.drag_tooltip = scene.createItemGroup([rect, text])
        scene.drag_tooltip.hide()
Exemple #5
0
    def box_group(self, stat, height=20):
        def line(x0, y0, x1, y1, *args):
            return QGraphicsLineItem(x0 * scale_x, y0, x1 * scale_x, y1, *args)

        scale_x = self.scale_x
        box = QGraphicsItemGroup()
        whisker1 = line(stat.a_min, -1.5, stat.a_min, 1.5, box)
        whisker2 = line(stat.a_max, -1.5, stat.a_max, 1.5, box)
        vert_line = line(stat.a_min, 0, stat.a_max, 0, box)
        mean_line = line(stat.mean, -height / 3, stat.mean, height / 3, box)
        for it in (whisker1, whisker2, mean_line):
            it.setPen(self._pen_paramet)
        vert_line.setPen(self._pen_dotted)
        var_line = line(stat.mean - stat.dev, 0, stat.mean + stat.dev, 0, box)
        var_line.setPen(self._pen_paramet)

        if stat.q25 is not None and stat.q75 is not None:
            mbox = QGraphicsRectItem(stat.q25 * scale_x, -height / 2,
                                     (stat.q75 - stat.q25) * scale_x, height,
                                     box)
            mbox.setBrush(self._box_brush)
            mbox.setPen(QPen(Qt.NoPen))
            mbox.setZValue(-200)

        if stat.median is not None:
            median_line = line(stat.median, -height / 2, stat.median,
                               height / 2, box)
            median_line.setPen(self._pen_median)
            median_line.setZValue(-150)

        return box
Exemple #6
0
 def test_other_exporter(self):
     sc = QGraphicsScene()
     sc.addItem(QGraphicsRectItem(0, 0, 3, 3))
     with patch("orangewidget.io.ImgFormat._get_exporter", Mock()) as mfn:
         with self.assertRaises(Exception):
             imgio.ImgFormat.write("", sc)
         self.assertEqual(0, mfn.call_count)
Exemple #7
0
    def draw_attribute(self, y, atr_name, atr_val, atr_contrib, error):
        fix = (self.offset_left + self.atr_area_w)
        """vertical line where x = 0"""
        self.scene.addLine(0 + fix, y, 0 + fix, y +
                           self.rect_height, self.black_pen)
        """borders"""
        self.scene.addLine(self.offset_left,
                           y, fix + self.atr_area_w, y, self.gray_pen)
        self.scene.addLine(self.offset_left, y + self.rect_height,
                           fix + self.atr_area_w, y + self.rect_height, self.gray_pen)

        if atr_name is not None and atr_val is not None and atr_contrib is not None:
            atr_contrib_x = atr_contrib * self.scale + fix
            error_x = error * self.scale

            padded_rect = self.rect_height - 2 * self.offset_y
            len_rec = 2 * error_x
            graphed_rect = QGraphicsRectItem(
                atr_contrib_x - error_x, y + self.offset_y, len_rec, padded_rect)
            graphed_rect.setBrush(self.brush)
            graphed_rect.setPen(QPen(Qt.NoPen))
            self.scene.addItem(graphed_rect)
            """vertical line marks calculated contribution of attribute"""
            self.atr_line = self.scene.addLine(atr_contrib_x, y + self.offset_y + 2, atr_contrib_x,
                                               y + self.rect_height - self.offset_y - 2, self.blue_pen)

            """atr name and value on the left"""
            self.place_left(QGraphicsSimpleTextItem(
                atr_val, None), y + self.rect_height/2)
            self.place_left_edge(QGraphicsSimpleTextItem(
                atr_name, None), y + self.rect_height/2)

            """atr score on the right"""
            self.place_right(self.format_marking(
                atr_contrib), y + self.rect_height/2)
Exemple #8
0
    def show_selection(self):
        self.plot_mark.clear()
        if not self.is_valid:  # though if it's not, selection is empty anyway
            return

        blue = QColor(Qt.blue)
        pen = QPen(QBrush(blue), 3)
        pen.setCosmetic(True)
        brush = QBrush(blue.lighter(190))

        for group in self.grouped_selection():
            group = list(group)
            left_idx, right_idx = group[0], group[-1]
            left_pad, right_pad = self._determine_padding(left_idx, right_idx)
            x0 = self.bar_items[left_idx].x0 - left_pad
            x1 = self.bar_items[right_idx].x1 + right_pad
            item = QGraphicsRectItem(x0, 0, x1 - x0, 1)
            item.setPen(pen)
            item.setBrush(brush)
            if self.var.is_continuous:
                valname = self.str_int(
                    x0, x1, not left_idx, right_idx == len(self.bar_items) - 1)
                inside = sum(np.sum(self.bar_items[i].freqs) for i in group)
                total = len(self.valid_data)
                item.setToolTip(
                    "<p style='white-space:pre;'>"
                    f"<b>{escape(valname)}</b>: "
                    f"{inside} ({100 * inside / total:.2f} %)")
            self.plot_mark.addItem(item)
    def mousePressEvent(self, event):
        pos = event.scenePos()
        any_item = self.scene.item_at(pos)
        if not any_item and event.button() & Qt.LeftButton:
            self.modifiers = event.modifiers()
            self.selection_rect = QRectF(pos, QSizeF(0, 0))
            self.rect_item = QGraphicsRectItem(
                self.selection_rect.normalized())

            self.rect_item.setPen(
                QPen(QBrush(QColor(51, 153, 255, 192)), 0.4, Qt.SolidLine,
                     Qt.RoundCap))

            self.rect_item.setBrush(QBrush(QColor(168, 202, 236, 192)))

            self.rect_item.setZValue(-100)

            # Clear the focus if necessary.
            if not self.scene.stickyFocus():
                self.scene.clearFocus()

            if not self.modifiers & Qt.ControlModifier:
                self.scene.clearSelection()

            event.accept()
            return True
        else:
            self.cancel(self.ErrorReason)
            return False
Exemple #10
0
    def __init__(self, color, parent):
        super().__init__(parent)

        height, width = self.SIZE.height(), self.SIZE.width()
        self.__square = QGraphicsRectItem(0, 0, height, width)
        self.__square.setBrush(QBrush(color))
        self.__square.setPen(QPen(QColor(0, 0, 0, 0)))
        self.__square.setParentItem(self)
Exemple #11
0
 def _add_bar(self):
     item = QGraphicsRectItem(0, 0, self.BAR_WIDTH, self.__bar_height)
     gradient = QLinearGradient(0, 0, 0, self.__bar_height)
     gradient.setColorAt(0, QColor(*RGB_HIGH))
     gradient.setColorAt(1, QColor(*RGB_LOW))
     item.setPen(QPen(Qt.NoPen))
     item.setBrush(gradient)
     self.__group.addToGroup(item)
Exemple #12
0
 def set_data(self, value):
     self._x_data = value
     item = QGraphicsRectItem()
     item.setX(0)
     item.setY(self._height / 2 - self._height * 0.5 / 2)
     width = value * self._width / (self._range[1] - self._range[0])
     item.setRect(0, 0, width, self._height * 0.5)
     self._group.addToGroup(item)
 def addSquare(self, size):
     size = np.clip(1.3**np.log2(size**.5), 8, 20)
     item = QGraphicsRectItem(self)
     offset = len(self.childItems())
     item.setRect(offset * 3, offset * 2, size, size)
     item.setPen(QColor('maroon'))
     item.setBrush(QColor('pink'))
     self.selected(False)
     self.addToGroup(item)
Exemple #14
0
 def __init__(self, text, parent):
     QGraphicsObject.__init__(self, parent)
     self.text_item = QGraphicsTextItem(text + ':', self)
     f = self.text_item.font()
     f.setBold(True)
     self.text_item.setFont(f)
     self.rect_item = QGraphicsRectItem(self.text_item.boundingRect(), self)
     self.rect_item.setPen(QPen(Qt.NoPen))
     self.rect_item.stackBefore(self.text_item)
Exemple #15
0
 def test_pdf(self):
     sc = QGraphicsScene()
     sc.addItem(QGraphicsRectItem(0, 0, 20, 20))
     fd, fname = tempfile.mkstemp()
     os.close(fd)
     try:
         imgio.PdfFormat.write_image(fname, sc)
     finally:
         os.unlink(fname)
    def __init__(self, parent):
        super().__init__(parent)
        self.__range = None  # type: Tuple[float]
        self.__value_range = None  # type: Tuple[float]
        self.__model_output = None  # type: float
        self.__base_value = None  # type: float

        self.__group = QGraphicsItemGroup(self)
        low_color, high_color = QColor(*RGB_LOW), QColor(*RGB_HIGH)

        self.__low_item = QGraphicsRectItem()
        self.__low_item.setPen(QPen(low_color))
        self.__low_item.setBrush(QBrush(low_color))

        self.__high_item = QGraphicsRectItem()
        self.__high_item.setPen(QPen(high_color))
        self.__high_item.setBrush(QBrush(high_color))

        self.__low_cover_item = LowCoverItem()
        self.__high_cover_item = HighCoverItem()

        pen = QPen(IndicatorItem.COLOR)
        pen.setStyle(Qt.DashLine)
        pen.setWidth(1)
        self.__model_output_line = QGraphicsLineItem()
        self.__model_output_line.setPen(pen)
        self.__base_value_line = QGraphicsLineItem()
        self.__base_value_line.setPen(pen)

        self.__model_output_ind = IndicatorItem("Model prediction: {}")
        self.__base_value_ind = IndicatorItem("Base value: {}\nThe average "
                                              "prediction for selected class.")

        self.__group.addToGroup(self.__low_item)
        self.__group.addToGroup(self.__high_item)
        self.__group.addToGroup(self.__low_cover_item)
        self.__group.addToGroup(self.__high_cover_item)
        self.__group.addToGroup(self.__model_output_line)
        self.__group.addToGroup(self.__base_value_line)
        self.__group.addToGroup(self.__model_output_ind)
        self.__group.addToGroup(self.__base_value_ind)

        self.__low_parts = []  # type: List[LowPartItem]
        self.__high_parts = []  # type: List[HighPartItem]
Exemple #17
0
    def __init__(self, name, values, scale, name_offset, offset, labels=None):
        super().__init__()

        # leading label
        font = name.document().defaultFont()
        if self.bold_label:
            font.setWeight(QFont.Bold)
        name.setFont(font)
        name.setPos(name_offset, -10)
        name.setParentItem(self)

        # prediction marker
        self.dot = self.DOT_ITEM_CLS(self.dot_r, scale, offset, values[0],
                                     values[-1])
        self.dot.setParentItem(self)

        # line
        line = QGraphicsLineItem(
            min(values) * scale + offset, 0,
            max(values) * scale + offset, 0)
        line.setParentItem(self)

        if labels is None:
            labels = [str(abs(v) if v == -0 else v) for v in values]

        old_x_tick = None
        shown_items = []
        w = QGraphicsSimpleTextItem(labels[0]).boundingRect().width()
        text_finish = values[0] * scale - w + offset - 10
        for i, (label, value) in enumerate(zip(labels, values)):
            text = QGraphicsSimpleTextItem(label)
            x_text = value * scale - text.boundingRect().width() / 2 + offset
            if text_finish > x_text - 10:
                y_text, y_tick = self.dot_r * 0.7, 0
                text_finish = values[0] * scale + offset
            else:
                y_text = -text.boundingRect().height() - self.dot_r * 0.7
                y_tick = -self.tick_height
                text_finish = x_text + text.boundingRect().width()
            text.setPos(x_text, y_text)
            if not collides(text, shown_items):
                text.setParentItem(self)
                shown_items.append(text)

            x_tick = value * scale - self.tick_width / 2 + offset
            tick = QGraphicsRectItem(x_tick, y_tick, self.tick_width,
                                     self.tick_height)
            tick.setBrush(QColor(Qt.black))
            tick.setParentItem(self)

            if self.half_tick_height and i:
                x = x_tick - (x_tick - old_x_tick) / 2
                half_tick = QGraphicsLineItem(x, -self.half_tick_height, x, 0)
                half_tick.setParentItem(self)
            old_x_tick = x_tick
Exemple #18
0
 def test_other(self):
     fd, fname = tempfile.mkstemp('.pdf')
     os.close(fd)
     sc = QGraphicsScene()
     sc.addItem(QGraphicsRectItem(0, 0, 3, 3))
     try:
         imgio.PdfFormat.write(fname, sc)
         with open(fname, "rb") as f:
             self.assertTrue(f.read().startswith(b'%PDF'))
     finally:
         os.unlink(fname)
Exemple #19
0
    def __init__(self, width, height, color, parent=None):
        super().__init__(parent=parent)
        self.width = width
        self.height = height
        self.color = color
        if not isinstance(self.color, QColor):
            self.color = QColor(self.color)

        self.__rect = QGraphicsRectItem(0, 0, self.width, self.height, self)
        self.__rect.setPen(QPen(Qt.NoPen))
        self.__rect.setBrush(QBrush(self.color))
Exemple #20
0
    def __update(self):
        self.__clear()

        pen = self.pen()
        brush = self.brush()
        for _ in range(self.count()):
            item = QGraphicsRectItem(self)
            item.setPen(pen)
            item.setBrush(brush)
            self.__items.append(item)

        self.__layout()
Exemple #21
0
 def test_other(self):
     fd, fname = tempfile.mkstemp('.png')
     os.close(fd)
     sc = QGraphicsScene()
     sc.addItem(QGraphicsRectItem(0, 0, 3, 3))
     try:
         imgio.PngFormat.write(fname, sc)
         im = QImage(fname)
         # writer adds 15*2 of empty space
         self.assertEqual((30+4, 30+4), (im.width(), im.height()))
     finally:
         os.unlink(fname)
Exemple #22
0
 def updateSelectionRect(self, event):
     pos = event.scenePos()
     buttonDownPos = event.buttonDownScenePos(Qt.LeftButton)
     rect = QRectF(pos, buttonDownPos).normalized()
     rect = rect.intersected(self.sceneRect())
     if not self.selectionRect:
         self.selectionRect = QGraphicsRectItem()
         self.selectionRect.setBrush(QColor(10, 10, 10, 20))
         self.selectionRect.setPen(QPen(QColor(200, 200, 200, 200)))
         self.addItem(self.selectionRect)
     self.selectionRect.setRect(rect)
     self.selectionRectPointChanged.emit(pos)
 def __init__(self):
     GraphicsWidget.__init__(self)
     self.width_bar = 15
     self.colors = None
     self.gradient = QLinearGradient()
     self.setMaximumHeight(2**16)
     self.setMinimumWidth(self.width_bar)
     self.setMaximumWidth(self.width_bar)
     self.rect = QGraphicsRectItem(QRectF(0, 0, self.width_bar, 100), self)
     self.axis = pg.AxisItem('right', parent=self)
     self.axis.setX(self.width_bar)
     self.axis.geometryChanged.connect(self._update_width)
     self.adapt_to_size()
     self._initialized = True
Exemple #24
0
 def redraw_grid(self):
     if self.grid is not None:
         self.scene.removeItem(self.grid)
     self.grid = QGraphicsItemGroup()
     self.grid.setZValue(-200)
     self.grid_cells = np.full((self.size_y, self.size_x), None)
     for y in range(self.size_y):
         for x in range(self.size_x - (y % 2) * self.hexagonal):
             if self.hexagonal:
                 cell = QGraphicsPathItem(_hexagon_path)
                 cell.setPos(x + (y % 2) / 2, y * sqrt3_2)
             else:
                 cell = QGraphicsRectItem(x - 0.5, y - 0.5, 1, 1)
             self.grid_cells[y, x] = cell
             cell.setPen(self._grid_pen)
             self.grid.addToGroup(cell)
     self.scene.addItem(self.grid)
Exemple #25
0
    def __init__(self, palette, values, parent):
        QGraphicsObject.__init__(self, parent)
        self.parent = parent
        self.palette = palette
        self.values = values
        self.legend = parent
        self.label_items = [QGraphicsTextItem(text, self) for text in values]
        for i in self.label_items:
            i.setTextWidth(50)

        self.rect = QRectF()

        self.gradient_item = QGraphicsRectItem(self)
        self.gradient = QLinearGradient()
        self.gradient.setStops([(v * 0.1, self.palette[v * 0.1])
                                for v in range(11)])
        self.orientation = Qt.Horizontal
        self.set_orientation(Qt.Vertical)
Exemple #26
0
 def updateSelectionRect(self, event):
     pos = event.scenePos()
     buttonDownPos = event.buttonDownScenePos(Qt.LeftButton)
     rect = QRectF(pos, buttonDownPos).normalized()
     rect = rect.intersected(self.sceneRect())
     if not self.selectionRect:
         self.selectionRect = QGraphicsRectItem()
         self.selectionRect.setBrush(QColor(10, 10, 10, 20))
         self.selectionRect.setPen(QPen(QColor(200, 200, 200, 200)))
         self.addItem(self.selectionRect)
     self.selectionRect.setRect(rect)
     if event.modifiers() & Qt.ControlModifier or \
                     event.modifiers() & Qt.ShiftModifier:
         path = self.selectionArea()
     else:
         path = QPainterPath()
     path.addRect(rect)
     self.setSelectionArea(path)
     self.selectionRectPointChanged.emit(pos)
Exemple #27
0
def render_drop_shadow_frame(pixmap, shadow_rect, shadow_color, offset, radius,
                             rect_fill_color):
    pixmap.fill(QColor(0, 0, 0, 0))
    scene = QGraphicsScene()
    rect = QGraphicsRectItem(shadow_rect)
    rect.setBrush(QColor(rect_fill_color))
    rect.setPen(QPen(Qt.NoPen))
    scene.addItem(rect)
    effect = QGraphicsDropShadowEffect(color=shadow_color,
                                       blurRadius=radius,
                                       offset=offset)

    rect.setGraphicsEffect(effect)
    scene.setSceneRect(QRectF(QPointF(0, 0), QSizeF(pixmap.size())))
    painter = QPainter(pixmap)
    scene.render(painter)
    painter.end()
    scene.clear()
    scene.deleteLater()
    return pixmap
Exemple #28
0
    def mouseMoveEvent(self, event):
        # Reimplemented
        if event.buttons() & Qt.LeftButton:
            assert self.__selstate is not None
            if self.__selectionRect is None:
                self.__selectionRect = QGraphicsRectItem(self)

            rect = (QRectF(event.buttonDownPos(Qt.LeftButton),
                           event.pos()).normalized())

            if not rect.width():
                rect = rect.adjusted(-1e-7, -1e-7, 1e-7, 1e-7)

            rect = rect.intersected(self.contentsRect())
            self.__selectionRect.setRect(rect)
            self.__selstate.rect = rect
            self.__selstate.action |= SelectAction.Current

            self.__setSelectionRect(rect, self.__selstate.action)
            event.accept()
Exemple #29
0
    def updateSelectionArea(self):
        mask = self.selectionMask()
        brush = self._stylebrush[mask.astype(int)]
        self._item.setBrush(brush)

        if self._selitem is not None:
            self.removeItem(self._selitem)
            self._selitem = None

        if self.__selectiondelegate is not None:
            self._selitem = QGraphicsItemGroup()
            self._selitem.dataBounds = \
                lambda axis, frac=1.0, orthoRange=None: None

            for p1, p2 in self.__selectiondelegate.selection:
                r = QRectF(p1, p2).normalized()
                ritem = QGraphicsRectItem(r, self._selitem)
                ritem.setBrush(QBrush(Qt.NoBrush))
                ritem.setPen(QPen(Qt.red, 0))

            self.addItem(self._selitem)
Exemple #30
0
 def __init__(self, name, point, parent):
     QGraphicsObject.__init__(self, parent)
     self.text_item = QGraphicsTextItem(name, self)
     if point:
         s = point.size()
         height = max(2 * s, self.text_item.boundingRect().height())
     else:
         height = self.text_item.boundingRect().height()
     p = 0.5 * height
     self.text_item.setPos(height, 0)
     self.point_item = point
     if point:
         self.point_item.setParentItem(self)
         self.point_item.setPos(p, p)
     self._rect = QRectF(0, 0,
                         height + self.text_item.boundingRect().width(),
                         height)
     self.rect_item = QGraphicsRectItem(self._rect, self)
     self.rect_item.setPen(QPen(Qt.NoPen))
     self.rect_item.stackBefore(self.text_item)
     if self.point_item:
         self.rect_item.stackBefore(self.point_item)