{
    "file_diffs": [
        {
            "old_file_content": "import sys\nimport itertools\nimport warnings\nfrom xml.sax.saxutils import escape\nfrom math import log10, floor, ceil\n\nimport numpy as np\nfrom AnyQt.QtCore import Qt, QRectF, QSize, QTimer, pyqtSignal as Signal, \\\n    QObject\nfrom AnyQt.QtGui import (\n    QStaticText, QColor, QPen, QBrush, QPainterPath, QTransform, QPainter\n)\nfrom AnyQt.QtWidgets import (\n    QApplication, QToolTip, QGraphicsTextItem, QGraphicsRectItem\n)\n\nimport pyqtgraph as pg\nimport pyqtgraph.graphicsItems.ScatterPlotItem\nfrom pyqtgraph.graphicsItems.LegendItem import (\n    LegendItem as PgLegendItem, ItemSample\n)\nfrom pyqtgraph.graphicsItems.TextItem import TextItem\n\nfrom Orange.util import OrangeDeprecationWarning\nfrom Orange.widgets import gui\nfrom Orange.widgets.settings import Setting\nfrom Orange.widgets.utils import classdensity\nfrom Orange.widgets.utils.colorpalette import ColorPaletteGenerator\nfrom Orange.widgets.utils.plot import OWPalette\nfrom Orange.widgets.visualize.owscatterplotgraph_obsolete import (\n    OWScatterPlotGraph as OWScatterPlotGraphObs\n)\nfrom Orange.widgets.visualize.utils.plotutils import (\n    HelpEventDelegate as EventDelegate,\n    InteractiveViewBox as ViewBox\n)\n\n\nSELECTION_WIDTH = 5\nMAX_N_VALID_SIZE_ANIMATE = 1000\n\n\nclass PaletteItemSample(ItemSample):\n    \"\"\"A color strip to insert into legends for discretized continuous values\"\"\"\n\n    def __init__(self, palette, scale, label_formatter=None):\n        \"\"\"\n        :param palette: palette used for showing continuous values\n        :type palette: ContinuousPaletteGenerator\n        :param scale: an instance of DiscretizedScale that defines the\n                      conversion of values into bins\n        :type scale: DiscretizedScale\n        \"\"\"\n        super().__init__(None)\n        self.palette = palette\n        self.scale = scale\n        if label_formatter is None:\n            label_formatter = \"{{:.{}f}}\".format(scale.decimals).format\n        cuts = [label_formatter(scale.offset + i * scale.width)\n                for i in range(scale.bins + 1)]\n        self.labels = [QStaticText(\"{} - {}\".format(fr, to))\n                       for fr, to in zip(cuts, cuts[1:])]\n        for label in self.labels:\n            label.prepare()\n        self.text_width = max(label.size().width() for label in self.labels)\n\n    def boundingRect(self):\n        return QRectF(0, 0, 40 + self.text_width, 20 + self.scale.bins * 15)\n\n    def paint(self, p, *args):\n        p.setRenderHint(p.Antialiasing)\n        scale = self.scale\n        font = p.font()\n        font.setPixelSize(11)\n        p.setFont(font)\n        for i, label in enumerate(self.labels):\n            color = QColor(*self.palette.getRGB((i + 0.5) / scale.bins))\n            p.setPen(Qt.NoPen)\n            p.setBrush(QBrush(color))\n            p.drawRect(0, i * 15, 15, 15)\n            p.setPen(QPen(Qt.black))\n            p.drawStaticText(20, i * 15 + 1, label)\n\n\nclass LegendItem(PgLegendItem):\n    def __init__(self, size=None, offset=None, pen=None, brush=None):\n        super().__init__(size, offset)\n\n        self.layout.setContentsMargins(5, 5, 5, 5)\n        self.layout.setHorizontalSpacing(15)\n        self.layout.setColumnAlignment(1, Qt.AlignLeft | Qt.AlignVCenter)\n\n        if pen is None:\n            pen = QPen(QColor(196, 197, 193, 200), 1)\n            pen.setCosmetic(True)\n        self.__pen = pen\n\n        if brush is None:\n            brush = QBrush(QColor(232, 232, 232, 100))\n        self.__brush = brush\n\n    def restoreAnchor(self, anchors):\n        \"\"\"\n        Restore (parent) relative position from stored anchors.\n\n        The restored position is within the parent bounds.\n        \"\"\"\n        anchor, parentanchor = anchors\n        self.anchor(*bound_anchor_pos(anchor, parentanchor))\n\n    def paint(self, painter, option, widget=None):\n        painter.setPen(self.__pen)\n        painter.setBrush(self.__brush)\n        rect = self.contentsRect()\n        painter.drawRoundedRect(rect, 2, 2)\n\n    def addItem(self, item, name):\n        super().addItem(item, name)\n        # Fix-up the label alignment\n        _, label = self.items[-1]\n        label.setText(name, justify=\"left\")\n\n    def clear(self):\n        \"\"\"\n        Clear all legend items.\n        \"\"\"\n        items = list(self.items)\n        self.items = []\n        for sample, label in items:\n            self.layout.removeItem(sample)\n            self.layout.removeItem(label)\n            sample.hide()\n            label.hide()\n\n        self.updateSize()\n\n\ndef bound_anchor_pos(corner, parentpos):\n    corner = np.clip(corner, 0, 1)\n    parentpos = np.clip(parentpos, 0, 1)\n\n    irx, iry = corner\n    prx, pry = parentpos\n\n    if irx > 0.9 and prx < 0.1:\n        irx = prx = 0.0\n    if iry > 0.9 and pry < 0.1:\n        iry = pry = 0.0\n    if irx < 0.1 and prx > 0.9:\n        irx = prx = 1.0\n    if iry < 0.1 and pry > 0.9:\n        iry = pry = 1.0\n    return (irx, iry), (prx, pry)\n\n\nclass DiscretizedScale:\n    \"\"\"\n    Compute suitable bins for continuous value from its minimal and\n    maximal value.\n\n    The width of the bin is a power of 10 (including negative powers).\n    The minimal value is rounded up and the maximal is rounded down. If this\n    gives less than 3 bins, the width is divided by four; if it gives\n    less than 6, it is halved.\n\n    .. attribute:: offset\n        The start of the first bin.\n\n    .. attribute:: width\n        The width of the bins\n\n    .. attribute:: bins\n        The number of bins\n\n    .. attribute:: decimals\n        The number of decimals used for printing out the boundaries\n    \"\"\"\n    def __init__(self, min_v, max_v):\n        \"\"\"\n        :param min_v: Minimal value\n        :type min_v: float\n        :param max_v: Maximal value\n        :type max_v: float\n        \"\"\"\n        super().__init__()\n        dif = max_v - min_v if max_v != min_v else 1\n        if np.isnan(dif):\n            min_v = 0\n            dif = decimals = 1\n        else:\n            decimals = -floor(log10(dif))\n        resolution = 10 ** -decimals\n        bins = ceil(dif / resolution)\n        if bins < 6:\n            decimals += 1\n            if bins < 3:\n                resolution /= 4\n            else:\n                resolution /= 2\n            bins = ceil(dif / resolution)\n        self.offset = resolution * floor(min_v // resolution)\n        self.bins = bins\n        self.decimals = max(decimals, 0)\n        self.width = resolution\n\n\nclass InteractiveViewBox(ViewBox):\n    def __init__(self, graph, enable_menu=False):\n        super().__init__(graph, enable_menu)\n        warnings.warn(\"InteractiveViewBox class has been deprecated since \"\n                      \"3.17. Use Orange.widgets.visualize.utils.plotutils.\"\n                      \"InteractiveViewBox instead.\", OrangeDeprecationWarning)\n\n\nclass OWScatterPlotGraph(OWScatterPlotGraphObs):\n    def __init__(self, scatter_widget, parent=None, _=\"None\", view_box=InteractiveViewBox):\n        super().__init__(scatter_widget, parent=parent, _=_, view_box=view_box)\n        warnings.warn(\"OWScatterPlotGraph class has been deprecated since \"\n                      \"3.17. Use OWScatterPlotBase instead.\",\n                      OrangeDeprecationWarning)\n\n\nclass ScatterPlotItem(pg.ScatterPlotItem):\n    \"\"\"PyQtGraph's ScatterPlotItem calls updateSpots at any change of sizes/colors/symbols,\n    which then rebuilds the stored pixmaps for each symbol. Because Orange calls\n    set* function in succession, we postpone updateSpots() to paint().\"\"\"\n\n    _update_spots_in_paint = False\n\n    def updateSpots(self, dataSet=None):  # pylint: disable=unused-argument\n        self._update_spots_in_paint = True\n        self.update()\n\n    def paint(self, painter, option, widget=None):\n        if self._update_spots_in_paint:\n            self._update_spots_in_paint = False\n            super().updateSpots()\n        painter.setRenderHint(QPainter.SmoothPixmapTransform, True)\n        super().paint(painter, option, widget)\n\n\ndef _define_symbols():\n    \"\"\"\n    Add symbol ? to ScatterPlotItemSymbols,\n    reflect the triangle to point upwards\n    \"\"\"\n    symbols = pyqtgraph.graphicsItems.ScatterPlotItem.Symbols\n    path = QPainterPath()\n    path.addEllipse(QRectF(-0.35, -0.35, 0.7, 0.7))\n    path.moveTo(-0.5, 0.5)\n    path.lineTo(0.5, -0.5)\n    path.moveTo(-0.5, -0.5)\n    path.lineTo(0.5, 0.5)\n    symbols[\"?\"] = path\n\n    tr = QTransform()\n    tr.rotate(180)\n    symbols['t'] = tr.map(symbols['t'])\n\n\n_define_symbols()\n\n\ndef _make_pen(color, width):\n    p = QPen(color, width)\n    p.setCosmetic(True)\n    return p\n\n\nclass OWScatterPlotBase(gui.OWComponent, QObject):\n    \"\"\"\n    Provide a graph component for widgets that show any kind of point plot\n\n    The component plots a set of points with given coordinates, shapes,\n    sizes and colors. Its function is similar to that of a *view*, whereas\n    the widget represents a *model* and a *controler*.\n\n    The model (widget) needs to provide methods:\n\n    - `get_coordinates_data`, `get_size_data`, `get_color_data`,\n      `get_shape_data`, `get_label_data`, which return a 1d array (or two\n      arrays, for `get_coordinates_data`) of `dtype` `float64`, except for\n      `get_label_data`, which returns formatted labels;\n    - `get_shape_labels` returns a list of strings for shape legend\n    - `get_color_labels` returns strings for color legend, or a function for\n       formatting numbers if the legend is continuous, or None for default\n       formatting\n    - `get_tooltip`, which gives a tooltip for a single data point\n    - (optional) `impute_sizes`, `impute_shapes` get final coordinates and\n      shapes, and replace nans;\n    - `get_subset_mask` returns a bool array indicating whether a\n      data point is in the subset or not (e.g. in the 'Data Subset' signal\n      in the Scatter plot and similar widgets);\n    - `get_palette` returns a palette appropriate for visualizing the\n      current color data;\n    - `is_continuous_color` decides the type of the color legend;\n\n    The widget (in a role of controller) must also provide methods\n    - `selection_changed`\n\n    If `get_coordinates_data` returns `(None, None)`, the plot is cleared. If\n    `get_size_data`, `get_color_data` or `get_shape_data` return `None`,\n    all points will have the same size, color or shape, respectively.\n    If `get_label_data` returns `None`, there are no labels.\n\n    The view (this compomnent) provides methods `update_coordinates`,\n    `update_sizes`, `update_colors`, `update_shapes` and `update_labels`\n    that the widget (in a role of a controler) should call when any of\n    these properties are changed. If the widget calls, for instance, the\n    plot's `update_colors`, the plot will react by calling the widget's\n    `get_color_data` as well as the widget's methods needed to construct the\n    legend.\n\n    The view also provides a method `reset_graph`, which should be called only\n    when\n    - the widget gets entirely new data\n    - the number of points may have changed, for instance when selecting\n    a different attribute for x or y in the scatter plot, where the points\n    with missing x or y coordinates are hidden.\n\n    Every `update_something` calls the plot's `get_something`, which\n    calls the model's `get_something_data`, then it transforms this data\n    into whatever is needed (colors, shapes, scaled sizes) and changes the\n    plot. For the simplest example, here is `update_shapes`:\n\n    ```\n        def update_shapes(self):\n            if self.scatterplot_item:\n                shape_data = self.get_shapes()\n                self.scatterplot_item.setSymbol(shape_data)\n            self.update_legends()\n\n        def get_shapes(self):\n            shape_data = self.master.get_shape_data()\n            shape_data = self.master.impute_shapes(\n                shape_data, len(self.CurveSymbols) - 1)\n            return self.CurveSymbols[shape_data]\n    ```\n\n    On the widget's side, `get_something_data` is essentially just:\n\n    ```\n        def get_size_data(self):\n            return self.get_column(self.attr_size)\n    ```\n\n    where `get_column` retrieves a column while also filtering out the\n    points with missing x and y and so forth. (Here we present the simplest\n    two cases, \"shapes\" for the view and \"sizes\" for the model. The colors\n    for the view are more complicated since they deal with discrete and\n    continuous palettes, and the shapes for the view merge infrequent shapes.)\n\n    The plot can also show just a random sample of the data. The sample size is\n    set by `set_sample_size`, and the rest is taken care by the plot: the\n    widget keeps providing the data for all points, selection indices refer\n    to the entire set etc. Internally, sampling happens as early as possible\n    (in methods `get_<something>`).\n    \"\"\"\n    too_many_labels = Signal(bool)\n    begin_resizing = Signal()\n    step_resizing = Signal()\n    end_resizing = Signal()\n\n    label_only_selected = Setting(False)\n    point_width = Setting(10)\n    alpha_value = Setting(128)\n    show_grid = Setting(False)\n    show_legend = Setting(True)\n    class_density = Setting(False)\n    jitter_size = Setting(0)\n\n    resolution = 256\n\n    CurveSymbols = np.array(\"o x t + d star ?\".split())\n    MinShapeSize = 6\n    DarkerValue = 120\n    UnknownColor = (168, 50, 168)\n\n    COLOR_NOT_SUBSET = (128, 128, 128, 0)\n    COLOR_SUBSET = (128, 128, 128, 255)\n    COLOR_DEFAULT = (128, 128, 128, 0)\n\n    MAX_VISIBLE_LABELS = 500\n\n    def __init__(self, scatter_widget, parent=None, view_box=ViewBox):\n        QObject.__init__(self)\n        gui.OWComponent.__init__(self, scatter_widget)\n\n        self.subset_is_shown = False\n\n        self.view_box = view_box(self)\n        self.plot_widget = pg.PlotWidget(viewBox=self.view_box, parent=parent,\n                                         background=\"w\")\n        self.plot_widget.hideAxis(\"left\")\n        self.plot_widget.hideAxis(\"bottom\")\n        self.plot_widget.getPlotItem().buttonsHidden = True\n        self.plot_widget.setAntialiasing(True)\n        self.plot_widget.sizeHint = lambda: QSize(500, 500)\n\n        self.density_img = None\n        self.scatterplot_item = None\n        self.scatterplot_item_sel = None\n        self.labels = []\n\n        self.master = scatter_widget\n        self._create_drag_tooltip(self.plot_widget.scene())\n\n        self.selection = None  # np.ndarray\n\n        self.n_valid = 0\n        self.n_shown = 0\n        self.sample_size = None\n        self.sample_indices = None\n\n        self.palette = None\n\n        self.shape_legend = self._create_legend(((1, 0), (1, 0)))\n        self.color_legend = self._create_legend(((1, 1), (1, 1)))\n        self.update_legend_visibility()\n\n        self.scale = None  # DiscretizedScale\n        self._too_many_labels = False\n\n        # self.setMouseTracking(True)\n        # self.grabGesture(QPinchGesture)\n        # self.grabGesture(QPanGesture)\n\n        self.update_grid_visibility()\n\n        self._tooltip_delegate = EventDelegate(self.help_event)\n        self.plot_widget.scene().installEventFilter(self._tooltip_delegate)\n        self.view_box.sigTransformChanged.connect(self.update_density)\n        self.view_box.sigRangeChangedManually.connect(self.update_labels)\n\n        self.timer = None\n\n    def _create_legend(self, anchor):\n        legend = LegendItem()\n        legend.setParentItem(self.plot_widget.getViewBox())\n        legend.restoreAnchor(anchor)\n        return legend\n\n    def _create_drag_tooltip(self, scene):\n        tip_parts = [\n            (Qt.ShiftModifier, \"Shift: Add group\"),\n            (Qt.ShiftModifier + Qt.ControlModifier,\n             \"Shift-{}: Append to group\".\n             format(\"Cmd\" if sys.platform == \"darwin\" else \"Ctrl\")),\n            (Qt.AltModifier, \"Alt: Remove\")\n        ]\n        all_parts = \", \".join(part for _, part in tip_parts)\n        self.tiptexts = {\n            int(modifier): all_parts.replace(part, \"<b>{}</b>\".format(part))\n            for modifier, part in tip_parts\n        }\n        self.tiptexts[0] = all_parts\n\n        self.tip_textitem = text = QGraphicsTextItem()\n        # Set to the longest text\n        text.setHtml(self.tiptexts[Qt.ShiftModifier + Qt.ControlModifier])\n        text.setPos(4, 2)\n        r = text.boundingRect()\n        rect = QGraphicsRectItem(0, 0, r.width() + 8, r.height() + 4)\n        rect.setBrush(QColor(224, 224, 224, 212))\n        rect.setPen(QPen(Qt.NoPen))\n        self.update_tooltip()\n\n        scene.drag_tooltip = scene.createItemGroup([rect, text])\n        scene.drag_tooltip.hide()\n\n    def update_tooltip(self, modifiers=Qt.NoModifier):\n        modifiers &= Qt.ShiftModifier + Qt.ControlModifier + Qt.AltModifier\n        text = self.tiptexts.get(int(modifiers), self.tiptexts[0])\n        self.tip_textitem.setHtml(text + self._get_jittering_tooltip())\n\n    def _get_jittering_tooltip(self):\n        warn_jittered = \"\"\n        if self.jitter_size:\n            warn_jittered = \\\n                '<br/><br/>' \\\n                '<span style=\"background-color: red; color: white; ' \\\n                'font-weight: 500;\">' \\\n                '&nbsp;Warning: Selection is applied to unjittered data&nbsp;' \\\n                '</span>'\n        return warn_jittered\n\n    def update_jittering(self):\n        self.update_tooltip()\n        x, y = self.get_coordinates()\n        if x is None or not len(x) or self.scatterplot_item is None:\n            return\n        self._update_plot_coordinates(self.scatterplot_item, x, y)\n        self._update_plot_coordinates(self.scatterplot_item_sel, x, y)\n        self.update_labels()\n\n    # TODO: Rename to remove_plot_items\n    def clear(self):\n        \"\"\"\n        Remove all graphical elements from the plot\n\n        Calls the pyqtgraph's plot widget's clear, sets all handles to `None`,\n        removes labels and selections.\n\n        This method should generally not be called by the widget. If the data\n        is gone (*e.g.* upon receiving `None` as an input data signal), this\n        should be handler by calling `reset_graph`, which will in turn call\n        `clear`.\n\n        Derived classes should override this method if they add more graphical\n        elements. For instance, the regression line in the scatterplot adds\n        `self.reg_line_item = None` (the line in the plot is already removed\n        in this method).\n        \"\"\"\n        self.plot_widget.clear()\n\n        self.density_img = None\n        if self.timer is not None and self.timer.isActive():\n            self.timer.stop()\n            self.timer = None\n        self.scatterplot_item = None\n        self.scatterplot_item_sel = None\n        self.labels = []\n        self._signal_too_many_labels(False)\n        self.view_box.init_history()\n        self.view_box.tag_history()\n\n    # TODO: I hate `keep_something` and `reset_something` arguments\n    # __keep_selection is used exclusively be set_sample size which would\n    # otherwise just repeat the code from reset_graph except for resetting\n    # the selection. I'm uncomfortable with this; we may prefer to have a\n    # method _reset_graph which does everything except resetting the selection,\n    # and reset_graph would call it.\n    def reset_graph(self, __keep_selection=False):\n        \"\"\"\n        Reset the graph to new data (or no data)\n\n        The method must be called when the plot receives new data, in\n        particular when the number of points change. If only their properties\n        - like coordinates or shapes - change, an update method\n        (`update_coordinates`, `update_shapes`...) should be called instead.\n\n        The method must also be called when the data is gone.\n\n        The method calls `clear`, followed by calls of all update methods.\n\n        NB. Argument `__keep_selection` is for internal use only\n        \"\"\"\n        self.clear()\n        if not __keep_selection:\n            self.selection = None\n        self.sample_indices = None\n        self.update_coordinates()\n        self.update_point_props()\n\n    def set_sample_size(self, sample_size):\n        \"\"\"\n        Set the sample size\n\n        Args:\n            sample_size (int or None): sample size or `None` to show all points\n        \"\"\"\n        if self.sample_size != sample_size:\n            self.sample_size = sample_size\n            self.reset_graph(True)\n\n    def update_point_props(self):\n        \"\"\"\n        Update the sizes, colors, shapes and labels\n\n        The method calls the appropriate update methods for individual\n        properties.\n        \"\"\"\n        self.update_sizes()\n        self.update_colors()\n        self.update_selection_colors()\n        self.update_shapes()\n        self.update_labels()\n\n    # Coordinates\n    # TODO: It could be nice if this method was run on entire data, not just\n    # a sample. For this, however, it would need to either be called from\n    # `get_coordinates` before sampling (very ugly) or call\n    # `self.master.get_coordinates_data` (beyond ugly) or the widget would\n    # have to store the ranges of unsampled data (ugly).\n    # Maybe we leave it as it is.\n    def _reset_view(self, x_data, y_data):\n        \"\"\"\n        Set the range of the view box\n\n        Args:\n            x_data (np.ndarray): x coordinates\n            y_data (np.ndarray) y coordinates\n        \"\"\"\n        min_x, max_x = np.min(x_data), np.max(x_data)\n        min_y, max_y = np.min(y_data), np.max(y_data)\n        self.view_box.setRange(\n            QRectF(min_x, min_y, max_x - min_x or 1, max_y - min_y or 1),\n            padding=0.025)\n\n    def _filter_visible(self, data):\n        \"\"\"Return the sample from the data using the stored sample_indices\"\"\"\n        if data is None or self.sample_indices is None:\n            return data\n        else:\n            return np.asarray(data[self.sample_indices])\n\n    def get_coordinates(self):\n        \"\"\"\n        Prepare coordinates of the points in the plot\n\n        The method is called by `update_coordinates`. It gets the coordinates\n        from the widget, jitters them and return them.\n\n        The methods also initializes the sample indices if neededd and stores\n        the original and sampled number of points.\n\n        Returns:\n            (tuple): a pair of numpy arrays containing (sampled) coordinates,\n                or `(None, None)`.\n        \"\"\"\n        x, y = self.master.get_coordinates_data()\n        if x is None:\n            self.n_valid = self.n_shown = 0\n            return None, None\n        self.n_valid = len(x)\n        self._create_sample()\n        x = self._filter_visible(x)\n        y = self._filter_visible(y)\n        # Jittering after sampling is OK if widgets do not change the sample\n        # semi-permanently, e.g. take a sample for the duration of some\n        # animation. If the sample size changes dynamically (like by adding\n        # a \"sample size\" slider), points would move around when the sample\n        # size changes. To prevent this, jittering should be done before\n        # sampling (i.e. two lines earlier). This would slow it down somewhat.\n        x, y = self.jitter_coordinates(x, y)\n        return x, y\n\n    def _create_sample(self):\n        \"\"\"\n        Create a random sample if the data is larger than the set sample size\n        \"\"\"\n        self.n_shown = min(self.n_valid, self.sample_size or self.n_valid)\n        if self.sample_size is not None \\\n                and self.sample_indices is None \\\n                and self.n_valid != self.n_shown:\n            random = np.random.RandomState(seed=0)\n            self.sample_indices = random.choice(\n                self.n_valid, self.n_shown, replace=False)\n            # TODO: Is this really needed?\n            np.sort(self.sample_indices)\n\n    def jitter_coordinates(self, x, y):\n        \"\"\"\n        Display coordinates to random positions within ellipses with\n        radiuses of `self.jittter_size` percents of spans\n        \"\"\"\n        if self.jitter_size == 0:\n            return x, y\n        return self._jitter_data(x, y)\n\n    def _jitter_data(self, x, y, span_x=None, span_y=None):\n        if span_x is None:\n            span_x = np.max(x) - np.min(x)\n        if span_y is None:\n            span_y = np.max(y) - np.min(y)\n        random = np.random.RandomState(seed=0)\n        rs = random.uniform(0, 1, len(x))\n        phis = random.uniform(0, 2 * np.pi, len(x))\n        magnitude = self.jitter_size / 100\n        return (x + magnitude * span_x * rs * np.cos(phis),\n                y + magnitude * span_y * rs * np.sin(phis))\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n\n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n            data[prop] = plot.data[prop]\n        plot.setData(**data)\n\n    def update_coordinates(self):\n        \"\"\"\n        Trigger the update of coordinates while keeping other features intact.\n\n        The method gets the coordinates by calling `self.get_coordinates`,\n        which in turn calls the widget's `get_coordinate_data`. The number of\n        coordinate pairs returned by the latter must match the current number\n        of points. If this is not the case, the widget should trigger\n        the complete update by calling `reset_graph` instead of this method.\n        \"\"\"\n        x, y = self.get_coordinates()\n        if x is None or not len(x):\n            return\n        if self.scatterplot_item is None:\n            if self.sample_indices is None:\n                indices = np.arange(self.n_valid)\n            else:\n                indices = self.sample_indices\n            kwargs = dict(x=x, y=y, data=indices)\n            self.scatterplot_item = ScatterPlotItem(**kwargs)\n            self.scatterplot_item.sigClicked.connect(self.select_by_click)\n            self.scatterplot_item_sel = ScatterPlotItem(**kwargs)\n            self.plot_widget.addItem(self.scatterplot_item_sel)\n            self.plot_widget.addItem(self.scatterplot_item)\n        else:\n            self._update_plot_coordinates(self.scatterplot_item, x, y)\n            self._update_plot_coordinates(self.scatterplot_item_sel, x, y)\n            self.update_labels()\n\n        self.update_density()  # Todo: doesn't work: try MDS with density on\n        self._reset_view(x, y)\n\n    # Sizes\n    def get_sizes(self):\n        \"\"\"\n        Prepare data for sizes of points in the plot\n\n        The method is called by `update_sizes`. It gets the sizes\n        from the widget and performs the necessary scaling and sizing.\n        The output is rounded to half a pixel for faster drawing.\n\n        Returns:\n            (np.ndarray): sizes\n        \"\"\"\n        size_column = self.master.get_size_data()\n        if size_column is None:\n            return np.full((self.n_shown,),\n                           self.MinShapeSize + (5 + self.point_width) * 0.5)\n        size_column = self._filter_visible(size_column)\n        size_column = size_column.copy()\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n            size_column -= np.nanmin(size_column)\n            mx = np.nanmax(size_column)\n        if mx > 0:\n            size_column /= mx\n        else:\n            size_column[:] = 0.5\n\n        sizes = self.MinShapeSize + (5 + self.point_width) * size_column\n        # round sizes to half pixel for smaller pyqtgraph's symbol pixmap atlas\n        sizes = (sizes * 2).round() / 2\n        return sizes\n\n    def update_sizes(self):\n        \"\"\"\n        Trigger an update of point sizes\n\n        The method calls `self.get_sizes`, which in turn calls the widget's\n        `get_size_data`. The result are properly scaled and then passed\n        back to widget for imputing (`master.impute_sizes`).\n        \"\"\"\n        if self.scatterplot_item:\n            size_data = self.get_sizes()\n            size_imputer = getattr(\n                self.master, \"impute_sizes\", self.default_impute_sizes)\n            size_imputer(size_data)\n\n            if self.timer is not None and self.timer.isActive():\n                self.timer.stop()\n                self.timer = None\n\n            current_size_data = self.scatterplot_item.data[\"size\"].copy()\n            diff = size_data - current_size_data\n            widget = self\n\n            class Timeout:\n                # 0.5 - np.cos(np.arange(0.17, 1, 0.17) * np.pi) / 2\n                factors = [0.07, 0.26, 0.52, 0.77, 0.95, 1]\n\n                def __init__(self):\n                    self._counter = 0\n\n                def __call__(self):\n                    factor = self.factors[self._counter]\n                    self._counter += 1\n                    size = current_size_data + diff * factor\n                    if len(self.factors) == self._counter:\n                        widget.timer.stop()\n                        widget.timer = None\n                        size = size_data\n                    widget.scatterplot_item.setSize(size)\n                    widget.scatterplot_item_sel.setSize(size + SELECTION_WIDTH)\n                    if widget.timer is None:\n                        widget.end_resizing.emit()\n                    else:\n                        widget.step_resizing.emit()\n\n            if self.n_valid <= MAX_N_VALID_SIZE_ANIMATE and \\\n                    np.all(current_size_data > 0) and np.any(diff != 0):\n                # If encountered any strange behaviour when updating sizes,\n                # implement it with threads\n                self.begin_resizing.emit()\n                self.timer = QTimer(self.scatterplot_item, interval=50)\n                self.timer.timeout.connect(Timeout())\n                self.timer.start()\n            else:\n                self.begin_resizing.emit()\n                self.scatterplot_item.setSize(size_data)\n                self.scatterplot_item_sel.setSize(size_data + SELECTION_WIDTH)\n                self.end_resizing.emit()\n\n    update_point_size = update_sizes  # backward compatibility (needed?!)\n    update_size = update_sizes\n\n    @classmethod\n    def default_impute_sizes(cls, size_data):\n        \"\"\"\n        Fallback imputation for sizes.\n\n        Set the size to two pixels smaller than the minimal size\n\n        Returns:\n            (bool): True if there was any missing data\n        \"\"\"\n        nans = np.isnan(size_data)\n        if np.any(nans):\n            size_data[nans] = cls.MinShapeSize - 2\n            return True\n        else:\n            return False\n\n    # Colors\n    def get_colors(self):\n        \"\"\"\n        Prepare data for colors of the points in the plot\n\n        The method is called by `update_colors`. It gets the colors and the\n        indices of the data subset from the widget (`get_color_data`,\n        `get_subset_mask`), and constructs lists of pens and brushes for\n        each data point.\n\n        The method uses different palettes for discrete and continuous data,\n        as determined by calling the widget's method `is_continuous_color`.\n\n        If also marks the points that are in the subset as defined by, for\n        instance the 'Data Subset' signal in the Scatter plot and similar\n        widgets. (Do not confuse this with *selected points*, which are\n        marked by circles around the points, which are colored by groups\n        and thus independent of this method.)\n\n        Returns:\n            (tuple): a list of pens and list of brushes\n        \"\"\"\n        self.palette = self.master.get_palette()\n        c_data = self.master.get_color_data()\n        c_data = self._filter_visible(c_data)\n        subset = self.master.get_subset_mask()\n        subset = self._filter_visible(subset)\n        self.subset_is_shown = subset is not None\n        if c_data is None:  # same color\n            return self._get_same_colors(subset)\n        elif self.master.is_continuous_color():\n            return self._get_continuous_colors(c_data, subset)\n        else:\n            return self._get_discrete_colors(c_data, subset)\n\n    def _get_same_colors(self, subset):\n        \"\"\"\n        Return the same pen for all points while the brush color depends\n        upon whether the point is in the subset or not\n\n        Args:\n            subset (np.ndarray): a bool array indicating whether a data point\n                is in the subset or not (e.g. in the 'Data Subset' signal\n                in the Scatter plot and similar widgets);\n\n        Returns:\n            (tuple): a list of pens and list of brushes\n        \"\"\"\n        color = self.plot_widget.palette().color(OWPalette.Data)\n        pen = [_make_pen(color, 1.5)] * self.n_shown  # use a single QPen instance\n        if subset is not None:\n            brush = np.where(\n                subset,\n                *(QBrush(QColor(*col))\n                  for col in (self.COLOR_SUBSET, self.COLOR_NOT_SUBSET)))\n        else:\n            color = QColor(*self.COLOR_DEFAULT)\n            color.setAlpha(self.alpha_value)\n            brush = [QBrush(color)] * self.n_shown  # use a single QBrush instance\n        return pen, brush\n\n    def _get_continuous_colors(self, c_data, subset):\n        \"\"\"\n        Return the pens and colors whose color represent an index into\n        a continuous palette. The same color is used for pen and brush,\n        except the former is darker. If the data has a subset, the brush\n        is transparent for points that are not in the subset.\n        \"\"\"\n        if np.isnan(c_data).all():\n            self.scale = None\n        else:\n            self.scale = DiscretizedScale(np.nanmin(c_data), np.nanmax(c_data))\n            c_data -= self.scale.offset\n            c_data /= self.scale.width\n            c_data = np.floor(c_data) + 0.5\n            c_data /= self.scale.bins\n            c_data = np.clip(c_data, 0, 1)\n        pen = self.palette.getRGB(c_data)\n        brush = np.hstack(\n            [pen, np.full((len(pen), 1), self.alpha_value, dtype=int)])\n        pen *= 100\n        pen //= self.DarkerValue\n\n        # Reuse pens and brushes with the same colors because PyQtGraph then builds\n        # smaller pixmap atlas, which makes the drawing faster\n\n        def reuse(cache, fn, *args):\n            if args not in cache:\n                cache[args] = fn(args)\n            return cache[args]\n\n        def create_pen(col):\n            return _make_pen(QColor(*col), 1.5)\n\n        def create_brush(col):\n            return QBrush(QColor(*col))\n\n        cached_pens = {}\n        pen = [reuse(cached_pens, create_pen, *col) for col in pen.tolist()]\n\n        if subset is not None:\n            brush[:, 3] = 0\n            brush[subset, 3] = 255\n\n        cached_brushes = {}\n        brush = np.array([reuse(cached_brushes, create_brush, *col) for col in brush.tolist()])\n\n        return pen, brush\n\n    def _get_discrete_colors(self, c_data, subset):\n        \"\"\"\n        Return the pens and colors whose color represent an index into\n        a discrete palette. The same color is used for pen and brush,\n        except the former is darker. If the data has a subset, the brush\n        is transparent for points that are not in the subset.\n        \"\"\"\n        n_colors = self.palette.number_of_colors\n        c_data = c_data.copy()\n        c_data[np.isnan(c_data)] = n_colors\n        c_data = c_data.astype(int)\n        colors = np.r_[self.palette.getRGB(np.arange(n_colors)),\n                       [[128, 128, 128]]]\n        pens = np.array(\n            [_make_pen(QColor(*col).darker(self.DarkerValue), 1.5)\n             for col in colors])\n        pen = pens[c_data]\n        alpha = self.alpha_value if subset is None else 255\n        brushes = np.array([\n            [QBrush(QColor(0, 0, 0, 0)),\n             QBrush(QColor(col[0], col[1], col[2], alpha))]\n            for col in colors])\n        brush = brushes[c_data]\n\n        if subset is not None:\n            brush = np.where(subset, brush[:, 1], brush[:, 0])\n        else:\n            brush = brush[:, 1]\n        return pen, brush\n\n    def update_colors(self):\n        \"\"\"\n        Trigger an update of point sizes\n\n        The method calls `self.get_colors`, which in turn calls the widget's\n        `get_color_data` to get the indices in the pallette. `get_colors`\n        returns a list of pens and brushes to which this method uses to\n        update the colors. Finally, the method triggers the update of the\n        legend and the density plot.\n        \"\"\"\n        if self.scatterplot_item is not None:\n            pen_data, brush_data = self.get_colors()\n            self.scatterplot_item.setPen(pen_data, update=False, mask=None)\n            self.scatterplot_item.setBrush(brush_data, mask=None)\n        self.update_legends()\n        self.update_density()\n\n    update_alpha_value = update_colors\n\n    def update_density(self):\n        \"\"\"\n        Remove the existing density plot (if there is one) and replace it\n        with a new one (if enabled).\n\n        The method gets the colors from the pens of the currently plotted\n        points.\n        \"\"\"\n        if self.density_img:\n            self.plot_widget.removeItem(self.density_img)\n            self.density_img = None\n        if self.class_density and self.scatterplot_item is not None:\n            rgb_data = [\n                pen.color().getRgb()[:3] if pen is not None else (255, 255, 255)\n                for pen in self.scatterplot_item.data['pen']]\n            if len(set(rgb_data)) <= 1:\n                return\n            [min_x, max_x], [min_y, max_y] = self.view_box.viewRange()\n            x_data, y_data = self.scatterplot_item.getData()\n            self.density_img = classdensity.class_density_image(\n                min_x, max_x, min_y, max_y, self.resolution,\n                x_data, y_data, rgb_data)\n            self.plot_widget.addItem(self.density_img)\n\n    def update_selection_colors(self):\n        \"\"\"\n        Trigger an update of selection markers\n\n        This update method is usually not called by the widget but by the\n        plot, since it is the plot that handles the selections.\n\n        Like other update methods, it calls the corresponding get method\n        (`get_colors_sel`) which returns a list of pens and brushes.\n        \"\"\"\n        if self.scatterplot_item_sel is None:\n            return\n        pen, brush = self.get_colors_sel()\n        self.scatterplot_item_sel.setPen(pen, update=False, mask=None)\n        self.scatterplot_item_sel.setBrush(brush, mask=None)\n\n    def get_colors_sel(self):\n        \"\"\"\n        Return pens and brushes for selection markers.\n\n        A pen can is set to `Qt.NoPen` if a point is not selected.\n\n        All brushes are completely transparent whites.\n\n        Returns:\n            (tuple): a list of pens and a list of brushes\n        \"\"\"\n        nopen = QPen(Qt.NoPen)\n        if self.selection is None:\n            pen = [nopen] * self.n_shown\n        else:\n            sels = np.max(self.selection)\n            if sels == 1:\n                pen = np.where(\n                    self._filter_visible(self.selection),\n                    _make_pen(QColor(255, 190, 0, 255), SELECTION_WIDTH + 1),\n                    nopen)\n            else:\n                palette = ColorPaletteGenerator(number_of_colors=sels + 1)\n                pen = np.choose(\n                    self._filter_visible(self.selection),\n                    [nopen] + [_make_pen(palette[i], SELECTION_WIDTH + 1)\n                               for i in range(sels)])\n        return pen, [QBrush(QColor(255, 255, 255, 0))] * self.n_shown\n\n    # Labels\n    def get_labels(self):\n        \"\"\"\n        Prepare data for labels for points\n\n        The method returns the results of the widget's `get_label_data`\n\n        Returns:\n            (labels): a sequence of labels\n        \"\"\"\n        return self._filter_visible(self.master.get_label_data())\n\n    def update_labels(self):\n        \"\"\"\n        Trigger an update of labels\n\n        The method calls `get_labels` which in turn calls the widget's\n        `get_label_data`. The obtained labels are shown if the corresponding\n        points are selected or if `label_only_selected` is `false`.\n        \"\"\"\n        for label in self.labels:\n            self.plot_widget.removeItem(label)\n        self.labels = []\n\n        mask = None\n        if self.scatterplot_item is not None:\n            x, y = self.scatterplot_item.getData()\n            mask = self._label_mask(x, y)\n\n        if mask is not None:\n            labels = self.get_labels()\n            if labels is None:\n                mask = None\n\n        self._signal_too_many_labels(\n            mask is not None and mask.sum() > self.MAX_VISIBLE_LABELS)\n        if self._too_many_labels or mask is None or not np.any(mask):\n            return\n\n        black = pg.mkColor(0, 0, 0)\n        labels = labels[mask]\n        x = x[mask]\n        y = y[mask]\n        for label, xp, yp in zip(labels, x, y):\n            ti = TextItem(label, black)\n            ti.setPos(xp, yp)\n            self.plot_widget.addItem(ti)\n            self.labels.append(ti)\n\n    def _signal_too_many_labels(self, too_many):\n        if self._too_many_labels != too_many:\n            self._too_many_labels = too_many\n            self.too_many_labels.emit(too_many)\n\n    def _label_mask(self, x, y):\n        (x0, x1), (y0, y1) = self.view_box.viewRange()\n        mask = np.logical_and(\n            np.logical_and(x >= x0, x <= x1),\n            np.logical_and(y >= y0, y <= y1))\n        if self.label_only_selected:\n            sub_mask = self._filter_visible(self.master.get_subset_mask())\n            if self.selection is None:\n                if sub_mask is None:\n                    return None\n                else:\n                    sel_mask = sub_mask\n            else:\n                sel_mask = self._filter_visible(self.selection) != 0\n                if sub_mask is not None:\n                    sel_mask = np.logical_or(sel_mask, sub_mask)\n            mask = np.logical_and(mask, sel_mask)\n        return mask\n\n    # Shapes\n    def get_shapes(self):\n        \"\"\"\n        Prepare data for shapes of points in the plot\n\n        The method is called by `update_shapes`. It gets the data from\n        the widget's `get_shape_data`, and then calls its `impute_shapes`\n        to impute the missing shape (usually with some default shape).\n\n        Returns:\n            (np.ndarray): an array of symbols (e.g. o, x, + ...)\n        \"\"\"\n        shape_data = self.master.get_shape_data()\n        shape_data = self._filter_visible(shape_data)\n        # Data has to be copied so the imputation can change it in-place\n        # TODO: Try avoiding this when we move imputation to the widget\n        if shape_data is not None:\n            shape_data = np.copy(shape_data)\n        shape_imputer = getattr(\n            self.master, \"impute_shapes\", self.default_impute_shapes)\n        shape_imputer(shape_data, len(self.CurveSymbols) - 1)\n        if isinstance(shape_data, np.ndarray):\n            shape_data = shape_data.astype(int)\n        else:\n            shape_data = np.zeros(self.n_shown, dtype=int)\n        return self.CurveSymbols[shape_data]\n\n    @staticmethod\n    def default_impute_shapes(shape_data, default_symbol):\n        \"\"\"\n        Fallback imputation for shapes.\n\n        Use the default symbol, usually the last symbol in the list.\n\n        Returns:\n            (bool): True if there was any missing data\n        \"\"\"\n        if shape_data is None:\n            return False\n        nans = np.isnan(shape_data)\n        if np.any(nans):\n            shape_data[nans] = default_symbol\n            return True\n        else:\n            return False\n\n    def update_shapes(self):\n        \"\"\"\n        Trigger an update of point symbols\n\n        The method calls `get_shapes` to obtain an array with a symbol\n        for each point and uses it to update the symbols.\n\n        Finally, the method updates the legend.\n        \"\"\"\n        if self.scatterplot_item:\n            shape_data = self.get_shapes()\n            self.scatterplot_item.setSymbol(shape_data)\n        self.update_legends()\n\n    def update_grid_visibility(self):\n        \"\"\"Show or hide the grid\"\"\"\n        self.plot_widget.showGrid(x=self.show_grid, y=self.show_grid)\n\n    def update_legend_visibility(self):\n        \"\"\"\n        Show or hide legends based on whether they are enabled and non-empty\n        \"\"\"\n        self.shape_legend.setVisible(\n            self.show_legend and bool(self.shape_legend.items))\n        self.color_legend.setVisible(\n            self.show_legend and bool(self.color_legend.items))\n\n    def update_legends(self):\n        \"\"\"Update content of legends and their visibility\"\"\"\n        cont_color = self.master.is_continuous_color()\n        shape_labels = self.master.get_shape_labels()\n        color_labels = self.master.get_color_labels()\n        if shape_labels == color_labels and shape_labels is not None:\n            self._update_combined_legend(shape_labels)\n        else:\n            self._update_shape_legend(shape_labels)\n            if cont_color:\n                self._update_continuous_color_legend(color_labels)\n            else:\n                self._update_color_legend(color_labels)\n        self.update_legend_visibility()\n\n    def _update_shape_legend(self, labels):\n        self.shape_legend.clear()\n        if labels is None or self.scatterplot_item is None:\n            return\n        color = QColor(0, 0, 0)\n        color.setAlpha(self.alpha_value)\n        for label, symbol in zip(labels, self.CurveSymbols):\n            self.shape_legend.addItem(\n                ScatterPlotItem(pen=color, brush=color, size=10, symbol=symbol),\n                escape(label))\n\n    def _update_continuous_color_legend(self, label_formatter):\n        self.color_legend.clear()\n        if self.scale is None or self.scatterplot_item is None:\n            return\n        label = PaletteItemSample(self.palette, self.scale, label_formatter)\n        self.color_legend.addItem(label, \"\")\n        self.color_legend.setGeometry(label.boundingRect())\n\n    def _update_color_legend(self, labels):\n        self.color_legend.clear()\n        if labels is None:\n            return\n        self._update_colored_legend(self.color_legend, labels, 'o')\n\n    def _update_combined_legend(self, labels):\n        # update_colored_legend will already clear the shape legend\n        # so we remove colors here\n        use_legend = \\\n            self.shape_legend if self.shape_legend.items else self.color_legend\n        self.color_legend.clear()\n        self.shape_legend.clear()\n        self._update_colored_legend(use_legend, labels, self.CurveSymbols)\n\n    def _update_colored_legend(self, legend, labels, symbols):\n        if self.scatterplot_item is None or not self.palette:\n            return\n        if isinstance(symbols, str):\n            symbols = itertools.repeat(symbols, times=len(labels))\n        for i, (label, symbol) in enumerate(zip(labels, symbols)):\n            color = QColor(*self.palette.getRGB(i))\n            pen = _make_pen(color.darker(self.DarkerValue), 1.5)\n            color.setAlpha(255 if self.subset_is_shown else self.alpha_value)\n            brush = QBrush(color)\n            legend.addItem(\n                ScatterPlotItem(pen=pen, brush=brush, size=10, symbol=symbol),\n                escape(label))\n\n    def zoom_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().RectMode)\n\n    def pan_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().PanMode)\n\n    def select_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().RectMode)\n\n    def reset_button_clicked(self):\n        self.plot_widget.getViewBox().autoRange()\n        self.update_labels()\n\n    def select_by_click(self, _, points):\n        if self.scatterplot_item is not None:\n            self.select(points)\n\n    def select_by_rectangle(self, rect):\n        if self.scatterplot_item is not None:\n            x0, x1 = sorted((rect.topLeft().x(), rect.bottomRight().x()))\n            y0, y1 = sorted((rect.topLeft().y(), rect.bottomRight().y()))\n            x, y = self.master.get_coordinates_data()\n            indices = np.flatnonzero(\n                (x0 <= x) & (x <= x1) & (y0 <= y) & (y <= y1))\n            self.select_by_indices(indices.astype(int))\n\n    def unselect_all(self):\n        if self.selection is not None:\n            self.selection = None\n            self.update_selection_colors()\n            if self.label_only_selected:\n                self.update_labels()\n            self.master.selection_changed()\n\n    def select(self, points):\n        # noinspection PyArgumentList\n        if self.scatterplot_item is None:\n            return\n        indices = [p.data() for p in points]\n        self.select_by_indices(indices)\n\n    def select_by_indices(self, indices):\n        if self.selection is None:\n            self.selection = np.zeros(self.n_valid, dtype=np.uint8)\n        keys = QApplication.keyboardModifiers()\n        if keys & Qt.AltModifier:\n            self.selection_remove(indices)\n        elif keys & Qt.ShiftModifier and keys & Qt.ControlModifier:\n            self.selection_append(indices)\n        elif keys & Qt.ShiftModifier:\n            self.selection_new_group(indices)\n        else:\n            self.selection_select(indices)\n\n    def selection_select(self, indices):\n        self.selection = np.zeros(self.n_valid, dtype=np.uint8)\n        self.selection[indices] = 1\n        self._update_after_selection()\n\n    def selection_append(self, indices):\n        self.selection[indices] = np.max(self.selection)\n        self._update_after_selection()\n\n    def selection_new_group(self, indices):\n        self.selection[indices] = np.max(self.selection) + 1\n        self._update_after_selection()\n\n    def selection_remove(self, indices):\n        self.selection[indices] = 0\n        self._update_after_selection()\n\n    def _update_after_selection(self):\n        self._compress_indices()\n        self.update_selection_colors()\n        if self.label_only_selected:\n            self.update_labels()\n        self.master.selection_changed()\n\n    def _compress_indices(self):\n        indices = sorted(set(self.selection) | {0})\n        if len(indices) == max(indices) + 1:\n            return\n        mapping = np.zeros((max(indices) + 1,), dtype=int)\n        for i, ind in enumerate(indices):\n            mapping[ind] = i\n        self.selection = mapping[self.selection]\n\n    def get_selection(self):\n        if self.selection is None:\n            return np.array([], dtype=np.uint8)\n        else:\n            return np.flatnonzero(self.selection)\n\n    def help_event(self, event):\n        \"\"\"\n        Create a `QToolTip` for the point hovered by the mouse\n        \"\"\"\n        if self.scatterplot_item is None:\n            return False\n        act_pos = self.scatterplot_item.mapFromScene(event.scenePos())\n        point_data = [p.data() for p in self.scatterplot_item.pointsAt(act_pos)]\n        text = self.master.get_tooltip(point_data)\n        if text:\n            QToolTip.showText(event.screenPos(), text, widget=self.plot_widget)\n            return True\n        else:\n            return False\n\n\nclass HelpEventDelegate(EventDelegate):\n    def __init__(self, delegate, parent=None):\n        super().__init__(delegate, parent)\n        warnings.warn(\"HelpEventDelegate class has been deprecated since 3.17.\"\n                      \" Use Orange.widgets.visualize.utils.plotutils.\"\n                      \"HelpEventDelegate instead.\", OrangeDeprecationWarning)\n",
            "new_file_content": "import sys\nimport itertools\nimport warnings\nfrom xml.sax.saxutils import escape\nfrom math import log10, floor, ceil\n\nimport numpy as np\nfrom AnyQt.QtCore import Qt, QRectF, QSize, QTimer, pyqtSignal as Signal, \\\n    QObject\nfrom AnyQt.QtGui import (\n    QStaticText, QColor, QPen, QBrush, QPainterPath, QTransform, QPainter\n)\nfrom AnyQt.QtWidgets import (\n    QApplication, QToolTip, QGraphicsTextItem, QGraphicsRectItem\n)\n\nimport pyqtgraph as pg\nimport pyqtgraph.graphicsItems.ScatterPlotItem\nfrom pyqtgraph.graphicsItems.LegendItem import (\n    LegendItem as PgLegendItem, ItemSample\n)\nfrom pyqtgraph.graphicsItems.TextItem import TextItem\n\nfrom Orange.util import OrangeDeprecationWarning\nfrom Orange.widgets import gui\nfrom Orange.widgets.settings import Setting\nfrom Orange.widgets.utils import classdensity\nfrom Orange.widgets.utils.colorpalette import ColorPaletteGenerator\nfrom Orange.widgets.utils.plot import OWPalette\nfrom Orange.widgets.visualize.owscatterplotgraph_obsolete import (\n    OWScatterPlotGraph as OWScatterPlotGraphObs\n)\nfrom Orange.widgets.visualize.utils.plotutils import (\n    HelpEventDelegate as EventDelegate,\n    InteractiveViewBox as ViewBox\n)\n\n\nSELECTION_WIDTH = 5\nMAX_N_VALID_SIZE_ANIMATE = 1000\n\n\nclass PaletteItemSample(ItemSample):\n    \"\"\"A color strip to insert into legends for discretized continuous values\"\"\"\n\n    def __init__(self, palette, scale, label_formatter=None):\n        \"\"\"\n        :param palette: palette used for showing continuous values\n        :type palette: ContinuousPaletteGenerator\n        :param scale: an instance of DiscretizedScale that defines the\n                      conversion of values into bins\n        :type scale: DiscretizedScale\n        \"\"\"\n        super().__init__(None)\n        self.palette = palette\n        self.scale = scale\n        if label_formatter is None:\n            label_formatter = \"{{:.{}f}}\".format(scale.decimals).format\n        cuts = [label_formatter(scale.offset + i * scale.width)\n                for i in range(scale.bins + 1)]\n        self.labels = [QStaticText(\"{} - {}\".format(fr, to))\n                       for fr, to in zip(cuts, cuts[1:])]\n        for label in self.labels:\n            label.prepare()\n        self.text_width = max(label.size().width() for label in self.labels)\n\n    def boundingRect(self):\n        return QRectF(0, 0, 40 + self.text_width, 20 + self.scale.bins * 15)\n\n    def paint(self, p, *args):\n        p.setRenderHint(p.Antialiasing)\n        scale = self.scale\n        font = p.font()\n        font.setPixelSize(11)\n        p.setFont(font)\n        for i, label in enumerate(self.labels):\n            color = QColor(*self.palette.getRGB((i + 0.5) / scale.bins))\n            p.setPen(Qt.NoPen)\n            p.setBrush(QBrush(color))\n            p.drawRect(0, i * 15, 15, 15)\n            p.setPen(QPen(Qt.black))\n            p.drawStaticText(20, i * 15 + 1, label)\n\n\nclass LegendItem(PgLegendItem):\n    def __init__(self, size=None, offset=None, pen=None, brush=None):\n        super().__init__(size, offset)\n\n        self.layout.setContentsMargins(5, 5, 5, 5)\n        self.layout.setHorizontalSpacing(15)\n        self.layout.setColumnAlignment(1, Qt.AlignLeft | Qt.AlignVCenter)\n\n        if pen is None:\n            pen = QPen(QColor(196, 197, 193, 200), 1)\n            pen.setCosmetic(True)\n        self.__pen = pen\n\n        if brush is None:\n            brush = QBrush(QColor(232, 232, 232, 100))\n        self.__brush = brush\n\n    def restoreAnchor(self, anchors):\n        \"\"\"\n        Restore (parent) relative position from stored anchors.\n\n        The restored position is within the parent bounds.\n        \"\"\"\n        anchor, parentanchor = anchors\n        self.anchor(*bound_anchor_pos(anchor, parentanchor))\n\n    def paint(self, painter, option, widget=None):\n        painter.setPen(self.__pen)\n        painter.setBrush(self.__brush)\n        rect = self.contentsRect()\n        painter.drawRoundedRect(rect, 2, 2)\n\n    def addItem(self, item, name):\n        super().addItem(item, name)\n        # Fix-up the label alignment\n        _, label = self.items[-1]\n        label.setText(name, justify=\"left\")\n\n    def clear(self):\n        \"\"\"\n        Clear all legend items.\n        \"\"\"\n        items = list(self.items)\n        self.items = []\n        for sample, label in items:\n            self.layout.removeItem(sample)\n            self.layout.removeItem(label)\n            sample.hide()\n            label.hide()\n\n        self.updateSize()\n\n\ndef bound_anchor_pos(corner, parentpos):\n    corner = np.clip(corner, 0, 1)\n    parentpos = np.clip(parentpos, 0, 1)\n\n    irx, iry = corner\n    prx, pry = parentpos\n\n    if irx > 0.9 and prx < 0.1:\n        irx = prx = 0.0\n    if iry > 0.9 and pry < 0.1:\n        iry = pry = 0.0\n    if irx < 0.1 and prx > 0.9:\n        irx = prx = 1.0\n    if iry < 0.1 and pry > 0.9:\n        iry = pry = 1.0\n    return (irx, iry), (prx, pry)\n\n\nclass DiscretizedScale:\n    \"\"\"\n    Compute suitable bins for continuous value from its minimal and\n    maximal value.\n\n    The width of the bin is a power of 10 (including negative powers).\n    The minimal value is rounded up and the maximal is rounded down. If this\n    gives less than 3 bins, the width is divided by four; if it gives\n    less than 6, it is halved.\n\n    .. attribute:: offset\n        The start of the first bin.\n\n    .. attribute:: width\n        The width of the bins\n\n    .. attribute:: bins\n        The number of bins\n\n    .. attribute:: decimals\n        The number of decimals used for printing out the boundaries\n    \"\"\"\n    def __init__(self, min_v, max_v):\n        \"\"\"\n        :param min_v: Minimal value\n        :type min_v: float\n        :param max_v: Maximal value\n        :type max_v: float\n        \"\"\"\n        super().__init__()\n        dif = max_v - min_v if max_v != min_v else 1\n        if np.isnan(dif):\n            min_v = 0\n            dif = decimals = 1\n        else:\n            decimals = -floor(log10(dif))\n        resolution = 10 ** -decimals\n        bins = ceil(dif / resolution)\n        if bins < 6:\n            decimals += 1\n            if bins < 3:\n                resolution /= 4\n            else:\n                resolution /= 2\n            bins = ceil(dif / resolution)\n        self.offset = resolution * floor(min_v // resolution)\n        self.bins = bins\n        self.decimals = max(decimals, 0)\n        self.width = resolution\n\n\nclass InteractiveViewBox(ViewBox):\n    def __init__(self, graph, enable_menu=False):\n        super().__init__(graph, enable_menu)\n        warnings.warn(\"InteractiveViewBox class has been deprecated since \"\n                      \"3.17. Use Orange.widgets.visualize.utils.plotutils.\"\n                      \"InteractiveViewBox instead.\", OrangeDeprecationWarning)\n\n\nclass OWScatterPlotGraph(OWScatterPlotGraphObs):\n    def __init__(self, scatter_widget, parent=None, _=\"None\", view_box=InteractiveViewBox):\n        super().__init__(scatter_widget, parent=parent, _=_, view_box=view_box)\n        warnings.warn(\"OWScatterPlotGraph class has been deprecated since \"\n                      \"3.17. Use OWScatterPlotBase instead.\",\n                      OrangeDeprecationWarning)\n\n\nclass ScatterPlotItem(pg.ScatterPlotItem):\n    \"\"\"PyQtGraph's ScatterPlotItem calls updateSpots at any change of sizes/colors/symbols,\n    which then rebuilds the stored pixmaps for each symbol. Because Orange calls\n    set* function in succession, we postpone updateSpots() to paint().\"\"\"\n\n    _update_spots_in_paint = False\n\n    def updateSpots(self, dataSet=None):  # pylint: disable=unused-argument\n        self._update_spots_in_paint = True\n        self.update()\n\n    def paint(self, painter, option, widget=None):\n        if self._update_spots_in_paint:\n            self._update_spots_in_paint = False\n            super().updateSpots()\n        painter.setRenderHint(QPainter.SmoothPixmapTransform, True)\n        super().paint(painter, option, widget)\n\n\ndef _define_symbols():\n    \"\"\"\n    Add symbol ? to ScatterPlotItemSymbols,\n    reflect the triangle to point upwards\n    \"\"\"\n    symbols = pyqtgraph.graphicsItems.ScatterPlotItem.Symbols\n    path = QPainterPath()\n    path.addEllipse(QRectF(-0.35, -0.35, 0.7, 0.7))\n    path.moveTo(-0.5, 0.5)\n    path.lineTo(0.5, -0.5)\n    path.moveTo(-0.5, -0.5)\n    path.lineTo(0.5, 0.5)\n    symbols[\"?\"] = path\n\n    tr = QTransform()\n    tr.rotate(180)\n    symbols['t'] = tr.map(symbols['t'])\n\n\n_define_symbols()\n\n\ndef _make_pen(color, width):\n    p = QPen(color, width)\n    p.setCosmetic(True)\n    return p\n\n\nclass OWScatterPlotBase(gui.OWComponent, QObject):\n    \"\"\"\n    Provide a graph component for widgets that show any kind of point plot\n\n    The component plots a set of points with given coordinates, shapes,\n    sizes and colors. Its function is similar to that of a *view*, whereas\n    the widget represents a *model* and a *controler*.\n\n    The model (widget) needs to provide methods:\n\n    - `get_coordinates_data`, `get_size_data`, `get_color_data`,\n      `get_shape_data`, `get_label_data`, which return a 1d array (or two\n      arrays, for `get_coordinates_data`) of `dtype` `float64`, except for\n      `get_label_data`, which returns formatted labels;\n    - `get_shape_labels` returns a list of strings for shape legend\n    - `get_color_labels` returns strings for color legend, or a function for\n       formatting numbers if the legend is continuous, or None for default\n       formatting\n    - `get_tooltip`, which gives a tooltip for a single data point\n    - (optional) `impute_sizes`, `impute_shapes` get final coordinates and\n      shapes, and replace nans;\n    - `get_subset_mask` returns a bool array indicating whether a\n      data point is in the subset or not (e.g. in the 'Data Subset' signal\n      in the Scatter plot and similar widgets);\n    - `get_palette` returns a palette appropriate for visualizing the\n      current color data;\n    - `is_continuous_color` decides the type of the color legend;\n\n    The widget (in a role of controller) must also provide methods\n    - `selection_changed`\n\n    If `get_coordinates_data` returns `(None, None)`, the plot is cleared. If\n    `get_size_data`, `get_color_data` or `get_shape_data` return `None`,\n    all points will have the same size, color or shape, respectively.\n    If `get_label_data` returns `None`, there are no labels.\n\n    The view (this compomnent) provides methods `update_coordinates`,\n    `update_sizes`, `update_colors`, `update_shapes` and `update_labels`\n    that the widget (in a role of a controler) should call when any of\n    these properties are changed. If the widget calls, for instance, the\n    plot's `update_colors`, the plot will react by calling the widget's\n    `get_color_data` as well as the widget's methods needed to construct the\n    legend.\n\n    The view also provides a method `reset_graph`, which should be called only\n    when\n    - the widget gets entirely new data\n    - the number of points may have changed, for instance when selecting\n    a different attribute for x or y in the scatter plot, where the points\n    with missing x or y coordinates are hidden.\n\n    Every `update_something` calls the plot's `get_something`, which\n    calls the model's `get_something_data`, then it transforms this data\n    into whatever is needed (colors, shapes, scaled sizes) and changes the\n    plot. For the simplest example, here is `update_shapes`:\n\n    ```\n        def update_shapes(self):\n            if self.scatterplot_item:\n                shape_data = self.get_shapes()\n                self.scatterplot_item.setSymbol(shape_data)\n            self.update_legends()\n\n        def get_shapes(self):\n            shape_data = self.master.get_shape_data()\n            shape_data = self.master.impute_shapes(\n                shape_data, len(self.CurveSymbols) - 1)\n            return self.CurveSymbols[shape_data]\n    ```\n\n    On the widget's side, `get_something_data` is essentially just:\n\n    ```\n        def get_size_data(self):\n            return self.get_column(self.attr_size)\n    ```\n\n    where `get_column` retrieves a column while also filtering out the\n    points with missing x and y and so forth. (Here we present the simplest\n    two cases, \"shapes\" for the view and \"sizes\" for the model. The colors\n    for the view are more complicated since they deal with discrete and\n    continuous palettes, and the shapes for the view merge infrequent shapes.)\n\n    The plot can also show just a random sample of the data. The sample size is\n    set by `set_sample_size`, and the rest is taken care by the plot: the\n    widget keeps providing the data for all points, selection indices refer\n    to the entire set etc. Internally, sampling happens as early as possible\n    (in methods `get_<something>`).\n    \"\"\"\n    too_many_labels = Signal(bool)\n    begin_resizing = Signal()\n    step_resizing = Signal()\n    end_resizing = Signal()\n\n    label_only_selected = Setting(False)\n    point_width = Setting(10)\n    alpha_value = Setting(128)\n    show_grid = Setting(False)\n    show_legend = Setting(True)\n    class_density = Setting(False)\n    jitter_size = Setting(0)\n\n    resolution = 256\n\n    CurveSymbols = np.array(\"o x t + d star ?\".split())\n    MinShapeSize = 6\n    DarkerValue = 120\n    UnknownColor = (168, 50, 168)\n\n    COLOR_NOT_SUBSET = (128, 128, 128, 0)\n    COLOR_SUBSET = (128, 128, 128, 255)\n    COLOR_DEFAULT = (128, 128, 128, 0)\n\n    MAX_VISIBLE_LABELS = 500\n\n    def __init__(self, scatter_widget, parent=None, view_box=ViewBox):\n        QObject.__init__(self)\n        gui.OWComponent.__init__(self, scatter_widget)\n\n        self.subset_is_shown = False\n\n        self.view_box = view_box(self)\n        self.plot_widget = pg.PlotWidget(viewBox=self.view_box, parent=parent,\n                                         background=\"w\")\n        self.plot_widget.hideAxis(\"left\")\n        self.plot_widget.hideAxis(\"bottom\")\n        self.plot_widget.getPlotItem().buttonsHidden = True\n        self.plot_widget.setAntialiasing(True)\n        self.plot_widget.sizeHint = lambda: QSize(500, 500)\n\n        self.density_img = None\n        self.scatterplot_item = None\n        self.scatterplot_item_sel = None\n        self.labels = []\n\n        self.master = scatter_widget\n        self._create_drag_tooltip(self.plot_widget.scene())\n\n        self.selection = None  # np.ndarray\n\n        self.n_valid = 0\n        self.n_shown = 0\n        self.sample_size = None\n        self.sample_indices = None\n\n        self.palette = None\n\n        self.shape_legend = self._create_legend(((1, 0), (1, 0)))\n        self.color_legend = self._create_legend(((1, 1), (1, 1)))\n        self.update_legend_visibility()\n\n        self.scale = None  # DiscretizedScale\n        self._too_many_labels = False\n\n        # self.setMouseTracking(True)\n        # self.grabGesture(QPinchGesture)\n        # self.grabGesture(QPanGesture)\n\n        self.update_grid_visibility()\n\n        self._tooltip_delegate = EventDelegate(self.help_event)\n        self.plot_widget.scene().installEventFilter(self._tooltip_delegate)\n        self.view_box.sigTransformChanged.connect(self.update_density)\n        self.view_box.sigRangeChangedManually.connect(self.update_labels)\n\n        self.timer = None\n\n    def _create_legend(self, anchor):\n        legend = LegendItem()\n        legend.setParentItem(self.plot_widget.getViewBox())\n        legend.restoreAnchor(anchor)\n        return legend\n\n    def _create_drag_tooltip(self, scene):\n        tip_parts = [\n            (Qt.ShiftModifier, \"Shift: Add group\"),\n            (Qt.ShiftModifier + Qt.ControlModifier,\n             \"Shift-{}: Append to group\".\n             format(\"Cmd\" if sys.platform == \"darwin\" else \"Ctrl\")),\n            (Qt.AltModifier, \"Alt: Remove\")\n        ]\n        all_parts = \", \".join(part for _, part in tip_parts)\n        self.tiptexts = {\n            int(modifier): all_parts.replace(part, \"<b>{}</b>\".format(part))\n            for modifier, part in tip_parts\n        }\n        self.tiptexts[0] = all_parts\n\n        self.tip_textitem = text = QGraphicsTextItem()\n        # Set to the longest text\n        text.setHtml(self.tiptexts[Qt.ShiftModifier + Qt.ControlModifier])\n        text.setPos(4, 2)\n        r = text.boundingRect()\n        rect = QGraphicsRectItem(0, 0, r.width() + 8, r.height() + 4)\n        rect.setBrush(QColor(224, 224, 224, 212))\n        rect.setPen(QPen(Qt.NoPen))\n        self.update_tooltip()\n\n        scene.drag_tooltip = scene.createItemGroup([rect, text])\n        scene.drag_tooltip.hide()\n\n    def update_tooltip(self, modifiers=Qt.NoModifier):\n        modifiers &= Qt.ShiftModifier + Qt.ControlModifier + Qt.AltModifier\n        text = self.tiptexts.get(int(modifiers), self.tiptexts[0])\n        self.tip_textitem.setHtml(text + self._get_jittering_tooltip())\n\n    def _get_jittering_tooltip(self):\n        warn_jittered = \"\"\n        if self.jitter_size:\n            warn_jittered = \\\n                '<br/><br/>' \\\n                '<span style=\"background-color: red; color: white; ' \\\n                'font-weight: 500;\">' \\\n                '&nbsp;Warning: Selection is applied to unjittered data&nbsp;' \\\n                '</span>'\n        return warn_jittered\n\n    def update_jittering(self):\n        self.update_tooltip()\n        x, y = self.get_coordinates()\n        if x is None or not len(x) or self.scatterplot_item is None:\n            return\n        self._update_plot_coordinates(self.scatterplot_item, x, y)\n        self._update_plot_coordinates(self.scatterplot_item_sel, x, y)\n        self.update_labels()\n\n    # TODO: Rename to remove_plot_items\n    def clear(self):\n        \"\"\"\n        Remove all graphical elements from the plot\n\n        Calls the pyqtgraph's plot widget's clear, sets all handles to `None`,\n        removes labels and selections.\n\n        This method should generally not be called by the widget. If the data\n        is gone (*e.g.* upon receiving `None` as an input data signal), this\n        should be handler by calling `reset_graph`, which will in turn call\n        `clear`.\n\n        Derived classes should override this method if they add more graphical\n        elements. For instance, the regression line in the scatterplot adds\n        `self.reg_line_item = None` (the line in the plot is already removed\n        in this method).\n        \"\"\"\n        self.plot_widget.clear()\n\n        self.density_img = None\n        if self.timer is not None and self.timer.isActive():\n            self.timer.stop()\n            self.timer = None\n        self.scatterplot_item = None\n        self.scatterplot_item_sel = None\n        self.labels = []\n        self._signal_too_many_labels(False)\n        self.view_box.init_history()\n        self.view_box.tag_history()\n\n    # TODO: I hate `keep_something` and `reset_something` arguments\n    # __keep_selection is used exclusively be set_sample size which would\n    # otherwise just repeat the code from reset_graph except for resetting\n    # the selection. I'm uncomfortable with this; we may prefer to have a\n    # method _reset_graph which does everything except resetting the selection,\n    # and reset_graph would call it.\n    def reset_graph(self, __keep_selection=False):\n        \"\"\"\n        Reset the graph to new data (or no data)\n\n        The method must be called when the plot receives new data, in\n        particular when the number of points change. If only their properties\n        - like coordinates or shapes - change, an update method\n        (`update_coordinates`, `update_shapes`...) should be called instead.\n\n        The method must also be called when the data is gone.\n\n        The method calls `clear`, followed by calls of all update methods.\n\n        NB. Argument `__keep_selection` is for internal use only\n        \"\"\"\n        self.clear()\n        if not __keep_selection:\n            self.selection = None\n        self.sample_indices = None\n        self.update_coordinates()\n        self.update_point_props()\n\n    def set_sample_size(self, sample_size):\n        \"\"\"\n        Set the sample size\n\n        Args:\n            sample_size (int or None): sample size or `None` to show all points\n        \"\"\"\n        if self.sample_size != sample_size:\n            self.sample_size = sample_size\n            self.reset_graph(True)\n\n    def update_point_props(self):\n        \"\"\"\n        Update the sizes, colors, shapes and labels\n\n        The method calls the appropriate update methods for individual\n        properties.\n        \"\"\"\n        self.update_sizes()\n        self.update_colors()\n        self.update_selection_colors()\n        self.update_shapes()\n        self.update_labels()\n\n    # Coordinates\n    # TODO: It could be nice if this method was run on entire data, not just\n    # a sample. For this, however, it would need to either be called from\n    # `get_coordinates` before sampling (very ugly) or call\n    # `self.master.get_coordinates_data` (beyond ugly) or the widget would\n    # have to store the ranges of unsampled data (ugly).\n    # Maybe we leave it as it is.\n    def _reset_view(self, x_data, y_data):\n        \"\"\"\n        Set the range of the view box\n\n        Args:\n            x_data (np.ndarray): x coordinates\n            y_data (np.ndarray) y coordinates\n        \"\"\"\n        min_x, max_x = np.min(x_data), np.max(x_data)\n        min_y, max_y = np.min(y_data), np.max(y_data)\n        self.view_box.setRange(\n            QRectF(min_x, min_y, max_x - min_x or 1, max_y - min_y or 1),\n            padding=0.025)\n\n    def _filter_visible(self, data):\n        \"\"\"Return the sample from the data using the stored sample_indices\"\"\"\n        if data is None or self.sample_indices is None:\n            return data\n        else:\n            return np.asarray(data[self.sample_indices])\n\n    def get_coordinates(self):\n        \"\"\"\n        Prepare coordinates of the points in the plot\n\n        The method is called by `update_coordinates`. It gets the coordinates\n        from the widget, jitters them and return them.\n\n        The methods also initializes the sample indices if neededd and stores\n        the original and sampled number of points.\n\n        Returns:\n            (tuple): a pair of numpy arrays containing (sampled) coordinates,\n                or `(None, None)`.\n        \"\"\"\n        x, y = self.master.get_coordinates_data()\n        if x is None:\n            self.n_valid = self.n_shown = 0\n            return None, None\n        self.n_valid = len(x)\n        self._create_sample()\n        x = self._filter_visible(x)\n        y = self._filter_visible(y)\n        # Jittering after sampling is OK if widgets do not change the sample\n        # semi-permanently, e.g. take a sample for the duration of some\n        # animation. If the sample size changes dynamically (like by adding\n        # a \"sample size\" slider), points would move around when the sample\n        # size changes. To prevent this, jittering should be done before\n        # sampling (i.e. two lines earlier). This would slow it down somewhat.\n        x, y = self.jitter_coordinates(x, y)\n        return x, y\n\n    def _create_sample(self):\n        \"\"\"\n        Create a random sample if the data is larger than the set sample size\n        \"\"\"\n        self.n_shown = min(self.n_valid, self.sample_size or self.n_valid)\n        if self.sample_size is not None \\\n                and self.sample_indices is None \\\n                and self.n_valid != self.n_shown:\n            random = np.random.RandomState(seed=0)\n            self.sample_indices = random.choice(\n                self.n_valid, self.n_shown, replace=False)\n            # TODO: Is this really needed?\n            np.sort(self.sample_indices)\n\n    def jitter_coordinates(self, x, y):\n        \"\"\"\n        Display coordinates to random positions within ellipses with\n        radiuses of `self.jittter_size` percents of spans\n        \"\"\"\n        if self.jitter_size == 0:\n            return x, y\n        return self._jitter_data(x, y)\n\n    def _jitter_data(self, x, y, span_x=None, span_y=None):\n        if span_x is None:\n            span_x = np.max(x) - np.min(x)\n        if span_y is None:\n            span_y = np.max(y) - np.min(y)\n        random = np.random.RandomState(seed=0)\n        rs = random.uniform(0, 1, len(x))\n        phis = random.uniform(0, 2 * np.pi, len(x))\n        magnitude = self.jitter_size / 100\n        return (x + magnitude * span_x * rs * np.cos(phis),\n                y + magnitude * span_y * rs * np.sin(phis))\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n\n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n            data[prop] = plot.data[prop]\n        plot.setData(**data)\n\n    def update_coordinates(self):\n        \"\"\"\n        Trigger the update of coordinates while keeping other features intact.\n\n        The method gets the coordinates by calling `self.get_coordinates`,\n        which in turn calls the widget's `get_coordinate_data`. The number of\n        coordinate pairs returned by the latter must match the current number\n        of points. If this is not the case, the widget should trigger\n        the complete update by calling `reset_graph` instead of this method.\n        \"\"\"\n        x, y = self.get_coordinates()\n        if x is None or not len(x):\n            return\n        if self.scatterplot_item is None:\n            if self.sample_indices is None:\n                indices = np.arange(self.n_valid)\n            else:\n                indices = self.sample_indices\n            kwargs = dict(x=x, y=y, data=indices)\n            self.scatterplot_item = ScatterPlotItem(**kwargs)\n            self.scatterplot_item.sigClicked.connect(self.select_by_click)\n            self.scatterplot_item_sel = ScatterPlotItem(**kwargs)\n            self.plot_widget.addItem(self.scatterplot_item_sel)\n            self.plot_widget.addItem(self.scatterplot_item)\n        else:\n            self._update_plot_coordinates(self.scatterplot_item, x, y)\n            self._update_plot_coordinates(self.scatterplot_item_sel, x, y)\n            self.update_labels()\n\n        self.update_density()  # Todo: doesn't work: try MDS with density on\n        self._reset_view(x, y)\n\n    # Sizes\n    def get_sizes(self):\n        \"\"\"\n        Prepare data for sizes of points in the plot\n\n        The method is called by `update_sizes`. It gets the sizes\n        from the widget and performs the necessary scaling and sizing.\n        The output is rounded to half a pixel for faster drawing.\n\n        Returns:\n            (np.ndarray): sizes\n        \"\"\"\n        size_column = self.master.get_size_data()\n        if size_column is None:\n            return np.full((self.n_shown,),\n                           self.MinShapeSize + (5 + self.point_width) * 0.5)\n        size_column = self._filter_visible(size_column)\n        size_column = size_column.copy()\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n            size_column -= np.nanmin(size_column)\n            mx = np.nanmax(size_column)\n        if mx > 0:\n            size_column /= mx\n        else:\n            size_column[:] = 0.5\n\n        sizes = self.MinShapeSize + (5 + self.point_width) * size_column\n        # round sizes to half pixel for smaller pyqtgraph's symbol pixmap atlas\n        sizes = (sizes * 2).round() / 2\n        return sizes\n\n    def update_sizes(self):\n        \"\"\"\n        Trigger an update of point sizes\n\n        The method calls `self.get_sizes`, which in turn calls the widget's\n        `get_size_data`. The result are properly scaled and then passed\n        back to widget for imputing (`master.impute_sizes`).\n        \"\"\"\n        if self.scatterplot_item:\n            size_data = self.get_sizes()\n            size_imputer = getattr(\n                self.master, \"impute_sizes\", self.default_impute_sizes)\n            size_imputer(size_data)\n\n            if self.timer is not None and self.timer.isActive():\n                self.timer.stop()\n                self.timer = None\n\n            current_size_data = self.scatterplot_item.data[\"size\"].copy()\n            diff = size_data - current_size_data\n            widget = self\n\n            class Timeout:\n                # 0.5 - np.cos(np.arange(0.17, 1, 0.17) * np.pi) / 2\n                factors = [0.07, 0.26, 0.52, 0.77, 0.95, 1]\n\n                def __init__(self):\n                    self._counter = 0\n\n                def __call__(self):\n                    factor = self.factors[self._counter]\n                    self._counter += 1\n                    size = current_size_data + diff * factor\n                    if len(self.factors) == self._counter:\n                        widget.timer.stop()\n                        widget.timer = None\n                        size = size_data\n                    widget.scatterplot_item.setSize(size)\n                    widget.scatterplot_item_sel.setSize(size + SELECTION_WIDTH)\n                    if widget.timer is None:\n                        widget.end_resizing.emit()\n                    else:\n                        widget.step_resizing.emit()\n\n            if self.n_valid <= MAX_N_VALID_SIZE_ANIMATE and \\\n                    np.all(current_size_data > 0) and np.any(diff != 0):\n                # If encountered any strange behaviour when updating sizes,\n                # implement it with threads\n                self.begin_resizing.emit()\n                self.timer = QTimer(self.scatterplot_item, interval=50)\n                self.timer.timeout.connect(Timeout())\n                self.timer.start()\n            else:\n                self.begin_resizing.emit()\n                self.scatterplot_item.setSize(size_data)\n                self.scatterplot_item_sel.setSize(size_data + SELECTION_WIDTH)\n                self.end_resizing.emit()\n\n    update_point_size = update_sizes  # backward compatibility (needed?!)\n    update_size = update_sizes\n\n    @classmethod\n    def default_impute_sizes(cls, size_data):\n        \"\"\"\n        Fallback imputation for sizes.\n\n        Set the size to two pixels smaller than the minimal size\n\n        Returns:\n            (bool): True if there was any missing data\n        \"\"\"\n        nans = np.isnan(size_data)\n        if np.any(nans):\n            size_data[nans] = cls.MinShapeSize - 2\n            return True\n        else:\n            return False\n\n    # Colors\n    def get_colors(self):\n        \"\"\"\n        Prepare data for colors of the points in the plot\n\n        The method is called by `update_colors`. It gets the colors and the\n        indices of the data subset from the widget (`get_color_data`,\n        `get_subset_mask`), and constructs lists of pens and brushes for\n        each data point.\n\n        The method uses different palettes for discrete and continuous data,\n        as determined by calling the widget's method `is_continuous_color`.\n\n        If also marks the points that are in the subset as defined by, for\n        instance the 'Data Subset' signal in the Scatter plot and similar\n        widgets. (Do not confuse this with *selected points*, which are\n        marked by circles around the points, which are colored by groups\n        and thus independent of this method.)\n\n        Returns:\n            (tuple): a list of pens and list of brushes\n        \"\"\"\n        self.palette = self.master.get_palette()\n        c_data = self.master.get_color_data()\n        c_data = self._filter_visible(c_data)\n        subset = self.master.get_subset_mask()\n        subset = self._filter_visible(subset)\n        self.subset_is_shown = subset is not None\n        if c_data is None:  # same color\n            return self._get_same_colors(subset)\n        elif self.master.is_continuous_color():\n            return self._get_continuous_colors(c_data, subset)\n        else:\n            return self._get_discrete_colors(c_data, subset)\n\n    def _get_same_colors(self, subset):\n        \"\"\"\n        Return the same pen for all points while the brush color depends\n        upon whether the point is in the subset or not\n\n        Args:\n            subset (np.ndarray): a bool array indicating whether a data point\n                is in the subset or not (e.g. in the 'Data Subset' signal\n                in the Scatter plot and similar widgets);\n\n        Returns:\n            (tuple): a list of pens and list of brushes\n        \"\"\"\n        color = self.plot_widget.palette().color(OWPalette.Data)\n        pen = [_make_pen(color, 1.5)] * self.n_shown  # use a single QPen instance\n        if subset is not None:\n            brush = np.where(\n                subset,\n                *(QBrush(QColor(*col))\n                  for col in (self.COLOR_SUBSET, self.COLOR_NOT_SUBSET)))\n        else:\n            color = QColor(*self.COLOR_DEFAULT)\n            color.setAlpha(self.alpha_value)\n            brush = [QBrush(color)] * self.n_shown  # use a single QBrush instance\n        return pen, brush\n\n    def _get_continuous_colors(self, c_data, subset):\n        \"\"\"\n        Return the pens and colors whose color represent an index into\n        a continuous palette. The same color is used for pen and brush,\n        except the former is darker. If the data has a subset, the brush\n        is transparent for points that are not in the subset.\n        \"\"\"\n        if np.isnan(c_data).all():\n            self.scale = None\n        else:\n            self.scale = DiscretizedScale(np.nanmin(c_data), np.nanmax(c_data))\n            c_data -= self.scale.offset\n            c_data /= self.scale.width\n            c_data = np.floor(c_data) + 0.5\n            c_data /= self.scale.bins\n            c_data = np.clip(c_data, 0, 1)\n        pen = self.palette.getRGB(c_data)\n        brush = np.hstack(\n            [pen, np.full((len(pen), 1), self.alpha_value, dtype=int)])\n        pen *= 100\n        pen //= self.DarkerValue\n\n        # Reuse pens and brushes with the same colors because PyQtGraph then builds\n        # smaller pixmap atlas, which makes the drawing faster\n\n        def reuse(cache, fn, *args):\n            if args not in cache:\n                cache[args] = fn(args)\n            return cache[args]\n\n        def create_pen(col):\n            return _make_pen(QColor(*col), 1.5)\n\n        def create_brush(col):\n            return QBrush(QColor(*col))\n\n        cached_pens = {}\n        pen = [reuse(cached_pens, create_pen, *col) for col in pen.tolist()]\n\n        if subset is not None:\n            brush[:, 3] = 0\n            brush[subset, 3] = 255\n\n        cached_brushes = {}\n        brush = np.array([reuse(cached_brushes, create_brush, *col) for col in brush.tolist()])\n\n        return pen, brush\n\n    def _get_discrete_colors(self, c_data, subset):\n        \"\"\"\n        Return the pens and colors whose color represent an index into\n        a discrete palette. The same color is used for pen and brush,\n        except the former is darker. If the data has a subset, the brush\n        is transparent for points that are not in the subset.\n        \"\"\"\n        n_colors = self.palette.number_of_colors\n        c_data = c_data.copy()\n        c_data[np.isnan(c_data)] = n_colors\n        c_data = c_data.astype(int)\n        colors = np.r_[self.palette.getRGB(np.arange(n_colors)),\n                       [[128, 128, 128]]]\n        pens = np.array(\n            [_make_pen(QColor(*col).darker(self.DarkerValue), 1.5)\n             for col in colors])\n        pen = pens[c_data]\n        alpha = self.alpha_value if subset is None else 255\n        brushes = np.array([\n            [QBrush(QColor(0, 0, 0, 0)),\n             QBrush(QColor(col[0], col[1], col[2], alpha))]\n            for col in colors])\n        brush = brushes[c_data]\n\n        if subset is not None:\n            brush = np.where(subset, brush[:, 1], brush[:, 0])\n        else:\n            brush = brush[:, 1]\n        return pen, brush\n\n    def update_colors(self):\n        \"\"\"\n        Trigger an update of point sizes\n\n        The method calls `self.get_colors`, which in turn calls the widget's\n        `get_color_data` to get the indices in the pallette. `get_colors`\n        returns a list of pens and brushes to which this method uses to\n        update the colors. Finally, the method triggers the update of the\n        legend and the density plot.\n        \"\"\"\n        if self.scatterplot_item is not None:\n            pen_data, brush_data = self.get_colors()\n            self.scatterplot_item.setPen(pen_data, update=False, mask=None)\n            self.scatterplot_item.setBrush(brush_data, mask=None)\n        self.update_legends()\n        self.update_density()\n\n    update_alpha_value = update_colors\n\n    def update_density(self):\n        \"\"\"\n        Remove the existing density plot (if there is one) and replace it\n        with a new one (if enabled).\n\n        The method gets the colors from the pens of the currently plotted\n        points.\n        \"\"\"\n        if self.density_img:\n            self.plot_widget.removeItem(self.density_img)\n            self.density_img = None\n        if self.class_density and self.scatterplot_item is not None:\n            rgb_data = [\n                pen.color().getRgb()[:3] if pen is not None else (255, 255, 255)\n                for pen in self.scatterplot_item.data['pen']]\n            if len(set(rgb_data)) <= 1:\n                return\n            [min_x, max_x], [min_y, max_y] = self.view_box.viewRange()\n            x_data, y_data = self.scatterplot_item.getData()\n            self.density_img = classdensity.class_density_image(\n                min_x, max_x, min_y, max_y, self.resolution,\n                x_data, y_data, rgb_data)\n            self.plot_widget.addItem(self.density_img)\n\n    def update_selection_colors(self):\n        \"\"\"\n        Trigger an update of selection markers\n\n        This update method is usually not called by the widget but by the\n        plot, since it is the plot that handles the selections.\n\n        Like other update methods, it calls the corresponding get method\n        (`get_colors_sel`) which returns a list of pens and brushes.\n        \"\"\"\n        if self.scatterplot_item_sel is None:\n            return\n        pen, brush = self.get_colors_sel()\n        self.scatterplot_item_sel.setPen(pen, update=False, mask=None)\n        self.scatterplot_item_sel.setBrush(brush, mask=None)\n\n    def get_colors_sel(self):\n        \"\"\"\n        Return pens and brushes for selection markers.\n\n        A pen can is set to `Qt.NoPen` if a point is not selected.\n\n        All brushes are completely transparent whites.\n\n        Returns:\n            (tuple): a list of pens and a list of brushes\n        \"\"\"\n        nopen = QPen(Qt.NoPen)\n        if self.selection is None:\n            pen = [nopen] * self.n_shown\n        else:\n            sels = np.max(self.selection)\n            if sels == 1:\n                pen = np.where(\n                    self._filter_visible(self.selection),\n                    _make_pen(QColor(255, 190, 0, 255), SELECTION_WIDTH + 1),\n                    nopen)\n            else:\n                palette = ColorPaletteGenerator(number_of_colors=sels + 1)\n                pen = np.choose(\n                    self._filter_visible(self.selection),\n                    [nopen] + [_make_pen(palette[i], SELECTION_WIDTH + 1)\n                               for i in range(sels)])\n        return pen, [QBrush(QColor(255, 255, 255, 0))] * self.n_shown\n\n    # Labels\n    def get_labels(self):\n        \"\"\"\n        Prepare data for labels for points\n\n        The method returns the results of the widget's `get_label_data`\n\n        Returns:\n            (labels): a sequence of labels\n        \"\"\"\n        return self._filter_visible(self.master.get_label_data())\n\n    def update_labels(self):\n        \"\"\"\n        Trigger an update of labels\n\n        The method calls `get_labels` which in turn calls the widget's\n        `get_label_data`. The obtained labels are shown if the corresponding\n        points are selected or if `label_only_selected` is `false`.\n        \"\"\"\n        for label in self.labels:\n            self.plot_widget.removeItem(label)\n        self.labels = []\n\n        mask = None\n        if self.scatterplot_item is not None:\n            x, y = self.scatterplot_item.getData()\n            mask = self._label_mask(x, y)\n\n        if mask is not None:\n            labels = self.get_labels()\n            if labels is None:\n                mask = None\n\n        self._signal_too_many_labels(\n            mask is not None and mask.sum() > self.MAX_VISIBLE_LABELS)\n        if self._too_many_labels or mask is None or not np.any(mask):\n            return\n\n        black = pg.mkColor(0, 0, 0)\n        labels = labels[mask]\n        x = x[mask]\n        y = y[mask]\n        for label, xp, yp in zip(labels, x, y):\n            ti = TextItem(label, black)\n            ti.setPos(xp, yp)\n            self.plot_widget.addItem(ti)\n            self.labels.append(ti)\n\n    def _signal_too_many_labels(self, too_many):\n        if self._too_many_labels != too_many:\n            self._too_many_labels = too_many\n            self.too_many_labels.emit(too_many)\n\n    def _label_mask(self, x, y):\n        (x0, x1), (y0, y1) = self.view_box.viewRange()\n        mask = np.logical_and(\n            np.logical_and(x >= x0, x <= x1),\n            np.logical_and(y >= y0, y <= y1))\n        if self.label_only_selected:\n            sub_mask = self._filter_visible(self.master.get_subset_mask())\n            if self.selection is None:\n                if sub_mask is None:\n                    return None\n                else:\n                    sel_mask = sub_mask\n            else:\n                sel_mask = self._filter_visible(self.selection) != 0\n                if sub_mask is not None:\n                    sel_mask = np.logical_or(sel_mask, sub_mask)\n            mask = np.logical_and(mask, sel_mask)\n        return mask\n\n    # Shapes\n    def get_shapes(self):\n        \"\"\"\n        Prepare data for shapes of points in the plot\n\n        The method is called by `update_shapes`. It gets the data from\n        the widget's `get_shape_data`, and then calls its `impute_shapes`\n        to impute the missing shape (usually with some default shape).\n\n        Returns:\n            (np.ndarray): an array of symbols (e.g. o, x, + ...)\n        \"\"\"\n        shape_data = self.master.get_shape_data()\n        shape_data = self._filter_visible(shape_data)\n        # Data has to be copied so the imputation can change it in-place\n        # TODO: Try avoiding this when we move imputation to the widget\n        if shape_data is not None:\n            shape_data = np.copy(shape_data)\n        shape_imputer = getattr(\n            self.master, \"impute_shapes\", self.default_impute_shapes)\n        shape_imputer(shape_data, len(self.CurveSymbols) - 1)\n        if isinstance(shape_data, np.ndarray):\n            shape_data = shape_data.astype(int)\n        else:\n            shape_data = np.zeros(self.n_shown, dtype=int)\n        return self.CurveSymbols[shape_data]\n\n    @staticmethod\n    def default_impute_shapes(shape_data, default_symbol):\n        \"\"\"\n        Fallback imputation for shapes.\n\n        Use the default symbol, usually the last symbol in the list.\n\n        Returns:\n            (bool): True if there was any missing data\n        \"\"\"\n        if shape_data is None:\n            return False\n        nans = np.isnan(shape_data)\n        if np.any(nans):\n            shape_data[nans] = default_symbol\n            return True\n        else:\n            return False\n\n    def update_shapes(self):\n        \"\"\"\n        Trigger an update of point symbols\n\n        The method calls `get_shapes` to obtain an array with a symbol\n        for each point and uses it to update the symbols.\n\n        Finally, the method updates the legend.\n        \"\"\"\n        if self.scatterplot_item:\n            shape_data = self.get_shapes()\n            self.scatterplot_item.setSymbol(shape_data)\n        self.update_legends()\n\n    def update_grid_visibility(self):\n        \"\"\"Show or hide the grid\"\"\"\n        self.plot_widget.showGrid(x=self.show_grid, y=self.show_grid)\n\n    def update_legend_visibility(self):\n        \"\"\"\n        Show or hide legends based on whether they are enabled and non-empty\n        \"\"\"\n        self.shape_legend.setVisible(\n            self.show_legend and bool(self.shape_legend.items))\n        self.color_legend.setVisible(\n            self.show_legend and bool(self.color_legend.items))\n\n    def update_legends(self):\n        \"\"\"Update content of legends and their visibility\"\"\"\n        cont_color = self.master.is_continuous_color()\n        shape_labels = self.master.get_shape_labels()\n        color_labels = self.master.get_color_labels()\n        if not cont_color and shape_labels is not None \\\n                and shape_labels == color_labels:\n            colors = self.master.get_color_data()\n            shapes = self.master.get_shape_data()\n            mask = np.isfinite(colors) * np.isfinite(shapes)\n            combined = (colors == shapes)[mask].all()\n        else:\n            combined = False\n        if combined:\n            self._update_combined_legend(shape_labels)\n        else:\n            self._update_shape_legend(shape_labels)\n            if cont_color:\n                self._update_continuous_color_legend(color_labels)\n            else:\n                self._update_color_legend(color_labels)\n        self.update_legend_visibility()\n\n    def _update_shape_legend(self, labels):\n        self.shape_legend.clear()\n        if labels is None or self.scatterplot_item is None:\n            return\n        color = QColor(0, 0, 0)\n        color.setAlpha(self.alpha_value)\n        for label, symbol in zip(labels, self.CurveSymbols):\n            self.shape_legend.addItem(\n                ScatterPlotItem(pen=color, brush=color, size=10, symbol=symbol),\n                escape(label))\n\n    def _update_continuous_color_legend(self, label_formatter):\n        self.color_legend.clear()\n        if self.scale is None or self.scatterplot_item is None:\n            return\n        label = PaletteItemSample(self.palette, self.scale, label_formatter)\n        self.color_legend.addItem(label, \"\")\n        self.color_legend.setGeometry(label.boundingRect())\n\n    def _update_color_legend(self, labels):\n        self.color_legend.clear()\n        if labels is None:\n            return\n        self._update_colored_legend(self.color_legend, labels, 'o')\n\n    def _update_combined_legend(self, labels):\n        # update_colored_legend will already clear the shape legend\n        # so we remove colors here\n        use_legend = \\\n            self.shape_legend if self.shape_legend.items else self.color_legend\n        self.color_legend.clear()\n        self.shape_legend.clear()\n        self._update_colored_legend(use_legend, labels, self.CurveSymbols)\n\n    def _update_colored_legend(self, legend, labels, symbols):\n        if self.scatterplot_item is None or not self.palette:\n            return\n        if isinstance(symbols, str):\n            symbols = itertools.repeat(symbols, times=len(labels))\n        for i, (label, symbol) in enumerate(zip(labels, symbols)):\n            color = QColor(*self.palette.getRGB(i))\n            pen = _make_pen(color.darker(self.DarkerValue), 1.5)\n            color.setAlpha(255 if self.subset_is_shown else self.alpha_value)\n            brush = QBrush(color)\n            legend.addItem(\n                ScatterPlotItem(pen=pen, brush=brush, size=10, symbol=symbol),\n                escape(label))\n\n    def zoom_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().RectMode)\n\n    def pan_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().PanMode)\n\n    def select_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().RectMode)\n\n    def reset_button_clicked(self):\n        self.plot_widget.getViewBox().autoRange()\n        self.update_labels()\n\n    def select_by_click(self, _, points):\n        if self.scatterplot_item is not None:\n            self.select(points)\n\n    def select_by_rectangle(self, rect):\n        if self.scatterplot_item is not None:\n            x0, x1 = sorted((rect.topLeft().x(), rect.bottomRight().x()))\n            y0, y1 = sorted((rect.topLeft().y(), rect.bottomRight().y()))\n            x, y = self.master.get_coordinates_data()\n            indices = np.flatnonzero(\n                (x0 <= x) & (x <= x1) & (y0 <= y) & (y <= y1))\n            self.select_by_indices(indices.astype(int))\n\n    def unselect_all(self):\n        if self.selection is not None:\n            self.selection = None\n            self.update_selection_colors()\n            if self.label_only_selected:\n                self.update_labels()\n            self.master.selection_changed()\n\n    def select(self, points):\n        # noinspection PyArgumentList\n        if self.scatterplot_item is None:\n            return\n        indices = [p.data() for p in points]\n        self.select_by_indices(indices)\n\n    def select_by_indices(self, indices):\n        if self.selection is None:\n            self.selection = np.zeros(self.n_valid, dtype=np.uint8)\n        keys = QApplication.keyboardModifiers()\n        if keys & Qt.AltModifier:\n            self.selection_remove(indices)\n        elif keys & Qt.ShiftModifier and keys & Qt.ControlModifier:\n            self.selection_append(indices)\n        elif keys & Qt.ShiftModifier:\n            self.selection_new_group(indices)\n        else:\n            self.selection_select(indices)\n\n    def selection_select(self, indices):\n        self.selection = np.zeros(self.n_valid, dtype=np.uint8)\n        self.selection[indices] = 1\n        self._update_after_selection()\n\n    def selection_append(self, indices):\n        self.selection[indices] = np.max(self.selection)\n        self._update_after_selection()\n\n    def selection_new_group(self, indices):\n        self.selection[indices] = np.max(self.selection) + 1\n        self._update_after_selection()\n\n    def selection_remove(self, indices):\n        self.selection[indices] = 0\n        self._update_after_selection()\n\n    def _update_after_selection(self):\n        self._compress_indices()\n        self.update_selection_colors()\n        if self.label_only_selected:\n            self.update_labels()\n        self.master.selection_changed()\n\n    def _compress_indices(self):\n        indices = sorted(set(self.selection) | {0})\n        if len(indices) == max(indices) + 1:\n            return\n        mapping = np.zeros((max(indices) + 1,), dtype=int)\n        for i, ind in enumerate(indices):\n            mapping[ind] = i\n        self.selection = mapping[self.selection]\n\n    def get_selection(self):\n        if self.selection is None:\n            return np.array([], dtype=np.uint8)\n        else:\n            return np.flatnonzero(self.selection)\n\n    def help_event(self, event):\n        \"\"\"\n        Create a `QToolTip` for the point hovered by the mouse\n        \"\"\"\n        if self.scatterplot_item is None:\n            return False\n        act_pos = self.scatterplot_item.mapFromScene(event.scenePos())\n        point_data = [p.data() for p in self.scatterplot_item.pointsAt(act_pos)]\n        text = self.master.get_tooltip(point_data)\n        if text:\n            QToolTip.showText(event.screenPos(), text, widget=self.plot_widget)\n            return True\n        else:\n            return False\n\n\nclass HelpEventDelegate(EventDelegate):\n    def __init__(self, delegate, parent=None):\n        super().__init__(delegate, parent)\n        warnings.warn(\"HelpEventDelegate class has been deprecated since 3.17.\"\n                      \" Use Orange.widgets.visualize.utils.plotutils.\"\n                      \"HelpEventDelegate instead.\", OrangeDeprecationWarning)\n",
            "header": {
                "file": {
                    "path": "Orange/widgets/visualize/owscatterplotgraph.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "505f792b3",
                "new_commit_hash": "355922765",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/widgets/visualize/owscatterplotgraph.py"
            },
            "plus_file": {
                "path": "b/Orange/widgets/visualize/owscatterplotgraph.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1208,
                            "length": 7
                        },
                        "new_range": {
                            "start": 1208,
                            "length": 15
                        },
                        "section": "class OWScatterPlotBase(gui.OWComponent, QObject):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        cont_color = self.master.is_continuous_color()",
                                "type": "context"
                            },
                            {
                                "content": "        shape_labels = self.master.get_shape_labels()",
                                "type": "context"
                            },
                            {
                                "content": "        color_labels = self.master.get_color_labels()",
                                "type": "context"
                            },
                            {
                                "content": "        if shape_labels == color_labels and shape_labels is not None:",
                                "type": "deleted"
                            },
                            {
                                "content": "        if not cont_color and shape_labels is not None \\",
                                "type": "added"
                            },
                            {
                                "content": "                and shape_labels == color_labels:",
                                "type": "added"
                            },
                            {
                                "content": "            colors = self.master.get_color_data()",
                                "type": "added"
                            },
                            {
                                "content": "            shapes = self.master.get_shape_data()",
                                "type": "added"
                            },
                            {
                                "content": "            mask = np.isfinite(colors) * np.isfinite(shapes)",
                                "type": "added"
                            },
                            {
                                "content": "            combined = (colors == shapes)[mask].all()",
                                "type": "added"
                            },
                            {
                                "content": "        else:",
                                "type": "added"
                            },
                            {
                                "content": "            combined = False",
                                "type": "added"
                            },
                            {
                                "content": "        if combined:",
                                "type": "added"
                            },
                            {
                                "content": "            self._update_combined_legend(shape_labels)",
                                "type": "context"
                            },
                            {
                                "content": "        else:",
                                "type": "context"
                            },
                            {
                                "content": "            self._update_shape_legend(shape_labels)",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/visualize/owscatterplotgraph.py",
                            "type": "method",
                            "name": "OWScatterPlotBase.update_legends",
                            "content": "class OWScatterPlotBase(gui.OWComponent, QObject):\n    \"\"\"\n    Provide a graph component for widgets that show any kind of point plot\n\n    The component plots a set of points with given coordinates, shapes,\n    sizes and colors. Its function is similar to that of a *view*, whereas\n    the widget represents a *model* and a *controler*.\n\n    The model (widget) needs to provide methods:\n\n    - `get_coordinates_data`, `get_size_data`, `get_color_data`,\n      `get_shape_data`, `get_label_data`, which return a 1d array (or two\n      arrays, for `get_coordinates_data`) of `dtype` `float64`, except for\n      `get_label_data`, which returns formatted labels;\n    - `get_shape_labels` returns a list of strings for shape legend\n    - `get_color_labels` returns strings for color legend, or a function for\n       formatting numbers if the legend is continuous, or None for default\n       formatting\n    - `get_tooltip`, which gives a tooltip for a single data point\n    - (optional) `impute_sizes`, `impute_shapes` get final coordinates and\n      shapes, and replace nans;\n    - `get_subset_mask` returns a bool array indicating whether a\n      data point is in the subset or not (e.g. in the 'Data Subset' signal\n      in the Scatter plot and similar widgets);\n    - `get_palette` returns a palette appropriate for visualizing the\n      current color data;\n    - `is_continuous_color` decides the type of the color legend;\n\n    The widget (in a role of controller) must also provide methods\n    - `selection_changed`\n\n    If `get_coordinates_data` returns `(None, None)`, the plot is cleared. If\n    `get_size_data`, `get_color_data` or `get_shape_data` return `None`,\n    all points will have the same size, color or shape, respectively.\n    If `get_label_data` returns `None`, there are no labels.\n\n    The view (this compomnent) provides methods `update_coordinates`,\n    `update_sizes`, `update_colors`, `update_shapes` and `update_labels`\n    that the widget (in a role of a controler) should call when any of\n    these properties are changed. If the widget calls, for instance, the\n    plot's `update_colors`, the plot will react by calling the widget's\n    `get_color_data` as well as the widget's methods needed to construct the\n    legend.\n\n    The view also provides a method `reset_graph`, which should be called only\n    when\n    - the widget gets entirely new data\n    - the number of points may have changed, for instance when selecting\n    a different attribute for x or y in the scatter plot, where the points\n    with missing x or y coordinates are hidden.\n\n    Every `update_something` calls the plot's `get_something`, which\n    calls the model's `get_something_data`, then it transforms this data\n    into whatever is needed (colors, shapes, scaled sizes) and changes the\n    plot. For the simplest example, here is `update_shapes`:\n\n    ```\n        def update_shapes(self):\n            if self.scatterplot_item:\n                shape_data = self.get_shapes()\n                self.scatterplot_item.setSymbol(shape_data)\n            self.update_legends()\n\n        def get_shapes(self):\n            shape_data = self.master.get_shape_data()\n            shape_data = self.master.impute_shapes(\n                shape_data, len(self.CurveSymbols) - 1)\n            return self.CurveSymbols[shape_data]\n    ```\n\n    On the widget's side, `get_something_data` is essentially just:\n\n    ```\n        def get_size_data(self):\n            return self.get_column(self.attr_size)\n    ```\n\n    where `get_column` retrieves a column while also filtering out the\n    points with missing x and y and so forth. (Here we present the simplest\n    two cases, \"shapes\" for the view and \"sizes\" for the model. The colors\n    for the view are more complicated since they deal with discrete and\n    continuous palettes, and the shapes for the view merge infrequent shapes.)\n\n    The plot can also show just a random sample of the data. The sample size is\n    set by `set_sample_size`, and the rest is taken care by the plot: the\n    widget keeps providing the data for all points, selection indices refer\n    to the entire set etc. Internally, sampling happens as early as possible\n    (in methods `get_<something>`).\n    \"\"\"\n    too_many_labels = Signal(bool)\n    begin_resizing = Signal()\n    step_resizing = Signal()\n    end_resizing = Signal()\n\n    label_only_selected = Setting(False)\n    point_width = Setting(10)\n    alpha_value = Setting(128)\n    show_grid = Setting(False)\n    show_legend = Setting(True)\n    class_density = Setting(False)\n    jitter_size = Setting(0)\n\n    resolution = 256\n\n    CurveSymbols = np.array(\"o x t + d star ?\".split())\n    MinShapeSize = 6\n    DarkerValue = 120\n    UnknownColor = (168, 50, 168)\n\n    COLOR_NOT_SUBSET = (128, 128, 128, 0)\n    COLOR_SUBSET = (128, 128, 128, 255)\n    COLOR_DEFAULT = (128, 128, 128, 0)\n\n    MAX_VISIBLE_LABELS = 500\n\n    def __init__(self, scatter_widget, parent=None, view_box=ViewBox):\n        QObject.__init__(self)\n        gui.OWComponent.__init__(self, scatter_widget)\n\n        self.subset_is_shown = False\n\n        self.view_box = view_box(self)\n        self.plot_widget = pg.PlotWidget(viewBox=self.view_box, parent=parent,\n                                         background=\"w\")\n        self.plot_widget.hideAxis(\"left\")\n        self.plot_widget.hideAxis(\"bottom\")\n        self.plot_widget.getPlotItem().buttonsHidden = True\n        self.plot_widget.setAntialiasing(True)\n        self.plot_widget.sizeHint = lambda: QSize(500, 500)\n\n        self.density_img = None\n        self.scatterplot_item = None\n        self.scatterplot_item_sel = None\n        self.labels = []\n\n        self.master = scatter_widget\n        self._create_drag_tooltip(self.plot_widget.scene())\n\n        self.selection = None  # np.ndarray\n\n        self.n_valid = 0\n        self.n_shown = 0\n        self.sample_size = None\n        self.sample_indices = None\n\n        self.palette = None\n\n        self.shape_legend = self._create_legend(((1, 0), (1, 0)))\n        self.color_legend = self._create_legend(((1, 1), (1, 1)))\n        self.update_legend_visibility()\n\n        self.scale = None  # DiscretizedScale\n        self._too_many_labels = False\n\n        # self.setMouseTracking(True)\n        # self.grabGesture(QPinchGesture)\n        # self.grabGesture(QPanGesture)\n\n        self.update_grid_visibility()\n\n        self._tooltip_delegate = EventDelegate(self.help_event)\n        self.plot_widget.scene().installEventFilter(self._tooltip_delegate)\n        self.view_box.sigTransformChanged.connect(self.update_density)\n        self.view_box.sigRangeChangedManually.connect(self.update_labels)\n\n        self.timer = None\n\n    def _create_legend(self, anchor):\n        legend = LegendItem()\n        legend.setParentItem(self.plot_widget.getViewBox())\n        legend.restoreAnchor(anchor)\n        return legend\n\n    def _create_drag_tooltip(self, scene):\n        tip_parts = [\n            (Qt.ShiftModifier, \"Shift: Add group\"),\n            (Qt.ShiftModifier + Qt.ControlModifier,\n             \"Shift-{}: Append to group\".\n             format(\"Cmd\" if sys.platform == \"darwin\" else \"Ctrl\")),\n            (Qt.AltModifier, \"Alt: Remove\")\n        ]\n        all_parts = \", \".join(part for _, part in tip_parts)\n        self.tiptexts = {\n            int(modifier): all_parts.replace(part, \"<b>{}</b>\".format(part))\n            for modifier, part in tip_parts\n        }\n        self.tiptexts[0] = all_parts\n\n        self.tip_textitem = text = QGraphicsTextItem()\n        # Set to the longest text\n        text.setHtml(self.tiptexts[Qt.ShiftModifier + Qt.ControlModifier])\n        text.setPos(4, 2)\n        r = text.boundingRect()\n        rect = QGraphicsRectItem(0, 0, r.width() + 8, r.height() + 4)\n        rect.setBrush(QColor(224, 224, 224, 212))\n        rect.setPen(QPen(Qt.NoPen))\n        self.update_tooltip()\n\n        scene.drag_tooltip = scene.createItemGroup([rect, text])\n        scene.drag_tooltip.hide()\n\n    def update_tooltip(self, modifiers=Qt.NoModifier):\n        modifiers &= Qt.ShiftModifier + Qt.ControlModifier + Qt.AltModifier\n        text = self.tiptexts.get(int(modifiers), self.tiptexts[0])\n        self.tip_textitem.setHtml(text + self._get_jittering_tooltip())\n\n    def _get_jittering_tooltip(self):\n        warn_jittered = \"\"\n        if self.jitter_size:\n            warn_jittered = \\\n                '<br/><br/>' \\\n                '<span style=\"background-color: red; color: white; ' \\\n                'font-weight: 500;\">' \\\n                '&nbsp;Warning: Selection is applied to unjittered data&nbsp;' \\\n                '</span>'\n        return warn_jittered\n\n    def update_jittering(self):\n        self.update_tooltip()\n        x, y = self.get_coordinates()\n        if x is None or not len(x) or self.scatterplot_item is None:\n            return\n        self._update_plot_coordinates(self.scatterplot_item, x, y)\n        self._update_plot_coordinates(self.scatterplot_item_sel, x, y)\n        self.update_labels()\n\n    # TODO: Rename to remove_plot_items\n    def clear(self):\n        \"\"\"\n        Remove all graphical elements from the plot\n\n        Calls the pyqtgraph's plot widget's clear, sets all handles to `None`,\n        removes labels and selections.\n\n        This method should generally not be called by the widget. If the data\n        is gone (*e.g.* upon receiving `None` as an input data signal), this\n        should be handler by calling `reset_graph`, which will in turn call\n        `clear`.\n\n        Derived classes should override this method if they add more graphical\n        elements. For instance, the regression line in the scatterplot adds\n        `self.reg_line_item = None` (the line in the plot is already removed\n        in this method).\n        \"\"\"\n        self.plot_widget.clear()\n\n        self.density_img = None\n        if self.timer is not None and self.timer.isActive():\n            self.timer.stop()\n            self.timer = None\n        self.scatterplot_item = None\n        self.scatterplot_item_sel = None\n        self.labels = []\n        self._signal_too_many_labels(False)\n        self.view_box.init_history()\n        self.view_box.tag_history()\n\n    # TODO: I hate `keep_something` and `reset_something` arguments\n    # __keep_selection is used exclusively be set_sample size which would\n    # otherwise just repeat the code from reset_graph except for resetting\n    # the selection. I'm uncomfortable with this; we may prefer to have a\n    # method _reset_graph which does everything except resetting the selection,\n    # and reset_graph would call it.\n    def reset_graph(self, __keep_selection=False):\n        \"\"\"\n        Reset the graph to new data (or no data)\n\n        The method must be called when the plot receives new data, in\n        particular when the number of points change. If only their properties\n        - like coordinates or shapes - change, an update method\n        (`update_coordinates`, `update_shapes`...) should be called instead.\n\n        The method must also be called when the data is gone.\n\n        The method calls `clear`, followed by calls of all update methods.\n\n        NB. Argument `__keep_selection` is for internal use only\n        \"\"\"\n        self.clear()\n        if not __keep_selection:\n            self.selection = None\n        self.sample_indices = None\n        self.update_coordinates()\n        self.update_point_props()\n\n    def set_sample_size(self, sample_size):\n        \"\"\"\n        Set the sample size\n\n        Args:\n            sample_size (int or None): sample size or `None` to show all points\n        \"\"\"\n        if self.sample_size != sample_size:\n            self.sample_size = sample_size\n            self.reset_graph(True)\n\n    def update_point_props(self):\n        \"\"\"\n        Update the sizes, colors, shapes and labels\n\n        The method calls the appropriate update methods for individual\n        properties.\n        \"\"\"\n        self.update_sizes()\n        self.update_colors()\n        self.update_selection_colors()\n        self.update_shapes()\n        self.update_labels()\n\n    # Coordinates\n    # TODO: It could be nice if this method was run on entire data, not just\n    # a sample. For this, however, it would need to either be called from\n    # `get_coordinates` before sampling (very ugly) or call\n    # `self.master.get_coordinates_data` (beyond ugly) or the widget would\n    # have to store the ranges of unsampled data (ugly).\n    # Maybe we leave it as it is.\n    def _reset_view(self, x_data, y_data):\n        \"\"\"\n        Set the range of the view box\n\n        Args:\n            x_data (np.ndarray): x coordinates\n            y_data (np.ndarray) y coordinates\n        \"\"\"\n        min_x, max_x = np.min(x_data), np.max(x_data)\n        min_y, max_y = np.min(y_data), np.max(y_data)\n        self.view_box.setRange(\n            QRectF(min_x, min_y, max_x - min_x or 1, max_y - min_y or 1),\n            padding=0.025)\n\n    def _filter_visible(self, data):\n        \"\"\"Return the sample from the data using the stored sample_indices\"\"\"\n        if data is None or self.sample_indices is None:\n            return data\n        else:\n            return np.asarray(data[self.sample_indices])\n\n    def get_coordinates(self):\n        \"\"\"\n        Prepare coordinates of the points in the plot\n\n        The method is called by `update_coordinates`. It gets the coordinates\n        from the widget, jitters them and return them.\n\n        The methods also initializes the sample indices if neededd and stores\n        the original and sampled number of points.\n\n        Returns:\n            (tuple): a pair of numpy arrays containing (sampled) coordinates,\n                or `(None, None)`.\n        \"\"\"\n        x, y = self.master.get_coordinates_data()\n        if x is None:\n            self.n_valid = self.n_shown = 0\n            return None, None\n        self.n_valid = len(x)\n        self._create_sample()\n        x = self._filter_visible(x)\n        y = self._filter_visible(y)\n        # Jittering after sampling is OK if widgets do not change the sample\n        # semi-permanently, e.g. take a sample for the duration of some\n        # animation. If the sample size changes dynamically (like by adding\n        # a \"sample size\" slider), points would move around when the sample\n        # size changes. To prevent this, jittering should be done before\n        # sampling (i.e. two lines earlier). This would slow it down somewhat.\n        x, y = self.jitter_coordinates(x, y)\n        return x, y\n\n    def _create_sample(self):\n        \"\"\"\n        Create a random sample if the data is larger than the set sample size\n        \"\"\"\n        self.n_shown = min(self.n_valid, self.sample_size or self.n_valid)\n        if self.sample_size is not None \\\n                and self.sample_indices is None \\\n                and self.n_valid != self.n_shown:\n            random = np.random.RandomState(seed=0)\n            self.sample_indices = random.choice(\n                self.n_valid, self.n_shown, replace=False)\n            # TODO: Is this really needed?\n            np.sort(self.sample_indices)\n\n    def jitter_coordinates(self, x, y):\n        \"\"\"\n        Display coordinates to random positions within ellipses with\n        radiuses of `self.jittter_size` percents of spans\n        \"\"\"\n        if self.jitter_size == 0:\n            return x, y\n        return self._jitter_data(x, y)\n\n    def _jitter_data(self, x, y, span_x=None, span_y=None):\n        if span_x is None:\n            span_x = np.max(x) - np.min(x)\n        if span_y is None:\n            span_y = np.max(y) - np.min(y)\n        random = np.random.RandomState(seed=0)\n        rs = random.uniform(0, 1, len(x))\n        phis = random.uniform(0, 2 * np.pi, len(x))\n        magnitude = self.jitter_size / 100\n        return (x + magnitude * span_x * rs * np.cos(phis),\n                y + magnitude * span_y * rs * np.sin(phis))\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n\n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n            data[prop] = plot.data[prop]\n        plot.setData(**data)\n\n    def update_coordinates(self):\n        \"\"\"\n        Trigger the update of coordinates while keeping other features intact.\n\n        The method gets the coordinates by calling `self.get_coordinates`,\n        which in turn calls the widget's `get_coordinate_data`. The number of\n        coordinate pairs returned by the latter must match the current number\n        of points. If this is not the case, the widget should trigger\n        the complete update by calling `reset_graph` instead of this method.\n        \"\"\"\n        x, y = self.get_coordinates()\n        if x is None or not len(x):\n            return\n        if self.scatterplot_item is None:\n            if self.sample_indices is None:\n                indices = np.arange(self.n_valid)\n            else:\n                indices = self.sample_indices\n            kwargs = dict(x=x, y=y, data=indices)\n            self.scatterplot_item = ScatterPlotItem(**kwargs)\n            self.scatterplot_item.sigClicked.connect(self.select_by_click)\n            self.scatterplot_item_sel = ScatterPlotItem(**kwargs)\n            self.plot_widget.addItem(self.scatterplot_item_sel)\n            self.plot_widget.addItem(self.scatterplot_item)\n        else:\n            self._update_plot_coordinates(self.scatterplot_item, x, y)\n            self._update_plot_coordinates(self.scatterplot_item_sel, x, y)\n            self.update_labels()\n\n        self.update_density()  # Todo: doesn't work: try MDS with density on\n        self._reset_view(x, y)\n\n    # Sizes\n    def get_sizes(self):\n        \"\"\"\n        Prepare data for sizes of points in the plot\n\n        The method is called by `update_sizes`. It gets the sizes\n        from the widget and performs the necessary scaling and sizing.\n        The output is rounded to half a pixel for faster drawing.\n\n        Returns:\n            (np.ndarray): sizes\n        \"\"\"\n        size_column = self.master.get_size_data()\n        if size_column is None:\n            return np.full((self.n_shown,),\n                           self.MinShapeSize + (5 + self.point_width) * 0.5)\n        size_column = self._filter_visible(size_column)\n        size_column = size_column.copy()\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n            size_column -= np.nanmin(size_column)\n            mx = np.nanmax(size_column)\n        if mx > 0:\n            size_column /= mx\n        else:\n            size_column[:] = 0.5\n\n        sizes = self.MinShapeSize + (5 + self.point_width) * size_column\n        # round sizes to half pixel for smaller pyqtgraph's symbol pixmap atlas\n        sizes = (sizes * 2).round() / 2\n        return sizes\n\n    def update_sizes(self):\n        \"\"\"\n        Trigger an update of point sizes\n\n        The method calls `self.get_sizes`, which in turn calls the widget's\n        `get_size_data`. The result are properly scaled and then passed\n        back to widget for imputing (`master.impute_sizes`).\n        \"\"\"\n        if self.scatterplot_item:\n            size_data = self.get_sizes()\n            size_imputer = getattr(\n                self.master, \"impute_sizes\", self.default_impute_sizes)\n            size_imputer(size_data)\n\n            if self.timer is not None and self.timer.isActive():\n                self.timer.stop()\n                self.timer = None\n\n            current_size_data = self.scatterplot_item.data[\"size\"].copy()\n            diff = size_data - current_size_data\n            widget = self\n\n            class Timeout:\n                # 0.5 - np.cos(np.arange(0.17, 1, 0.17) * np.pi) / 2\n                factors = [0.07, 0.26, 0.52, 0.77, 0.95, 1]\n\n                def __init__(self):\n                    self._counter = 0\n\n                def __call__(self):\n                    factor = self.factors[self._counter]\n                    self._counter += 1\n                    size = current_size_data + diff * factor\n                    if len(self.factors) == self._counter:\n                        widget.timer.stop()\n                        widget.timer = None\n                        size = size_data\n                    widget.scatterplot_item.setSize(size)\n                    widget.scatterplot_item_sel.setSize(size + SELECTION_WIDTH)\n                    if widget.timer is None:\n                        widget.end_resizing.emit()\n                    else:\n                        widget.step_resizing.emit()\n\n            if self.n_valid <= MAX_N_VALID_SIZE_ANIMATE and \\\n                    np.all(current_size_data > 0) and np.any(diff != 0):\n                # If encountered any strange behaviour when updating sizes,\n                # implement it with threads\n                self.begin_resizing.emit()\n                self.timer = QTimer(self.scatterplot_item, interval=50)\n                self.timer.timeout.connect(Timeout())\n                self.timer.start()\n            else:\n                self.begin_resizing.emit()\n                self.scatterplot_item.setSize(size_data)\n                self.scatterplot_item_sel.setSize(size_data + SELECTION_WIDTH)\n                self.end_resizing.emit()\n\n    update_point_size = update_sizes  # backward compatibility (needed?!)\n    update_size = update_sizes\n\n    @classmethod\n    def default_impute_sizes(cls, size_data):\n        \"\"\"\n        Fallback imputation for sizes.\n\n        Set the size to two pixels smaller than the minimal size\n\n        Returns:\n            (bool): True if there was any missing data\n        \"\"\"\n        nans = np.isnan(size_data)\n        if np.any(nans):\n            size_data[nans] = cls.MinShapeSize - 2\n            return True\n        else:\n            return False\n\n    # Colors\n    def get_colors(self):\n        \"\"\"\n        Prepare data for colors of the points in the plot\n\n        The method is called by `update_colors`. It gets the colors and the\n        indices of the data subset from the widget (`get_color_data`,\n        `get_subset_mask`), and constructs lists of pens and brushes for\n        each data point.\n\n        The method uses different palettes for discrete and continuous data,\n        as determined by calling the widget's method `is_continuous_color`.\n\n        If also marks the points that are in the subset as defined by, for\n        instance the 'Data Subset' signal in the Scatter plot and similar\n        widgets. (Do not confuse this with *selected points*, which are\n        marked by circles around the points, which are colored by groups\n        and thus independent of this method.)\n\n        Returns:\n            (tuple): a list of pens and list of brushes\n        \"\"\"\n        self.palette = self.master.get_palette()\n        c_data = self.master.get_color_data()\n        c_data = self._filter_visible(c_data)\n        subset = self.master.get_subset_mask()\n        subset = self._filter_visible(subset)\n        self.subset_is_shown = subset is not None\n        if c_data is None:  # same color\n            return self._get_same_colors(subset)\n        elif self.master.is_continuous_color():\n            return self._get_continuous_colors(c_data, subset)\n        else:\n            return self._get_discrete_colors(c_data, subset)\n\n    def _get_same_colors(self, subset):\n        \"\"\"\n        Return the same pen for all points while the brush color depends\n        upon whether the point is in the subset or not\n\n        Args:\n            subset (np.ndarray): a bool array indicating whether a data point\n                is in the subset or not (e.g. in the 'Data Subset' signal\n                in the Scatter plot and similar widgets);\n\n        Returns:\n            (tuple): a list of pens and list of brushes\n        \"\"\"\n        color = self.plot_widget.palette().color(OWPalette.Data)\n        pen = [_make_pen(color, 1.5)] * self.n_shown  # use a single QPen instance\n        if subset is not None:\n            brush = np.where(\n                subset,\n                *(QBrush(QColor(*col))\n                  for col in (self.COLOR_SUBSET, self.COLOR_NOT_SUBSET)))\n        else:\n            color = QColor(*self.COLOR_DEFAULT)\n            color.setAlpha(self.alpha_value)\n            brush = [QBrush(color)] * self.n_shown  # use a single QBrush instance\n        return pen, brush\n\n    def _get_continuous_colors(self, c_data, subset):\n        \"\"\"\n        Return the pens and colors whose color represent an index into\n        a continuous palette. The same color is used for pen and brush,\n        except the former is darker. If the data has a subset, the brush\n        is transparent for points that are not in the subset.\n        \"\"\"\n        if np.isnan(c_data).all():\n            self.scale = None\n        else:\n            self.scale = DiscretizedScale(np.nanmin(c_data), np.nanmax(c_data))\n            c_data -= self.scale.offset\n            c_data /= self.scale.width\n            c_data = np.floor(c_data) + 0.5\n            c_data /= self.scale.bins\n            c_data = np.clip(c_data, 0, 1)\n        pen = self.palette.getRGB(c_data)\n        brush = np.hstack(\n            [pen, np.full((len(pen), 1), self.alpha_value, dtype=int)])\n        pen *= 100\n        pen //= self.DarkerValue\n\n        # Reuse pens and brushes with the same colors because PyQtGraph then builds\n        # smaller pixmap atlas, which makes the drawing faster\n\n        def reuse(cache, fn, *args):\n            if args not in cache:\n                cache[args] = fn(args)\n            return cache[args]\n\n        def create_pen(col):\n            return _make_pen(QColor(*col), 1.5)\n\n        def create_brush(col):\n            return QBrush(QColor(*col))\n\n        cached_pens = {}\n        pen = [reuse(cached_pens, create_pen, *col) for col in pen.tolist()]\n\n        if subset is not None:\n            brush[:, 3] = 0\n            brush[subset, 3] = 255\n\n        cached_brushes = {}\n        brush = np.array([reuse(cached_brushes, create_brush, *col) for col in brush.tolist()])\n\n        return pen, brush\n\n    def _get_discrete_colors(self, c_data, subset):\n        \"\"\"\n        Return the pens and colors whose color represent an index into\n        a discrete palette. The same color is used for pen and brush,\n        except the former is darker. If the data has a subset, the brush\n        is transparent for points that are not in the subset.\n        \"\"\"\n        n_colors = self.palette.number_of_colors\n        c_data = c_data.copy()\n        c_data[np.isnan(c_data)] = n_colors\n        c_data = c_data.astype(int)\n        colors = np.r_[self.palette.getRGB(np.arange(n_colors)),\n                       [[128, 128, 128]]]\n        pens = np.array(\n            [_make_pen(QColor(*col).darker(self.DarkerValue), 1.5)\n             for col in colors])\n        pen = pens[c_data]\n        alpha = self.alpha_value if subset is None else 255\n        brushes = np.array([\n            [QBrush(QColor(0, 0, 0, 0)),\n             QBrush(QColor(col[0], col[1], col[2], alpha))]\n            for col in colors])\n        brush = brushes[c_data]\n\n        if subset is not None:\n            brush = np.where(subset, brush[:, 1], brush[:, 0])\n        else:\n            brush = brush[:, 1]\n        return pen, brush\n\n    def update_colors(self):\n        \"\"\"\n        Trigger an update of point sizes\n\n        The method calls `self.get_colors`, which in turn calls the widget's\n        `get_color_data` to get the indices in the pallette. `get_colors`\n        returns a list of pens and brushes to which this method uses to\n        update the colors. Finally, the method triggers the update of the\n        legend and the density plot.\n        \"\"\"\n        if self.scatterplot_item is not None:\n            pen_data, brush_data = self.get_colors()\n            self.scatterplot_item.setPen(pen_data, update=False, mask=None)\n            self.scatterplot_item.setBrush(brush_data, mask=None)\n        self.update_legends()\n        self.update_density()\n\n    update_alpha_value = update_colors\n\n    def update_density(self):\n        \"\"\"\n        Remove the existing density plot (if there is one) and replace it\n        with a new one (if enabled).\n\n        The method gets the colors from the pens of the currently plotted\n        points.\n        \"\"\"\n        if self.density_img:\n            self.plot_widget.removeItem(self.density_img)\n            self.density_img = None\n        if self.class_density and self.scatterplot_item is not None:\n            rgb_data = [\n                pen.color().getRgb()[:3] if pen is not None else (255, 255, 255)\n                for pen in self.scatterplot_item.data['pen']]\n            if len(set(rgb_data)) <= 1:\n                return\n            [min_x, max_x], [min_y, max_y] = self.view_box.viewRange()\n            x_data, y_data = self.scatterplot_item.getData()\n            self.density_img = classdensity.class_density_image(\n                min_x, max_x, min_y, max_y, self.resolution,\n                x_data, y_data, rgb_data)\n            self.plot_widget.addItem(self.density_img)\n\n    def update_selection_colors(self):\n        \"\"\"\n        Trigger an update of selection markers\n\n        This update method is usually not called by the widget but by the\n        plot, since it is the plot that handles the selections.\n\n        Like other update methods, it calls the corresponding get method\n        (`get_colors_sel`) which returns a list of pens and brushes.\n        \"\"\"\n        if self.scatterplot_item_sel is None:\n            return\n        pen, brush = self.get_colors_sel()\n        self.scatterplot_item_sel.setPen(pen, update=False, mask=None)\n        self.scatterplot_item_sel.setBrush(brush, mask=None)\n\n    def get_colors_sel(self):\n        \"\"\"\n        Return pens and brushes for selection markers.\n\n        A pen can is set to `Qt.NoPen` if a point is not selected.\n\n        All brushes are completely transparent whites.\n\n        Returns:\n            (tuple): a list of pens and a list of brushes\n        \"\"\"\n        nopen = QPen(Qt.NoPen)\n        if self.selection is None:\n            pen = [nopen] * self.n_shown\n        else:\n            sels = np.max(self.selection)\n            if sels == 1:\n                pen = np.where(\n                    self._filter_visible(self.selection),\n                    _make_pen(QColor(255, 190, 0, 255), SELECTION_WIDTH + 1),\n                    nopen)\n            else:\n                palette = ColorPaletteGenerator(number_of_colors=sels + 1)\n                pen = np.choose(\n                    self._filter_visible(self.selection),\n                    [nopen] + [_make_pen(palette[i], SELECTION_WIDTH + 1)\n                               for i in range(sels)])\n        return pen, [QBrush(QColor(255, 255, 255, 0))] * self.n_shown\n\n    # Labels\n    def get_labels(self):\n        \"\"\"\n        Prepare data for labels for points\n\n        The method returns the results of the widget's `get_label_data`\n\n        Returns:\n            (labels): a sequence of labels\n        \"\"\"\n        return self._filter_visible(self.master.get_label_data())\n\n    def update_labels(self):\n        \"\"\"\n        Trigger an update of labels\n\n        The method calls `get_labels` which in turn calls the widget's\n        `get_label_data`. The obtained labels are shown if the corresponding\n        points are selected or if `label_only_selected` is `false`.\n        \"\"\"\n        for label in self.labels:\n            self.plot_widget.removeItem(label)\n        self.labels = []\n\n        mask = None\n        if self.scatterplot_item is not None:\n            x, y = self.scatterplot_item.getData()\n            mask = self._label_mask(x, y)\n\n        if mask is not None:\n            labels = self.get_labels()\n            if labels is None:\n                mask = None\n\n        self._signal_too_many_labels(\n            mask is not None and mask.sum() > self.MAX_VISIBLE_LABELS)\n        if self._too_many_labels or mask is None or not np.any(mask):\n            return\n\n        black = pg.mkColor(0, 0, 0)\n        labels = labels[mask]\n        x = x[mask]\n        y = y[mask]\n        for label, xp, yp in zip(labels, x, y):\n            ti = TextItem(label, black)\n            ti.setPos(xp, yp)\n            self.plot_widget.addItem(ti)\n            self.labels.append(ti)\n\n    def _signal_too_many_labels(self, too_many):\n        if self._too_many_labels != too_many:\n            self._too_many_labels = too_many\n            self.too_many_labels.emit(too_many)\n\n    def _label_mask(self, x, y):\n        (x0, x1), (y0, y1) = self.view_box.viewRange()\n        mask = np.logical_and(\n            np.logical_and(x >= x0, x <= x1),\n            np.logical_and(y >= y0, y <= y1))\n        if self.label_only_selected:\n            sub_mask = self._filter_visible(self.master.get_subset_mask())\n            if self.selection is None:\n                if sub_mask is None:\n                    return None\n                else:\n                    sel_mask = sub_mask\n            else:\n                sel_mask = self._filter_visible(self.selection) != 0\n                if sub_mask is not None:\n                    sel_mask = np.logical_or(sel_mask, sub_mask)\n            mask = np.logical_and(mask, sel_mask)\n        return mask\n\n    # Shapes\n    def get_shapes(self):\n        \"\"\"\n        Prepare data for shapes of points in the plot\n\n        The method is called by `update_shapes`. It gets the data from\n        the widget's `get_shape_data`, and then calls its `impute_shapes`\n        to impute the missing shape (usually with some default shape).\n\n        Returns:\n            (np.ndarray): an array of symbols (e.g. o, x, + ...)\n        \"\"\"\n        shape_data = self.master.get_shape_data()\n        shape_data = self._filter_visible(shape_data)\n        # Data has to be copied so the imputation can change it in-place\n        # TODO: Try avoiding this when we move imputation to the widget\n        if shape_data is not None:\n            shape_data = np.copy(shape_data)\n        shape_imputer = getattr(\n            self.master, \"impute_shapes\", self.default_impute_shapes)\n        shape_imputer(shape_data, len(self.CurveSymbols) - 1)\n        if isinstance(shape_data, np.ndarray):\n            shape_data = shape_data.astype(int)\n        else:\n            shape_data = np.zeros(self.n_shown, dtype=int)\n        return self.CurveSymbols[shape_data]\n\n    @staticmethod\n    def default_impute_shapes(shape_data, default_symbol):\n        \"\"\"\n        Fallback imputation for shapes.\n\n        Use the default symbol, usually the last symbol in the list.\n\n        Returns:\n            (bool): True if there was any missing data\n        \"\"\"\n        if shape_data is None:\n            return False\n        nans = np.isnan(shape_data)\n        if np.any(nans):\n            shape_data[nans] = default_symbol\n            return True\n        else:\n            return False\n\n    def update_shapes(self):\n        \"\"\"\n        Trigger an update of point symbols\n\n        The method calls `get_shapes` to obtain an array with a symbol\n        for each point and uses it to update the symbols.\n\n        Finally, the method updates the legend.\n        \"\"\"\n        if self.scatterplot_item:\n            shape_data = self.get_shapes()\n            self.scatterplot_item.setSymbol(shape_data)\n        self.update_legends()\n\n    def update_grid_visibility(self):\n        \"\"\"Show or hide the grid\"\"\"\n        self.plot_widget.showGrid(x=self.show_grid, y=self.show_grid)\n\n    def update_legend_visibility(self):\n        \"\"\"\n        Show or hide legends based on whether they are enabled and non-empty\n        \"\"\"\n        self.shape_legend.setVisible(\n            self.show_legend and bool(self.shape_legend.items))\n        self.color_legend.setVisible(\n            self.show_legend and bool(self.color_legend.items))\n\n    def update_legends(self):\n        \"\"\"Update content of legends and their visibility\"\"\"\n        cont_color = self.master.is_continuous_color()\n        shape_labels = self.master.get_shape_labels()\n        color_labels = self.master.get_color_labels()\n        if shape_labels == color_labels and shape_labels is not None:\n            self._update_combined_legend(shape_labels)\n        else:\n            self._update_shape_legend(shape_labels)\n            if cont_color:\n                self._update_continuous_color_legend(color_labels)\n            else:\n                self._update_color_legend(color_labels)\n        self.update_legend_visibility()\n\n    def _update_shape_legend(self, labels):\n        self.shape_legend.clear()\n        if labels is None or self.scatterplot_item is None:\n            return\n        color = QColor(0, 0, 0)\n        color.setAlpha(self.alpha_value)\n        for label, symbol in zip(labels, self.CurveSymbols):\n            self.shape_legend.addItem(\n                ScatterPlotItem(pen=color, brush=color, size=10, symbol=symbol),\n                escape(label))\n\n    def _update_continuous_color_legend(self, label_formatter):\n        self.color_legend.clear()\n        if self.scale is None or self.scatterplot_item is None:\n            return\n        label = PaletteItemSample(self.palette, self.scale, label_formatter)\n        self.color_legend.addItem(label, \"\")\n        self.color_legend.setGeometry(label.boundingRect())\n\n    def _update_color_legend(self, labels):\n        self.color_legend.clear()\n        if labels is None:\n            return\n        self._update_colored_legend(self.color_legend, labels, 'o')\n\n    def _update_combined_legend(self, labels):\n        # update_colored_legend will already clear the shape legend\n        # so we remove colors here\n        use_legend = \\\n            self.shape_legend if self.shape_legend.items else self.color_legend\n        self.color_legend.clear()\n        self.shape_legend.clear()\n        self._update_colored_legend(use_legend, labels, self.CurveSymbols)\n\n    def _update_colored_legend(self, legend, labels, symbols):\n        if self.scatterplot_item is None or not self.palette:\n            return\n        if isinstance(symbols, str):\n            symbols = itertools.repeat(symbols, times=len(labels))\n        for i, (label, symbol) in enumerate(zip(labels, symbols)):\n            color = QColor(*self.palette.getRGB(i))\n            pen = _make_pen(color.darker(self.DarkerValue), 1.5)\n            color.setAlpha(255 if self.subset_is_shown else self.alpha_value)\n            brush = QBrush(color)\n            legend.addItem(\n                ScatterPlotItem(pen=pen, brush=brush, size=10, symbol=symbol),\n                escape(label))\n\n    def zoom_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().RectMode)\n\n    def pan_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().PanMode)\n\n    def select_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().RectMode)\n\n    def reset_button_clicked(self):\n        self.plot_widget.getViewBox().autoRange()\n        self.update_labels()\n\n    def select_by_click(self, _, points):\n        if self.scatterplot_item is not None:\n            self.select(points)\n\n    def select_by_rectangle(self, rect):\n        if self.scatterplot_item is not None:\n            x0, x1 = sorted((rect.topLeft().x(), rect.bottomRight().x()))\n            y0, y1 = sorted((rect.topLeft().y(), rect.bottomRight().y()))\n            x, y = self.master.get_coordinates_data()\n            indices = np.flatnonzero(\n                (x0 <= x) & (x <= x1) & (y0 <= y) & (y <= y1))\n            self.select_by_indices(indices.astype(int))\n\n    def unselect_all(self):\n        if self.selection is not None:\n            self.selection = None\n            self.update_selection_colors()\n            if self.label_only_selected:\n                self.update_labels()\n            self.master.selection_changed()\n\n    def select(self, points):\n        # noinspection PyArgumentList\n        if self.scatterplot_item is None:\n            return\n        indices = [p.data() for p in points]\n        self.select_by_indices(indices)\n\n    def select_by_indices(self, indices):\n        if self.selection is None:\n            self.selection = np.zeros(self.n_valid, dtype=np.uint8)\n        keys = QApplication.keyboardModifiers()\n        if keys & Qt.AltModifier:\n            self.selection_remove(indices)\n        elif keys & Qt.ShiftModifier and keys & Qt.ControlModifier:\n            self.selection_append(indices)\n        elif keys & Qt.ShiftModifier:\n            self.selection_new_group(indices)\n        else:\n            self.selection_select(indices)\n\n    def selection_select(self, indices):\n        self.selection = np.zeros(self.n_valid, dtype=np.uint8)\n        self.selection[indices] = 1\n        self._update_after_selection()\n\n    def selection_append(self, indices):\n        self.selection[indices] = np.max(self.selection)\n        self._update_after_selection()\n\n    def selection_new_group(self, indices):\n        self.selection[indices] = np.max(self.selection) + 1\n        self._update_after_selection()\n\n    def selection_remove(self, indices):\n        self.selection[indices] = 0\n        self._update_after_selection()\n\n    def _update_after_selection(self):\n        self._compress_indices()\n        self.update_selection_colors()\n        if self.label_only_selected:\n            self.update_labels()\n        self.master.selection_changed()\n\n    def _compress_indices(self):\n        indices = sorted(set(self.selection) | {0})\n        if len(indices) == max(indices) + 1:\n            return\n        mapping = np.zeros((max(indices) + 1,), dtype=int)\n        for i, ind in enumerate(indices):\n            mapping[ind] = i\n        self.selection = mapping[self.selection]\n\n    def get_selection(self):\n        if self.selection is None:\n            return np.array([], dtype=np.uint8)\n        else:\n            return np.flatnonzero(self.selection)\n\n    def help_event(self, event):\n        \"\"\"\n        Create a `QToolTip` for the point hovered by the mouse\n        \"\"\"\n        if self.scatterplot_item is None:\n            return False\n        act_pos = self.scatterplot_item.mapFromScene(event.scenePos())\n        point_data = [p.data() for p in self.scatterplot_item.pointsAt(act_pos)]\n        text = self.master.get_tooltip(point_data)\n        if text:\n            QToolTip.showText(event.screenPos(), text, widget=self.plot_widget)\n            return True\n        else:\n            return False",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1206,
                            "end_lineno": 1219,
                            "parent": {
                                "file_name": "Orange/widgets/visualize/owscatterplotgraph.py",
                                "type": "class",
                                "name": "OWScatterPlotBase",
                                "content": "class OWScatterPlotBase(gui.OWComponent, QObject):\n    \"\"\"\n    Provide a graph component for widgets that show any kind of point plot\n\n    The component plots a set of points with given coordinates, shapes,\n    sizes and colors. Its function is similar to that of a *view*, whereas\n    the widget represents a *model* and a *controler*.\n\n    The model (widget) needs to provide methods:\n\n    - `get_coordinates_data`, `get_size_data`, `get_color_data`,\n      `get_shape_data`, `get_label_data`, which return a 1d array (or two\n      arrays, for `get_coordinates_data`) of `dtype` `float64`, except for\n      `get_label_data`, which returns formatted labels;\n    - `get_shape_labels` returns a list of strings for shape legend\n    - `get_color_labels` returns strings for color legend, or a function for\n       formatting numbers if the legend is continuous, or None for default\n       formatting\n    - `get_tooltip`, which gives a tooltip for a single data point\n    - (optional) `impute_sizes`, `impute_shapes` get final coordinates and\n      shapes, and replace nans;\n    - `get_subset_mask` returns a bool array indicating whether a\n      data point is in the subset or not (e.g. in the 'Data Subset' signal\n      in the Scatter plot and similar widgets);\n    - `get_palette` returns a palette appropriate for visualizing the\n      current color data;\n    - `is_continuous_color` decides the type of the color legend;\n\n    The widget (in a role of controller) must also provide methods\n    - `selection_changed`\n\n    If `get_coordinates_data` returns `(None, None)`, the plot is cleared. If\n    `get_size_data`, `get_color_data` or `get_shape_data` return `None`,\n    all points will have the same size, color or shape, respectively.\n    If `get_label_data` returns `None`, there are no labels.\n\n    The view (this compomnent) provides methods `update_coordinates`,\n    `update_sizes`, `update_colors`, `update_shapes` and `update_labels`\n    that the widget (in a role of a controler) should call when any of\n    these properties are changed. If the widget calls, for instance, the\n    plot's `update_colors`, the plot will react by calling the widget's\n    `get_color_data` as well as the widget's methods needed to construct the\n    legend.\n\n    The view also provides a method `reset_graph`, which should be called only\n    when\n    - the widget gets entirely new data\n    - the number of points may have changed, for instance when selecting\n    a different attribute for x or y in the scatter plot, where the points\n    with missing x or y coordinates are hidden.\n\n    Every `update_something` calls the plot's `get_something`, which\n    calls the model's `get_something_data`, then it transforms this data\n    into whatever is needed (colors, shapes, scaled sizes) and changes the\n    plot. For the simplest example, here is `update_shapes`:\n\n    ```\n        def update_shapes(self):\n            if self.scatterplot_item:\n                shape_data = self.get_shapes()\n                self.scatterplot_item.setSymbol(shape_data)\n            self.update_legends()\n\n        def get_shapes(self):\n            shape_data = self.master.get_shape_data()\n            shape_data = self.master.impute_shapes(\n                shape_data, len(self.CurveSymbols) - 1)\n            return self.CurveSymbols[shape_data]\n    ```\n\n    On the widget's side, `get_something_data` is essentially just:\n\n    ```\n        def get_size_data(self):\n            return self.get_column(self.attr_size)\n    ```\n\n    where `get_column` retrieves a column while also filtering out the\n    points with missing x and y and so forth. (Here we present the simplest\n    two cases, \"shapes\" for the view and \"sizes\" for the model. The colors\n    for the view are more complicated since they deal with discrete and\n    continuous palettes, and the shapes for the view merge infrequent shapes.)\n\n    The plot can also show just a random sample of the data. The sample size is\n    set by `set_sample_size`, and the rest is taken care by the plot: the\n    widget keeps providing the data for all points, selection indices refer\n    to the entire set etc. Internally, sampling happens as early as possible\n    (in methods `get_<something>`).\n    \"\"\"\n    too_many_labels = Signal(bool)\n    begin_resizing = Signal()\n    step_resizing = Signal()\n    end_resizing = Signal()\n\n    label_only_selected = Setting(False)\n    point_width = Setting(10)\n    alpha_value = Setting(128)\n    show_grid = Setting(False)\n    show_legend = Setting(True)\n    class_density = Setting(False)\n    jitter_size = Setting(0)\n\n    resolution = 256\n\n    CurveSymbols = np.array(\"o x t + d star ?\".split())\n    MinShapeSize = 6\n    DarkerValue = 120\n    UnknownColor = (168, 50, 168)\n\n    COLOR_NOT_SUBSET = (128, 128, 128, 0)\n    COLOR_SUBSET = (128, 128, 128, 255)\n    COLOR_DEFAULT = (128, 128, 128, 0)\n\n    MAX_VISIBLE_LABELS = 500\n\n    def __init__(self, scatter_widget, parent=None, view_box=ViewBox):\n        QObject.__init__(self)\n        gui.OWComponent.__init__(self, scatter_widget)\n\n        self.subset_is_shown = False\n\n        self.view_box = view_box(self)\n        self.plot_widget = pg.PlotWidget(viewBox=self.view_box, parent=parent,\n                                         background=\"w\")\n        self.plot_widget.hideAxis(\"left\")\n        self.plot_widget.hideAxis(\"bottom\")\n        self.plot_widget.getPlotItem().buttonsHidden = True\n        self.plot_widget.setAntialiasing(True)\n        self.plot_widget.sizeHint = lambda: QSize(500, 500)\n\n        self.density_img = None\n        self.scatterplot_item = None\n        self.scatterplot_item_sel = None\n        self.labels = []\n\n        self.master = scatter_widget\n        self._create_drag_tooltip(self.plot_widget.scene())\n\n        self.selection = None  # np.ndarray\n\n        self.n_valid = 0\n        self.n_shown = 0\n        self.sample_size = None\n        self.sample_indices = None\n\n        self.palette = None\n\n        self.shape_legend = self._create_legend(((1, 0), (1, 0)))\n        self.color_legend = self._create_legend(((1, 1), (1, 1)))\n        self.update_legend_visibility()\n\n        self.scale = None  # DiscretizedScale\n        self._too_many_labels = False\n\n        # self.setMouseTracking(True)\n        # self.grabGesture(QPinchGesture)\n        # self.grabGesture(QPanGesture)\n\n        self.update_grid_visibility()\n\n        self._tooltip_delegate = EventDelegate(self.help_event)\n        self.plot_widget.scene().installEventFilter(self._tooltip_delegate)\n        self.view_box.sigTransformChanged.connect(self.update_density)\n        self.view_box.sigRangeChangedManually.connect(self.update_labels)\n\n        self.timer = None\n\n    def _create_legend(self, anchor):\n        legend = LegendItem()\n        legend.setParentItem(self.plot_widget.getViewBox())\n        legend.restoreAnchor(anchor)\n        return legend\n\n    def _create_drag_tooltip(self, scene):\n        tip_parts = [\n            (Qt.ShiftModifier, \"Shift: Add group\"),\n            (Qt.ShiftModifier + Qt.ControlModifier,\n             \"Shift-{}: Append to group\".\n             format(\"Cmd\" if sys.platform == \"darwin\" else \"Ctrl\")),\n            (Qt.AltModifier, \"Alt: Remove\")\n        ]\n        all_parts = \", \".join(part for _, part in tip_parts)\n        self.tiptexts = {\n            int(modifier): all_parts.replace(part, \"<b>{}</b>\".format(part))\n            for modifier, part in tip_parts\n        }\n        self.tiptexts[0] = all_parts\n\n        self.tip_textitem = text = QGraphicsTextItem()\n        # Set to the longest text\n        text.setHtml(self.tiptexts[Qt.ShiftModifier + Qt.ControlModifier])\n        text.setPos(4, 2)\n        r = text.boundingRect()\n        rect = QGraphicsRectItem(0, 0, r.width() + 8, r.height() + 4)\n        rect.setBrush(QColor(224, 224, 224, 212))\n        rect.setPen(QPen(Qt.NoPen))\n        self.update_tooltip()\n\n        scene.drag_tooltip = scene.createItemGroup([rect, text])\n        scene.drag_tooltip.hide()\n\n    def update_tooltip(self, modifiers=Qt.NoModifier):\n        modifiers &= Qt.ShiftModifier + Qt.ControlModifier + Qt.AltModifier\n        text = self.tiptexts.get(int(modifiers), self.tiptexts[0])\n        self.tip_textitem.setHtml(text + self._get_jittering_tooltip())\n\n    def _get_jittering_tooltip(self):\n        warn_jittered = \"\"\n        if self.jitter_size:\n            warn_jittered = \\\n                '<br/><br/>' \\\n                '<span style=\"background-color: red; color: white; ' \\\n                'font-weight: 500;\">' \\\n                '&nbsp;Warning: Selection is applied to unjittered data&nbsp;' \\\n                '</span>'\n        return warn_jittered\n\n    def update_jittering(self):\n        self.update_tooltip()\n        x, y = self.get_coordinates()\n        if x is None or not len(x) or self.scatterplot_item is None:\n            return\n        self._update_plot_coordinates(self.scatterplot_item, x, y)\n        self._update_plot_coordinates(self.scatterplot_item_sel, x, y)\n        self.update_labels()\n\n    # TODO: Rename to remove_plot_items\n    def clear(self):\n        \"\"\"\n        Remove all graphical elements from the plot\n\n        Calls the pyqtgraph's plot widget's clear, sets all handles to `None`,\n        removes labels and selections.\n\n        This method should generally not be called by the widget. If the data\n        is gone (*e.g.* upon receiving `None` as an input data signal), this\n        should be handler by calling `reset_graph`, which will in turn call\n        `clear`.\n\n        Derived classes should override this method if they add more graphical\n        elements. For instance, the regression line in the scatterplot adds\n        `self.reg_line_item = None` (the line in the plot is already removed\n        in this method).\n        \"\"\"\n        self.plot_widget.clear()\n\n        self.density_img = None\n        if self.timer is not None and self.timer.isActive():\n            self.timer.stop()\n            self.timer = None\n        self.scatterplot_item = None\n        self.scatterplot_item_sel = None\n        self.labels = []\n        self._signal_too_many_labels(False)\n        self.view_box.init_history()\n        self.view_box.tag_history()\n\n    # TODO: I hate `keep_something` and `reset_something` arguments\n    # __keep_selection is used exclusively be set_sample size which would\n    # otherwise just repeat the code from reset_graph except for resetting\n    # the selection. I'm uncomfortable with this; we may prefer to have a\n    # method _reset_graph which does everything except resetting the selection,\n    # and reset_graph would call it.\n    def reset_graph(self, __keep_selection=False):\n        \"\"\"\n        Reset the graph to new data (or no data)\n\n        The method must be called when the plot receives new data, in\n        particular when the number of points change. If only their properties\n        - like coordinates or shapes - change, an update method\n        (`update_coordinates`, `update_shapes`...) should be called instead.\n\n        The method must also be called when the data is gone.\n\n        The method calls `clear`, followed by calls of all update methods.\n\n        NB. Argument `__keep_selection` is for internal use only\n        \"\"\"\n        self.clear()\n        if not __keep_selection:\n            self.selection = None\n        self.sample_indices = None\n        self.update_coordinates()\n        self.update_point_props()\n\n    def set_sample_size(self, sample_size):\n        \"\"\"\n        Set the sample size\n\n        Args:\n            sample_size (int or None): sample size or `None` to show all points\n        \"\"\"\n        if self.sample_size != sample_size:\n            self.sample_size = sample_size\n            self.reset_graph(True)\n\n    def update_point_props(self):\n        \"\"\"\n        Update the sizes, colors, shapes and labels\n\n        The method calls the appropriate update methods for individual\n        properties.\n        \"\"\"\n        self.update_sizes()\n        self.update_colors()\n        self.update_selection_colors()\n        self.update_shapes()\n        self.update_labels()\n\n    # Coordinates\n    # TODO: It could be nice if this method was run on entire data, not just\n    # a sample. For this, however, it would need to either be called from\n    # `get_coordinates` before sampling (very ugly) or call\n    # `self.master.get_coordinates_data` (beyond ugly) or the widget would\n    # have to store the ranges of unsampled data (ugly).\n    # Maybe we leave it as it is.\n    def _reset_view(self, x_data, y_data):\n        \"\"\"\n        Set the range of the view box\n\n        Args:\n            x_data (np.ndarray): x coordinates\n            y_data (np.ndarray) y coordinates\n        \"\"\"\n        min_x, max_x = np.min(x_data), np.max(x_data)\n        min_y, max_y = np.min(y_data), np.max(y_data)\n        self.view_box.setRange(\n            QRectF(min_x, min_y, max_x - min_x or 1, max_y - min_y or 1),\n            padding=0.025)\n\n    def _filter_visible(self, data):\n        \"\"\"Return the sample from the data using the stored sample_indices\"\"\"\n        if data is None or self.sample_indices is None:\n            return data\n        else:\n            return np.asarray(data[self.sample_indices])\n\n    def get_coordinates(self):\n        \"\"\"\n        Prepare coordinates of the points in the plot\n\n        The method is called by `update_coordinates`. It gets the coordinates\n        from the widget, jitters them and return them.\n\n        The methods also initializes the sample indices if neededd and stores\n        the original and sampled number of points.\n\n        Returns:\n            (tuple): a pair of numpy arrays containing (sampled) coordinates,\n                or `(None, None)`.\n        \"\"\"\n        x, y = self.master.get_coordinates_data()\n        if x is None:\n            self.n_valid = self.n_shown = 0\n            return None, None\n        self.n_valid = len(x)\n        self._create_sample()\n        x = self._filter_visible(x)\n        y = self._filter_visible(y)\n        # Jittering after sampling is OK if widgets do not change the sample\n        # semi-permanently, e.g. take a sample for the duration of some\n        # animation. If the sample size changes dynamically (like by adding\n        # a \"sample size\" slider), points would move around when the sample\n        # size changes. To prevent this, jittering should be done before\n        # sampling (i.e. two lines earlier). This would slow it down somewhat.\n        x, y = self.jitter_coordinates(x, y)\n        return x, y\n\n    def _create_sample(self):\n        \"\"\"\n        Create a random sample if the data is larger than the set sample size\n        \"\"\"\n        self.n_shown = min(self.n_valid, self.sample_size or self.n_valid)\n        if self.sample_size is not None \\\n                and self.sample_indices is None \\\n                and self.n_valid != self.n_shown:\n            random = np.random.RandomState(seed=0)\n            self.sample_indices = random.choice(\n                self.n_valid, self.n_shown, replace=False)\n            # TODO: Is this really needed?\n            np.sort(self.sample_indices)\n\n    def jitter_coordinates(self, x, y):\n        \"\"\"\n        Display coordinates to random positions within ellipses with\n        radiuses of `self.jittter_size` percents of spans\n        \"\"\"\n        if self.jitter_size == 0:\n            return x, y\n        return self._jitter_data(x, y)\n\n    def _jitter_data(self, x, y, span_x=None, span_y=None):\n        if span_x is None:\n            span_x = np.max(x) - np.min(x)\n        if span_y is None:\n            span_y = np.max(y) - np.min(y)\n        random = np.random.RandomState(seed=0)\n        rs = random.uniform(0, 1, len(x))\n        phis = random.uniform(0, 2 * np.pi, len(x))\n        magnitude = self.jitter_size / 100\n        return (x + magnitude * span_x * rs * np.cos(phis),\n                y + magnitude * span_y * rs * np.sin(phis))\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n\n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n            data[prop] = plot.data[prop]\n        plot.setData(**data)\n\n    def update_coordinates(self):\n        \"\"\"\n        Trigger the update of coordinates while keeping other features intact.\n\n        The method gets the coordinates by calling `self.get_coordinates`,\n        which in turn calls the widget's `get_coordinate_data`. The number of\n        coordinate pairs returned by the latter must match the current number\n        of points. If this is not the case, the widget should trigger\n        the complete update by calling `reset_graph` instead of this method.\n        \"\"\"\n        x, y = self.get_coordinates()\n        if x is None or not len(x):\n            return\n        if self.scatterplot_item is None:\n            if self.sample_indices is None:\n                indices = np.arange(self.n_valid)\n            else:\n                indices = self.sample_indices\n            kwargs = dict(x=x, y=y, data=indices)\n            self.scatterplot_item = ScatterPlotItem(**kwargs)\n            self.scatterplot_item.sigClicked.connect(self.select_by_click)\n            self.scatterplot_item_sel = ScatterPlotItem(**kwargs)\n            self.plot_widget.addItem(self.scatterplot_item_sel)\n            self.plot_widget.addItem(self.scatterplot_item)\n        else:\n            self._update_plot_coordinates(self.scatterplot_item, x, y)\n            self._update_plot_coordinates(self.scatterplot_item_sel, x, y)\n            self.update_labels()\n\n        self.update_density()  # Todo: doesn't work: try MDS with density on\n        self._reset_view(x, y)\n\n    # Sizes\n    def get_sizes(self):\n        \"\"\"\n        Prepare data for sizes of points in the plot\n\n        The method is called by `update_sizes`. It gets the sizes\n        from the widget and performs the necessary scaling and sizing.\n        The output is rounded to half a pixel for faster drawing.\n\n        Returns:\n            (np.ndarray): sizes\n        \"\"\"\n        size_column = self.master.get_size_data()\n        if size_column is None:\n            return np.full((self.n_shown,),\n                           self.MinShapeSize + (5 + self.point_width) * 0.5)\n        size_column = self._filter_visible(size_column)\n        size_column = size_column.copy()\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n            size_column -= np.nanmin(size_column)\n            mx = np.nanmax(size_column)\n        if mx > 0:\n            size_column /= mx\n        else:\n            size_column[:] = 0.5\n\n        sizes = self.MinShapeSize + (5 + self.point_width) * size_column\n        # round sizes to half pixel for smaller pyqtgraph's symbol pixmap atlas\n        sizes = (sizes * 2).round() / 2\n        return sizes\n\n    def update_sizes(self):\n        \"\"\"\n        Trigger an update of point sizes\n\n        The method calls `self.get_sizes`, which in turn calls the widget's\n        `get_size_data`. The result are properly scaled and then passed\n        back to widget for imputing (`master.impute_sizes`).\n        \"\"\"\n        if self.scatterplot_item:\n            size_data = self.get_sizes()\n            size_imputer = getattr(\n                self.master, \"impute_sizes\", self.default_impute_sizes)\n            size_imputer(size_data)\n\n            if self.timer is not None and self.timer.isActive():\n                self.timer.stop()\n                self.timer = None\n\n            current_size_data = self.scatterplot_item.data[\"size\"].copy()\n            diff = size_data - current_size_data\n            widget = self\n\n            class Timeout:\n                # 0.5 - np.cos(np.arange(0.17, 1, 0.17) * np.pi) / 2\n                factors = [0.07, 0.26, 0.52, 0.77, 0.95, 1]\n\n                def __init__(self):\n                    self._counter = 0\n\n                def __call__(self):\n                    factor = self.factors[self._counter]\n                    self._counter += 1\n                    size = current_size_data + diff * factor\n                    if len(self.factors) == self._counter:\n                        widget.timer.stop()\n                        widget.timer = None\n                        size = size_data\n                    widget.scatterplot_item.setSize(size)\n                    widget.scatterplot_item_sel.setSize(size + SELECTION_WIDTH)\n                    if widget.timer is None:\n                        widget.end_resizing.emit()\n                    else:\n                        widget.step_resizing.emit()\n\n            if self.n_valid <= MAX_N_VALID_SIZE_ANIMATE and \\\n                    np.all(current_size_data > 0) and np.any(diff != 0):\n                # If encountered any strange behaviour when updating sizes,\n                # implement it with threads\n                self.begin_resizing.emit()\n                self.timer = QTimer(self.scatterplot_item, interval=50)\n                self.timer.timeout.connect(Timeout())\n                self.timer.start()\n            else:\n                self.begin_resizing.emit()\n                self.scatterplot_item.setSize(size_data)\n                self.scatterplot_item_sel.setSize(size_data + SELECTION_WIDTH)\n                self.end_resizing.emit()\n\n    update_point_size = update_sizes  # backward compatibility (needed?!)\n    update_size = update_sizes\n\n    @classmethod\n    def default_impute_sizes(cls, size_data):\n        \"\"\"\n        Fallback imputation for sizes.\n\n        Set the size to two pixels smaller than the minimal size\n\n        Returns:\n            (bool): True if there was any missing data\n        \"\"\"\n        nans = np.isnan(size_data)\n        if np.any(nans):\n            size_data[nans] = cls.MinShapeSize - 2\n            return True\n        else:\n            return False\n\n    # Colors\n    def get_colors(self):\n        \"\"\"\n        Prepare data for colors of the points in the plot\n\n        The method is called by `update_colors`. It gets the colors and the\n        indices of the data subset from the widget (`get_color_data`,\n        `get_subset_mask`), and constructs lists of pens and brushes for\n        each data point.\n\n        The method uses different palettes for discrete and continuous data,\n        as determined by calling the widget's method `is_continuous_color`.\n\n        If also marks the points that are in the subset as defined by, for\n        instance the 'Data Subset' signal in the Scatter plot and similar\n        widgets. (Do not confuse this with *selected points*, which are\n        marked by circles around the points, which are colored by groups\n        and thus independent of this method.)\n\n        Returns:\n            (tuple): a list of pens and list of brushes\n        \"\"\"\n        self.palette = self.master.get_palette()\n        c_data = self.master.get_color_data()\n        c_data = self._filter_visible(c_data)\n        subset = self.master.get_subset_mask()\n        subset = self._filter_visible(subset)\n        self.subset_is_shown = subset is not None\n        if c_data is None:  # same color\n            return self._get_same_colors(subset)\n        elif self.master.is_continuous_color():\n            return self._get_continuous_colors(c_data, subset)\n        else:\n            return self._get_discrete_colors(c_data, subset)\n\n    def _get_same_colors(self, subset):\n        \"\"\"\n        Return the same pen for all points while the brush color depends\n        upon whether the point is in the subset or not\n\n        Args:\n            subset (np.ndarray): a bool array indicating whether a data point\n                is in the subset or not (e.g. in the 'Data Subset' signal\n                in the Scatter plot and similar widgets);\n\n        Returns:\n            (tuple): a list of pens and list of brushes\n        \"\"\"\n        color = self.plot_widget.palette().color(OWPalette.Data)\n        pen = [_make_pen(color, 1.5)] * self.n_shown  # use a single QPen instance\n        if subset is not None:\n            brush = np.where(\n                subset,\n                *(QBrush(QColor(*col))\n                  for col in (self.COLOR_SUBSET, self.COLOR_NOT_SUBSET)))\n        else:\n            color = QColor(*self.COLOR_DEFAULT)\n            color.setAlpha(self.alpha_value)\n            brush = [QBrush(color)] * self.n_shown  # use a single QBrush instance\n        return pen, brush\n\n    def _get_continuous_colors(self, c_data, subset):\n        \"\"\"\n        Return the pens and colors whose color represent an index into\n        a continuous palette. The same color is used for pen and brush,\n        except the former is darker. If the data has a subset, the brush\n        is transparent for points that are not in the subset.\n        \"\"\"\n        if np.isnan(c_data).all():\n            self.scale = None\n        else:\n            self.scale = DiscretizedScale(np.nanmin(c_data), np.nanmax(c_data))\n            c_data -= self.scale.offset\n            c_data /= self.scale.width\n            c_data = np.floor(c_data) + 0.5\n            c_data /= self.scale.bins\n            c_data = np.clip(c_data, 0, 1)\n        pen = self.palette.getRGB(c_data)\n        brush = np.hstack(\n            [pen, np.full((len(pen), 1), self.alpha_value, dtype=int)])\n        pen *= 100\n        pen //= self.DarkerValue\n\n        # Reuse pens and brushes with the same colors because PyQtGraph then builds\n        # smaller pixmap atlas, which makes the drawing faster\n\n        def reuse(cache, fn, *args):\n            if args not in cache:\n                cache[args] = fn(args)\n            return cache[args]\n\n        def create_pen(col):\n            return _make_pen(QColor(*col), 1.5)\n\n        def create_brush(col):\n            return QBrush(QColor(*col))\n\n        cached_pens = {}\n        pen = [reuse(cached_pens, create_pen, *col) for col in pen.tolist()]\n\n        if subset is not None:\n            brush[:, 3] = 0\n            brush[subset, 3] = 255\n\n        cached_brushes = {}\n        brush = np.array([reuse(cached_brushes, create_brush, *col) for col in brush.tolist()])\n\n        return pen, brush\n\n    def _get_discrete_colors(self, c_data, subset):\n        \"\"\"\n        Return the pens and colors whose color represent an index into\n        a discrete palette. The same color is used for pen and brush,\n        except the former is darker. If the data has a subset, the brush\n        is transparent for points that are not in the subset.\n        \"\"\"\n        n_colors = self.palette.number_of_colors\n        c_data = c_data.copy()\n        c_data[np.isnan(c_data)] = n_colors\n        c_data = c_data.astype(int)\n        colors = np.r_[self.palette.getRGB(np.arange(n_colors)),\n                       [[128, 128, 128]]]\n        pens = np.array(\n            [_make_pen(QColor(*col).darker(self.DarkerValue), 1.5)\n             for col in colors])\n        pen = pens[c_data]\n        alpha = self.alpha_value if subset is None else 255\n        brushes = np.array([\n            [QBrush(QColor(0, 0, 0, 0)),\n             QBrush(QColor(col[0], col[1], col[2], alpha))]\n            for col in colors])\n        brush = brushes[c_data]\n\n        if subset is not None:\n            brush = np.where(subset, brush[:, 1], brush[:, 0])\n        else:\n            brush = brush[:, 1]\n        return pen, brush\n\n    def update_colors(self):\n        \"\"\"\n        Trigger an update of point sizes\n\n        The method calls `self.get_colors`, which in turn calls the widget's\n        `get_color_data` to get the indices in the pallette. `get_colors`\n        returns a list of pens and brushes to which this method uses to\n        update the colors. Finally, the method triggers the update of the\n        legend and the density plot.\n        \"\"\"\n        if self.scatterplot_item is not None:\n            pen_data, brush_data = self.get_colors()\n            self.scatterplot_item.setPen(pen_data, update=False, mask=None)\n            self.scatterplot_item.setBrush(brush_data, mask=None)\n        self.update_legends()\n        self.update_density()\n\n    update_alpha_value = update_colors\n\n    def update_density(self):\n        \"\"\"\n        Remove the existing density plot (if there is one) and replace it\n        with a new one (if enabled).\n\n        The method gets the colors from the pens of the currently plotted\n        points.\n        \"\"\"\n        if self.density_img:\n            self.plot_widget.removeItem(self.density_img)\n            self.density_img = None\n        if self.class_density and self.scatterplot_item is not None:\n            rgb_data = [\n                pen.color().getRgb()[:3] if pen is not None else (255, 255, 255)\n                for pen in self.scatterplot_item.data['pen']]\n            if len(set(rgb_data)) <= 1:\n                return\n            [min_x, max_x], [min_y, max_y] = self.view_box.viewRange()\n            x_data, y_data = self.scatterplot_item.getData()\n            self.density_img = classdensity.class_density_image(\n                min_x, max_x, min_y, max_y, self.resolution,\n                x_data, y_data, rgb_data)\n            self.plot_widget.addItem(self.density_img)\n\n    def update_selection_colors(self):\n        \"\"\"\n        Trigger an update of selection markers\n\n        This update method is usually not called by the widget but by the\n        plot, since it is the plot that handles the selections.\n\n        Like other update methods, it calls the corresponding get method\n        (`get_colors_sel`) which returns a list of pens and brushes.\n        \"\"\"\n        if self.scatterplot_item_sel is None:\n            return\n        pen, brush = self.get_colors_sel()\n        self.scatterplot_item_sel.setPen(pen, update=False, mask=None)\n        self.scatterplot_item_sel.setBrush(brush, mask=None)\n\n    def get_colors_sel(self):\n        \"\"\"\n        Return pens and brushes for selection markers.\n\n        A pen can is set to `Qt.NoPen` if a point is not selected.\n\n        All brushes are completely transparent whites.\n\n        Returns:\n            (tuple): a list of pens and a list of brushes\n        \"\"\"\n        nopen = QPen(Qt.NoPen)\n        if self.selection is None:\n            pen = [nopen] * self.n_shown\n        else:\n            sels = np.max(self.selection)\n            if sels == 1:\n                pen = np.where(\n                    self._filter_visible(self.selection),\n                    _make_pen(QColor(255, 190, 0, 255), SELECTION_WIDTH + 1),\n                    nopen)\n            else:\n                palette = ColorPaletteGenerator(number_of_colors=sels + 1)\n                pen = np.choose(\n                    self._filter_visible(self.selection),\n                    [nopen] + [_make_pen(palette[i], SELECTION_WIDTH + 1)\n                               for i in range(sels)])\n        return pen, [QBrush(QColor(255, 255, 255, 0))] * self.n_shown\n\n    # Labels\n    def get_labels(self):\n        \"\"\"\n        Prepare data for labels for points\n\n        The method returns the results of the widget's `get_label_data`\n\n        Returns:\n            (labels): a sequence of labels\n        \"\"\"\n        return self._filter_visible(self.master.get_label_data())\n\n    def update_labels(self):\n        \"\"\"\n        Trigger an update of labels\n\n        The method calls `get_labels` which in turn calls the widget's\n        `get_label_data`. The obtained labels are shown if the corresponding\n        points are selected or if `label_only_selected` is `false`.\n        \"\"\"\n        for label in self.labels:\n            self.plot_widget.removeItem(label)\n        self.labels = []\n\n        mask = None\n        if self.scatterplot_item is not None:\n            x, y = self.scatterplot_item.getData()\n            mask = self._label_mask(x, y)\n\n        if mask is not None:\n            labels = self.get_labels()\n            if labels is None:\n                mask = None\n\n        self._signal_too_many_labels(\n            mask is not None and mask.sum() > self.MAX_VISIBLE_LABELS)\n        if self._too_many_labels or mask is None or not np.any(mask):\n            return\n\n        black = pg.mkColor(0, 0, 0)\n        labels = labels[mask]\n        x = x[mask]\n        y = y[mask]\n        for label, xp, yp in zip(labels, x, y):\n            ti = TextItem(label, black)\n            ti.setPos(xp, yp)\n            self.plot_widget.addItem(ti)\n            self.labels.append(ti)\n\n    def _signal_too_many_labels(self, too_many):\n        if self._too_many_labels != too_many:\n            self._too_many_labels = too_many\n            self.too_many_labels.emit(too_many)\n\n    def _label_mask(self, x, y):\n        (x0, x1), (y0, y1) = self.view_box.viewRange()\n        mask = np.logical_and(\n            np.logical_and(x >= x0, x <= x1),\n            np.logical_and(y >= y0, y <= y1))\n        if self.label_only_selected:\n            sub_mask = self._filter_visible(self.master.get_subset_mask())\n            if self.selection is None:\n                if sub_mask is None:\n                    return None\n                else:\n                    sel_mask = sub_mask\n            else:\n                sel_mask = self._filter_visible(self.selection) != 0\n                if sub_mask is not None:\n                    sel_mask = np.logical_or(sel_mask, sub_mask)\n            mask = np.logical_and(mask, sel_mask)\n        return mask\n\n    # Shapes\n    def get_shapes(self):\n        \"\"\"\n        Prepare data for shapes of points in the plot\n\n        The method is called by `update_shapes`. It gets the data from\n        the widget's `get_shape_data`, and then calls its `impute_shapes`\n        to impute the missing shape (usually with some default shape).\n\n        Returns:\n            (np.ndarray): an array of symbols (e.g. o, x, + ...)\n        \"\"\"\n        shape_data = self.master.get_shape_data()\n        shape_data = self._filter_visible(shape_data)\n        # Data has to be copied so the imputation can change it in-place\n        # TODO: Try avoiding this when we move imputation to the widget\n        if shape_data is not None:\n            shape_data = np.copy(shape_data)\n        shape_imputer = getattr(\n            self.master, \"impute_shapes\", self.default_impute_shapes)\n        shape_imputer(shape_data, len(self.CurveSymbols) - 1)\n        if isinstance(shape_data, np.ndarray):\n            shape_data = shape_data.astype(int)\n        else:\n            shape_data = np.zeros(self.n_shown, dtype=int)\n        return self.CurveSymbols[shape_data]\n\n    @staticmethod\n    def default_impute_shapes(shape_data, default_symbol):\n        \"\"\"\n        Fallback imputation for shapes.\n\n        Use the default symbol, usually the last symbol in the list.\n\n        Returns:\n            (bool): True if there was any missing data\n        \"\"\"\n        if shape_data is None:\n            return False\n        nans = np.isnan(shape_data)\n        if np.any(nans):\n            shape_data[nans] = default_symbol\n            return True\n        else:\n            return False\n\n    def update_shapes(self):\n        \"\"\"\n        Trigger an update of point symbols\n\n        The method calls `get_shapes` to obtain an array with a symbol\n        for each point and uses it to update the symbols.\n\n        Finally, the method updates the legend.\n        \"\"\"\n        if self.scatterplot_item:\n            shape_data = self.get_shapes()\n            self.scatterplot_item.setSymbol(shape_data)\n        self.update_legends()\n\n    def update_grid_visibility(self):\n        \"\"\"Show or hide the grid\"\"\"\n        self.plot_widget.showGrid(x=self.show_grid, y=self.show_grid)\n\n    def update_legend_visibility(self):\n        \"\"\"\n        Show or hide legends based on whether they are enabled and non-empty\n        \"\"\"\n        self.shape_legend.setVisible(\n            self.show_legend and bool(self.shape_legend.items))\n        self.color_legend.setVisible(\n            self.show_legend and bool(self.color_legend.items))\n\n    def update_legends(self):\n        \"\"\"Update content of legends and their visibility\"\"\"\n        cont_color = self.master.is_continuous_color()\n        shape_labels = self.master.get_shape_labels()\n        color_labels = self.master.get_color_labels()\n        if shape_labels == color_labels and shape_labels is not None:\n            self._update_combined_legend(shape_labels)\n        else:\n            self._update_shape_legend(shape_labels)\n            if cont_color:\n                self._update_continuous_color_legend(color_labels)\n            else:\n                self._update_color_legend(color_labels)\n        self.update_legend_visibility()\n\n    def _update_shape_legend(self, labels):\n        self.shape_legend.clear()\n        if labels is None or self.scatterplot_item is None:\n            return\n        color = QColor(0, 0, 0)\n        color.setAlpha(self.alpha_value)\n        for label, symbol in zip(labels, self.CurveSymbols):\n            self.shape_legend.addItem(\n                ScatterPlotItem(pen=color, brush=color, size=10, symbol=symbol),\n                escape(label))\n\n    def _update_continuous_color_legend(self, label_formatter):\n        self.color_legend.clear()\n        if self.scale is None or self.scatterplot_item is None:\n            return\n        label = PaletteItemSample(self.palette, self.scale, label_formatter)\n        self.color_legend.addItem(label, \"\")\n        self.color_legend.setGeometry(label.boundingRect())\n\n    def _update_color_legend(self, labels):\n        self.color_legend.clear()\n        if labels is None:\n            return\n        self._update_colored_legend(self.color_legend, labels, 'o')\n\n    def _update_combined_legend(self, labels):\n        # update_colored_legend will already clear the shape legend\n        # so we remove colors here\n        use_legend = \\\n            self.shape_legend if self.shape_legend.items else self.color_legend\n        self.color_legend.clear()\n        self.shape_legend.clear()\n        self._update_colored_legend(use_legend, labels, self.CurveSymbols)\n\n    def _update_colored_legend(self, legend, labels, symbols):\n        if self.scatterplot_item is None or not self.palette:\n            return\n        if isinstance(symbols, str):\n            symbols = itertools.repeat(symbols, times=len(labels))\n        for i, (label, symbol) in enumerate(zip(labels, symbols)):\n            color = QColor(*self.palette.getRGB(i))\n            pen = _make_pen(color.darker(self.DarkerValue), 1.5)\n            color.setAlpha(255 if self.subset_is_shown else self.alpha_value)\n            brush = QBrush(color)\n            legend.addItem(\n                ScatterPlotItem(pen=pen, brush=brush, size=10, symbol=symbol),\n                escape(label))\n\n    def zoom_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().RectMode)\n\n    def pan_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().PanMode)\n\n    def select_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().RectMode)\n\n    def reset_button_clicked(self):\n        self.plot_widget.getViewBox().autoRange()\n        self.update_labels()\n\n    def select_by_click(self, _, points):\n        if self.scatterplot_item is not None:\n            self.select(points)\n\n    def select_by_rectangle(self, rect):\n        if self.scatterplot_item is not None:\n            x0, x1 = sorted((rect.topLeft().x(), rect.bottomRight().x()))\n            y0, y1 = sorted((rect.topLeft().y(), rect.bottomRight().y()))\n            x, y = self.master.get_coordinates_data()\n            indices = np.flatnonzero(\n                (x0 <= x) & (x <= x1) & (y0 <= y) & (y <= y1))\n            self.select_by_indices(indices.astype(int))\n\n    def unselect_all(self):\n        if self.selection is not None:\n            self.selection = None\n            self.update_selection_colors()\n            if self.label_only_selected:\n                self.update_labels()\n            self.master.selection_changed()\n\n    def select(self, points):\n        # noinspection PyArgumentList\n        if self.scatterplot_item is None:\n            return\n        indices = [p.data() for p in points]\n        self.select_by_indices(indices)\n\n    def select_by_indices(self, indices):\n        if self.selection is None:\n            self.selection = np.zeros(self.n_valid, dtype=np.uint8)\n        keys = QApplication.keyboardModifiers()\n        if keys & Qt.AltModifier:\n            self.selection_remove(indices)\n        elif keys & Qt.ShiftModifier and keys & Qt.ControlModifier:\n            self.selection_append(indices)\n        elif keys & Qt.ShiftModifier:\n            self.selection_new_group(indices)\n        else:\n            self.selection_select(indices)\n\n    def selection_select(self, indices):\n        self.selection = np.zeros(self.n_valid, dtype=np.uint8)\n        self.selection[indices] = 1\n        self._update_after_selection()\n\n    def selection_append(self, indices):\n        self.selection[indices] = np.max(self.selection)\n        self._update_after_selection()\n\n    def selection_new_group(self, indices):\n        self.selection[indices] = np.max(self.selection) + 1\n        self._update_after_selection()\n\n    def selection_remove(self, indices):\n        self.selection[indices] = 0\n        self._update_after_selection()\n\n    def _update_after_selection(self):\n        self._compress_indices()\n        self.update_selection_colors()\n        if self.label_only_selected:\n            self.update_labels()\n        self.master.selection_changed()\n\n    def _compress_indices(self):\n        indices = sorted(set(self.selection) | {0})\n        if len(indices) == max(indices) + 1:\n            return\n        mapping = np.zeros((max(indices) + 1,), dtype=int)\n        for i, ind in enumerate(indices):\n            mapping[ind] = i\n        self.selection = mapping[self.selection]\n\n    def get_selection(self):\n        if self.selection is None:\n            return np.array([], dtype=np.uint8)\n        else:\n            return np.flatnonzero(self.selection)\n\n    def help_event(self, event):\n        \"\"\"\n        Create a `QToolTip` for the point hovered by the mouse\n        \"\"\"\n        if self.scatterplot_item is None:\n            return False\n        act_pos = self.scatterplot_item.mapFromScene(event.scenePos())\n        point_data = [p.data() for p in self.scatterplot_item.pointsAt(act_pos)]\n        text = self.master.get_tooltip(point_data)\n        if text:\n            QToolTip.showText(event.screenPos(), text, widget=self.plot_widget)\n            return True\n        else:\n            return False",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 270,
                                "end_lineno": 1378,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/widgets/visualize/owscatterplotgraph.py",
                            "type": "class",
                            "name": "OWScatterPlotBase",
                            "content": "class OWScatterPlotBase(gui.OWComponent, QObject):\n    \"\"\"\n    Provide a graph component for widgets that show any kind of point plot\n\n    The component plots a set of points with given coordinates, shapes,\n    sizes and colors. Its function is similar to that of a *view*, whereas\n    the widget represents a *model* and a *controler*.\n\n    The model (widget) needs to provide methods:\n\n    - `get_coordinates_data`, `get_size_data`, `get_color_data`,\n      `get_shape_data`, `get_label_data`, which return a 1d array (or two\n      arrays, for `get_coordinates_data`) of `dtype` `float64`, except for\n      `get_label_data`, which returns formatted labels;\n    - `get_shape_labels` returns a list of strings for shape legend\n    - `get_color_labels` returns strings for color legend, or a function for\n       formatting numbers if the legend is continuous, or None for default\n       formatting\n    - `get_tooltip`, which gives a tooltip for a single data point\n    - (optional) `impute_sizes`, `impute_shapes` get final coordinates and\n      shapes, and replace nans;\n    - `get_subset_mask` returns a bool array indicating whether a\n      data point is in the subset or not (e.g. in the 'Data Subset' signal\n      in the Scatter plot and similar widgets);\n    - `get_palette` returns a palette appropriate for visualizing the\n      current color data;\n    - `is_continuous_color` decides the type of the color legend;\n\n    The widget (in a role of controller) must also provide methods\n    - `selection_changed`\n\n    If `get_coordinates_data` returns `(None, None)`, the plot is cleared. If\n    `get_size_data`, `get_color_data` or `get_shape_data` return `None`,\n    all points will have the same size, color or shape, respectively.\n    If `get_label_data` returns `None`, there are no labels.\n\n    The view (this compomnent) provides methods `update_coordinates`,\n    `update_sizes`, `update_colors`, `update_shapes` and `update_labels`\n    that the widget (in a role of a controler) should call when any of\n    these properties are changed. If the widget calls, for instance, the\n    plot's `update_colors`, the plot will react by calling the widget's\n    `get_color_data` as well as the widget's methods needed to construct the\n    legend.\n\n    The view also provides a method `reset_graph`, which should be called only\n    when\n    - the widget gets entirely new data\n    - the number of points may have changed, for instance when selecting\n    a different attribute for x or y in the scatter plot, where the points\n    with missing x or y coordinates are hidden.\n\n    Every `update_something` calls the plot's `get_something`, which\n    calls the model's `get_something_data`, then it transforms this data\n    into whatever is needed (colors, shapes, scaled sizes) and changes the\n    plot. For the simplest example, here is `update_shapes`:\n\n    ```\n        def update_shapes(self):\n            if self.scatterplot_item:\n                shape_data = self.get_shapes()\n                self.scatterplot_item.setSymbol(shape_data)\n            self.update_legends()\n\n        def get_shapes(self):\n            shape_data = self.master.get_shape_data()\n            shape_data = self.master.impute_shapes(\n                shape_data, len(self.CurveSymbols) - 1)\n            return self.CurveSymbols[shape_data]\n    ```\n\n    On the widget's side, `get_something_data` is essentially just:\n\n    ```\n        def get_size_data(self):\n            return self.get_column(self.attr_size)\n    ```\n\n    where `get_column` retrieves a column while also filtering out the\n    points with missing x and y and so forth. (Here we present the simplest\n    two cases, \"shapes\" for the view and \"sizes\" for the model. The colors\n    for the view are more complicated since they deal with discrete and\n    continuous palettes, and the shapes for the view merge infrequent shapes.)\n\n    The plot can also show just a random sample of the data. The sample size is\n    set by `set_sample_size`, and the rest is taken care by the plot: the\n    widget keeps providing the data for all points, selection indices refer\n    to the entire set etc. Internally, sampling happens as early as possible\n    (in methods `get_<something>`).\n    \"\"\"\n    too_many_labels = Signal(bool)\n    begin_resizing = Signal()\n    step_resizing = Signal()\n    end_resizing = Signal()\n\n    label_only_selected = Setting(False)\n    point_width = Setting(10)\n    alpha_value = Setting(128)\n    show_grid = Setting(False)\n    show_legend = Setting(True)\n    class_density = Setting(False)\n    jitter_size = Setting(0)\n\n    resolution = 256\n\n    CurveSymbols = np.array(\"o x t + d star ?\".split())\n    MinShapeSize = 6\n    DarkerValue = 120\n    UnknownColor = (168, 50, 168)\n\n    COLOR_NOT_SUBSET = (128, 128, 128, 0)\n    COLOR_SUBSET = (128, 128, 128, 255)\n    COLOR_DEFAULT = (128, 128, 128, 0)\n\n    MAX_VISIBLE_LABELS = 500\n\n    def __init__(self, scatter_widget, parent=None, view_box=ViewBox):\n        QObject.__init__(self)\n        gui.OWComponent.__init__(self, scatter_widget)\n\n        self.subset_is_shown = False\n\n        self.view_box = view_box(self)\n        self.plot_widget = pg.PlotWidget(viewBox=self.view_box, parent=parent,\n                                         background=\"w\")\n        self.plot_widget.hideAxis(\"left\")\n        self.plot_widget.hideAxis(\"bottom\")\n        self.plot_widget.getPlotItem().buttonsHidden = True\n        self.plot_widget.setAntialiasing(True)\n        self.plot_widget.sizeHint = lambda: QSize(500, 500)\n\n        self.density_img = None\n        self.scatterplot_item = None\n        self.scatterplot_item_sel = None\n        self.labels = []\n\n        self.master = scatter_widget\n        self._create_drag_tooltip(self.plot_widget.scene())\n\n        self.selection = None  # np.ndarray\n\n        self.n_valid = 0\n        self.n_shown = 0\n        self.sample_size = None\n        self.sample_indices = None\n\n        self.palette = None\n\n        self.shape_legend = self._create_legend(((1, 0), (1, 0)))\n        self.color_legend = self._create_legend(((1, 1), (1, 1)))\n        self.update_legend_visibility()\n\n        self.scale = None  # DiscretizedScale\n        self._too_many_labels = False\n\n        # self.setMouseTracking(True)\n        # self.grabGesture(QPinchGesture)\n        # self.grabGesture(QPanGesture)\n\n        self.update_grid_visibility()\n\n        self._tooltip_delegate = EventDelegate(self.help_event)\n        self.plot_widget.scene().installEventFilter(self._tooltip_delegate)\n        self.view_box.sigTransformChanged.connect(self.update_density)\n        self.view_box.sigRangeChangedManually.connect(self.update_labels)\n\n        self.timer = None\n\n    def _create_legend(self, anchor):\n        legend = LegendItem()\n        legend.setParentItem(self.plot_widget.getViewBox())\n        legend.restoreAnchor(anchor)\n        return legend\n\n    def _create_drag_tooltip(self, scene):\n        tip_parts = [\n            (Qt.ShiftModifier, \"Shift: Add group\"),\n            (Qt.ShiftModifier + Qt.ControlModifier,\n             \"Shift-{}: Append to group\".\n             format(\"Cmd\" if sys.platform == \"darwin\" else \"Ctrl\")),\n            (Qt.AltModifier, \"Alt: Remove\")\n        ]\n        all_parts = \", \".join(part for _, part in tip_parts)\n        self.tiptexts = {\n            int(modifier): all_parts.replace(part, \"<b>{}</b>\".format(part))\n            for modifier, part in tip_parts\n        }\n        self.tiptexts[0] = all_parts\n\n        self.tip_textitem = text = QGraphicsTextItem()\n        # Set to the longest text\n        text.setHtml(self.tiptexts[Qt.ShiftModifier + Qt.ControlModifier])\n        text.setPos(4, 2)\n        r = text.boundingRect()\n        rect = QGraphicsRectItem(0, 0, r.width() + 8, r.height() + 4)\n        rect.setBrush(QColor(224, 224, 224, 212))\n        rect.setPen(QPen(Qt.NoPen))\n        self.update_tooltip()\n\n        scene.drag_tooltip = scene.createItemGroup([rect, text])\n        scene.drag_tooltip.hide()\n\n    def update_tooltip(self, modifiers=Qt.NoModifier):\n        modifiers &= Qt.ShiftModifier + Qt.ControlModifier + Qt.AltModifier\n        text = self.tiptexts.get(int(modifiers), self.tiptexts[0])\n        self.tip_textitem.setHtml(text + self._get_jittering_tooltip())\n\n    def _get_jittering_tooltip(self):\n        warn_jittered = \"\"\n        if self.jitter_size:\n            warn_jittered = \\\n                '<br/><br/>' \\\n                '<span style=\"background-color: red; color: white; ' \\\n                'font-weight: 500;\">' \\\n                '&nbsp;Warning: Selection is applied to unjittered data&nbsp;' \\\n                '</span>'\n        return warn_jittered\n\n    def update_jittering(self):\n        self.update_tooltip()\n        x, y = self.get_coordinates()\n        if x is None or not len(x) or self.scatterplot_item is None:\n            return\n        self._update_plot_coordinates(self.scatterplot_item, x, y)\n        self._update_plot_coordinates(self.scatterplot_item_sel, x, y)\n        self.update_labels()\n\n    # TODO: Rename to remove_plot_items\n    def clear(self):\n        \"\"\"\n        Remove all graphical elements from the plot\n\n        Calls the pyqtgraph's plot widget's clear, sets all handles to `None`,\n        removes labels and selections.\n\n        This method should generally not be called by the widget. If the data\n        is gone (*e.g.* upon receiving `None` as an input data signal), this\n        should be handler by calling `reset_graph`, which will in turn call\n        `clear`.\n\n        Derived classes should override this method if they add more graphical\n        elements. For instance, the regression line in the scatterplot adds\n        `self.reg_line_item = None` (the line in the plot is already removed\n        in this method).\n        \"\"\"\n        self.plot_widget.clear()\n\n        self.density_img = None\n        if self.timer is not None and self.timer.isActive():\n            self.timer.stop()\n            self.timer = None\n        self.scatterplot_item = None\n        self.scatterplot_item_sel = None\n        self.labels = []\n        self._signal_too_many_labels(False)\n        self.view_box.init_history()\n        self.view_box.tag_history()\n\n    # TODO: I hate `keep_something` and `reset_something` arguments\n    # __keep_selection is used exclusively be set_sample size which would\n    # otherwise just repeat the code from reset_graph except for resetting\n    # the selection. I'm uncomfortable with this; we may prefer to have a\n    # method _reset_graph which does everything except resetting the selection,\n    # and reset_graph would call it.\n    def reset_graph(self, __keep_selection=False):\n        \"\"\"\n        Reset the graph to new data (or no data)\n\n        The method must be called when the plot receives new data, in\n        particular when the number of points change. If only their properties\n        - like coordinates or shapes - change, an update method\n        (`update_coordinates`, `update_shapes`...) should be called instead.\n\n        The method must also be called when the data is gone.\n\n        The method calls `clear`, followed by calls of all update methods.\n\n        NB. Argument `__keep_selection` is for internal use only\n        \"\"\"\n        self.clear()\n        if not __keep_selection:\n            self.selection = None\n        self.sample_indices = None\n        self.update_coordinates()\n        self.update_point_props()\n\n    def set_sample_size(self, sample_size):\n        \"\"\"\n        Set the sample size\n\n        Args:\n            sample_size (int or None): sample size or `None` to show all points\n        \"\"\"\n        if self.sample_size != sample_size:\n            self.sample_size = sample_size\n            self.reset_graph(True)\n\n    def update_point_props(self):\n        \"\"\"\n        Update the sizes, colors, shapes and labels\n\n        The method calls the appropriate update methods for individual\n        properties.\n        \"\"\"\n        self.update_sizes()\n        self.update_colors()\n        self.update_selection_colors()\n        self.update_shapes()\n        self.update_labels()\n\n    # Coordinates\n    # TODO: It could be nice if this method was run on entire data, not just\n    # a sample. For this, however, it would need to either be called from\n    # `get_coordinates` before sampling (very ugly) or call\n    # `self.master.get_coordinates_data` (beyond ugly) or the widget would\n    # have to store the ranges of unsampled data (ugly).\n    # Maybe we leave it as it is.\n    def _reset_view(self, x_data, y_data):\n        \"\"\"\n        Set the range of the view box\n\n        Args:\n            x_data (np.ndarray): x coordinates\n            y_data (np.ndarray) y coordinates\n        \"\"\"\n        min_x, max_x = np.min(x_data), np.max(x_data)\n        min_y, max_y = np.min(y_data), np.max(y_data)\n        self.view_box.setRange(\n            QRectF(min_x, min_y, max_x - min_x or 1, max_y - min_y or 1),\n            padding=0.025)\n\n    def _filter_visible(self, data):\n        \"\"\"Return the sample from the data using the stored sample_indices\"\"\"\n        if data is None or self.sample_indices is None:\n            return data\n        else:\n            return np.asarray(data[self.sample_indices])\n\n    def get_coordinates(self):\n        \"\"\"\n        Prepare coordinates of the points in the plot\n\n        The method is called by `update_coordinates`. It gets the coordinates\n        from the widget, jitters them and return them.\n\n        The methods also initializes the sample indices if neededd and stores\n        the original and sampled number of points.\n\n        Returns:\n            (tuple): a pair of numpy arrays containing (sampled) coordinates,\n                or `(None, None)`.\n        \"\"\"\n        x, y = self.master.get_coordinates_data()\n        if x is None:\n            self.n_valid = self.n_shown = 0\n            return None, None\n        self.n_valid = len(x)\n        self._create_sample()\n        x = self._filter_visible(x)\n        y = self._filter_visible(y)\n        # Jittering after sampling is OK if widgets do not change the sample\n        # semi-permanently, e.g. take a sample for the duration of some\n        # animation. If the sample size changes dynamically (like by adding\n        # a \"sample size\" slider), points would move around when the sample\n        # size changes. To prevent this, jittering should be done before\n        # sampling (i.e. two lines earlier). This would slow it down somewhat.\n        x, y = self.jitter_coordinates(x, y)\n        return x, y\n\n    def _create_sample(self):\n        \"\"\"\n        Create a random sample if the data is larger than the set sample size\n        \"\"\"\n        self.n_shown = min(self.n_valid, self.sample_size or self.n_valid)\n        if self.sample_size is not None \\\n                and self.sample_indices is None \\\n                and self.n_valid != self.n_shown:\n            random = np.random.RandomState(seed=0)\n            self.sample_indices = random.choice(\n                self.n_valid, self.n_shown, replace=False)\n            # TODO: Is this really needed?\n            np.sort(self.sample_indices)\n\n    def jitter_coordinates(self, x, y):\n        \"\"\"\n        Display coordinates to random positions within ellipses with\n        radiuses of `self.jittter_size` percents of spans\n        \"\"\"\n        if self.jitter_size == 0:\n            return x, y\n        return self._jitter_data(x, y)\n\n    def _jitter_data(self, x, y, span_x=None, span_y=None):\n        if span_x is None:\n            span_x = np.max(x) - np.min(x)\n        if span_y is None:\n            span_y = np.max(y) - np.min(y)\n        random = np.random.RandomState(seed=0)\n        rs = random.uniform(0, 1, len(x))\n        phis = random.uniform(0, 2 * np.pi, len(x))\n        magnitude = self.jitter_size / 100\n        return (x + magnitude * span_x * rs * np.cos(phis),\n                y + magnitude * span_y * rs * np.sin(phis))\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n\n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n            data[prop] = plot.data[prop]\n        plot.setData(**data)\n\n    def update_coordinates(self):\n        \"\"\"\n        Trigger the update of coordinates while keeping other features intact.\n\n        The method gets the coordinates by calling `self.get_coordinates`,\n        which in turn calls the widget's `get_coordinate_data`. The number of\n        coordinate pairs returned by the latter must match the current number\n        of points. If this is not the case, the widget should trigger\n        the complete update by calling `reset_graph` instead of this method.\n        \"\"\"\n        x, y = self.get_coordinates()\n        if x is None or not len(x):\n            return\n        if self.scatterplot_item is None:\n            if self.sample_indices is None:\n                indices = np.arange(self.n_valid)\n            else:\n                indices = self.sample_indices\n            kwargs = dict(x=x, y=y, data=indices)\n            self.scatterplot_item = ScatterPlotItem(**kwargs)\n            self.scatterplot_item.sigClicked.connect(self.select_by_click)\n            self.scatterplot_item_sel = ScatterPlotItem(**kwargs)\n            self.plot_widget.addItem(self.scatterplot_item_sel)\n            self.plot_widget.addItem(self.scatterplot_item)\n        else:\n            self._update_plot_coordinates(self.scatterplot_item, x, y)\n            self._update_plot_coordinates(self.scatterplot_item_sel, x, y)\n            self.update_labels()\n\n        self.update_density()  # Todo: doesn't work: try MDS with density on\n        self._reset_view(x, y)\n\n    # Sizes\n    def get_sizes(self):\n        \"\"\"\n        Prepare data for sizes of points in the plot\n\n        The method is called by `update_sizes`. It gets the sizes\n        from the widget and performs the necessary scaling and sizing.\n        The output is rounded to half a pixel for faster drawing.\n\n        Returns:\n            (np.ndarray): sizes\n        \"\"\"\n        size_column = self.master.get_size_data()\n        if size_column is None:\n            return np.full((self.n_shown,),\n                           self.MinShapeSize + (5 + self.point_width) * 0.5)\n        size_column = self._filter_visible(size_column)\n        size_column = size_column.copy()\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n            size_column -= np.nanmin(size_column)\n            mx = np.nanmax(size_column)\n        if mx > 0:\n            size_column /= mx\n        else:\n            size_column[:] = 0.5\n\n        sizes = self.MinShapeSize + (5 + self.point_width) * size_column\n        # round sizes to half pixel for smaller pyqtgraph's symbol pixmap atlas\n        sizes = (sizes * 2).round() / 2\n        return sizes\n\n    def update_sizes(self):\n        \"\"\"\n        Trigger an update of point sizes\n\n        The method calls `self.get_sizes`, which in turn calls the widget's\n        `get_size_data`. The result are properly scaled and then passed\n        back to widget for imputing (`master.impute_sizes`).\n        \"\"\"\n        if self.scatterplot_item:\n            size_data = self.get_sizes()\n            size_imputer = getattr(\n                self.master, \"impute_sizes\", self.default_impute_sizes)\n            size_imputer(size_data)\n\n            if self.timer is not None and self.timer.isActive():\n                self.timer.stop()\n                self.timer = None\n\n            current_size_data = self.scatterplot_item.data[\"size\"].copy()\n            diff = size_data - current_size_data\n            widget = self\n\n            class Timeout:\n                # 0.5 - np.cos(np.arange(0.17, 1, 0.17) * np.pi) / 2\n                factors = [0.07, 0.26, 0.52, 0.77, 0.95, 1]\n\n                def __init__(self):\n                    self._counter = 0\n\n                def __call__(self):\n                    factor = self.factors[self._counter]\n                    self._counter += 1\n                    size = current_size_data + diff * factor\n                    if len(self.factors) == self._counter:\n                        widget.timer.stop()\n                        widget.timer = None\n                        size = size_data\n                    widget.scatterplot_item.setSize(size)\n                    widget.scatterplot_item_sel.setSize(size + SELECTION_WIDTH)\n                    if widget.timer is None:\n                        widget.end_resizing.emit()\n                    else:\n                        widget.step_resizing.emit()\n\n            if self.n_valid <= MAX_N_VALID_SIZE_ANIMATE and \\\n                    np.all(current_size_data > 0) and np.any(diff != 0):\n                # If encountered any strange behaviour when updating sizes,\n                # implement it with threads\n                self.begin_resizing.emit()\n                self.timer = QTimer(self.scatterplot_item, interval=50)\n                self.timer.timeout.connect(Timeout())\n                self.timer.start()\n            else:\n                self.begin_resizing.emit()\n                self.scatterplot_item.setSize(size_data)\n                self.scatterplot_item_sel.setSize(size_data + SELECTION_WIDTH)\n                self.end_resizing.emit()\n\n    update_point_size = update_sizes  # backward compatibility (needed?!)\n    update_size = update_sizes\n\n    @classmethod\n    def default_impute_sizes(cls, size_data):\n        \"\"\"\n        Fallback imputation for sizes.\n\n        Set the size to two pixels smaller than the minimal size\n\n        Returns:\n            (bool): True if there was any missing data\n        \"\"\"\n        nans = np.isnan(size_data)\n        if np.any(nans):\n            size_data[nans] = cls.MinShapeSize - 2\n            return True\n        else:\n            return False\n\n    # Colors\n    def get_colors(self):\n        \"\"\"\n        Prepare data for colors of the points in the plot\n\n        The method is called by `update_colors`. It gets the colors and the\n        indices of the data subset from the widget (`get_color_data`,\n        `get_subset_mask`), and constructs lists of pens and brushes for\n        each data point.\n\n        The method uses different palettes for discrete and continuous data,\n        as determined by calling the widget's method `is_continuous_color`.\n\n        If also marks the points that are in the subset as defined by, for\n        instance the 'Data Subset' signal in the Scatter plot and similar\n        widgets. (Do not confuse this with *selected points*, which are\n        marked by circles around the points, which are colored by groups\n        and thus independent of this method.)\n\n        Returns:\n            (tuple): a list of pens and list of brushes\n        \"\"\"\n        self.palette = self.master.get_palette()\n        c_data = self.master.get_color_data()\n        c_data = self._filter_visible(c_data)\n        subset = self.master.get_subset_mask()\n        subset = self._filter_visible(subset)\n        self.subset_is_shown = subset is not None\n        if c_data is None:  # same color\n            return self._get_same_colors(subset)\n        elif self.master.is_continuous_color():\n            return self._get_continuous_colors(c_data, subset)\n        else:\n            return self._get_discrete_colors(c_data, subset)\n\n    def _get_same_colors(self, subset):\n        \"\"\"\n        Return the same pen for all points while the brush color depends\n        upon whether the point is in the subset or not\n\n        Args:\n            subset (np.ndarray): a bool array indicating whether a data point\n                is in the subset or not (e.g. in the 'Data Subset' signal\n                in the Scatter plot and similar widgets);\n\n        Returns:\n            (tuple): a list of pens and list of brushes\n        \"\"\"\n        color = self.plot_widget.palette().color(OWPalette.Data)\n        pen = [_make_pen(color, 1.5)] * self.n_shown  # use a single QPen instance\n        if subset is not None:\n            brush = np.where(\n                subset,\n                *(QBrush(QColor(*col))\n                  for col in (self.COLOR_SUBSET, self.COLOR_NOT_SUBSET)))\n        else:\n            color = QColor(*self.COLOR_DEFAULT)\n            color.setAlpha(self.alpha_value)\n            brush = [QBrush(color)] * self.n_shown  # use a single QBrush instance\n        return pen, brush\n\n    def _get_continuous_colors(self, c_data, subset):\n        \"\"\"\n        Return the pens and colors whose color represent an index into\n        a continuous palette. The same color is used for pen and brush,\n        except the former is darker. If the data has a subset, the brush\n        is transparent for points that are not in the subset.\n        \"\"\"\n        if np.isnan(c_data).all():\n            self.scale = None\n        else:\n            self.scale = DiscretizedScale(np.nanmin(c_data), np.nanmax(c_data))\n            c_data -= self.scale.offset\n            c_data /= self.scale.width\n            c_data = np.floor(c_data) + 0.5\n            c_data /= self.scale.bins\n            c_data = np.clip(c_data, 0, 1)\n        pen = self.palette.getRGB(c_data)\n        brush = np.hstack(\n            [pen, np.full((len(pen), 1), self.alpha_value, dtype=int)])\n        pen *= 100\n        pen //= self.DarkerValue\n\n        # Reuse pens and brushes with the same colors because PyQtGraph then builds\n        # smaller pixmap atlas, which makes the drawing faster\n\n        def reuse(cache, fn, *args):\n            if args not in cache:\n                cache[args] = fn(args)\n            return cache[args]\n\n        def create_pen(col):\n            return _make_pen(QColor(*col), 1.5)\n\n        def create_brush(col):\n            return QBrush(QColor(*col))\n\n        cached_pens = {}\n        pen = [reuse(cached_pens, create_pen, *col) for col in pen.tolist()]\n\n        if subset is not None:\n            brush[:, 3] = 0\n            brush[subset, 3] = 255\n\n        cached_brushes = {}\n        brush = np.array([reuse(cached_brushes, create_brush, *col) for col in brush.tolist()])\n\n        return pen, brush\n\n    def _get_discrete_colors(self, c_data, subset):\n        \"\"\"\n        Return the pens and colors whose color represent an index into\n        a discrete palette. The same color is used for pen and brush,\n        except the former is darker. If the data has a subset, the brush\n        is transparent for points that are not in the subset.\n        \"\"\"\n        n_colors = self.palette.number_of_colors\n        c_data = c_data.copy()\n        c_data[np.isnan(c_data)] = n_colors\n        c_data = c_data.astype(int)\n        colors = np.r_[self.palette.getRGB(np.arange(n_colors)),\n                       [[128, 128, 128]]]\n        pens = np.array(\n            [_make_pen(QColor(*col).darker(self.DarkerValue), 1.5)\n             for col in colors])\n        pen = pens[c_data]\n        alpha = self.alpha_value if subset is None else 255\n        brushes = np.array([\n            [QBrush(QColor(0, 0, 0, 0)),\n             QBrush(QColor(col[0], col[1], col[2], alpha))]\n            for col in colors])\n        brush = brushes[c_data]\n\n        if subset is not None:\n            brush = np.where(subset, brush[:, 1], brush[:, 0])\n        else:\n            brush = brush[:, 1]\n        return pen, brush\n\n    def update_colors(self):\n        \"\"\"\n        Trigger an update of point sizes\n\n        The method calls `self.get_colors`, which in turn calls the widget's\n        `get_color_data` to get the indices in the pallette. `get_colors`\n        returns a list of pens and brushes to which this method uses to\n        update the colors. Finally, the method triggers the update of the\n        legend and the density plot.\n        \"\"\"\n        if self.scatterplot_item is not None:\n            pen_data, brush_data = self.get_colors()\n            self.scatterplot_item.setPen(pen_data, update=False, mask=None)\n            self.scatterplot_item.setBrush(brush_data, mask=None)\n        self.update_legends()\n        self.update_density()\n\n    update_alpha_value = update_colors\n\n    def update_density(self):\n        \"\"\"\n        Remove the existing density plot (if there is one) and replace it\n        with a new one (if enabled).\n\n        The method gets the colors from the pens of the currently plotted\n        points.\n        \"\"\"\n        if self.density_img:\n            self.plot_widget.removeItem(self.density_img)\n            self.density_img = None\n        if self.class_density and self.scatterplot_item is not None:\n            rgb_data = [\n                pen.color().getRgb()[:3] if pen is not None else (255, 255, 255)\n                for pen in self.scatterplot_item.data['pen']]\n            if len(set(rgb_data)) <= 1:\n                return\n            [min_x, max_x], [min_y, max_y] = self.view_box.viewRange()\n            x_data, y_data = self.scatterplot_item.getData()\n            self.density_img = classdensity.class_density_image(\n                min_x, max_x, min_y, max_y, self.resolution,\n                x_data, y_data, rgb_data)\n            self.plot_widget.addItem(self.density_img)\n\n    def update_selection_colors(self):\n        \"\"\"\n        Trigger an update of selection markers\n\n        This update method is usually not called by the widget but by the\n        plot, since it is the plot that handles the selections.\n\n        Like other update methods, it calls the corresponding get method\n        (`get_colors_sel`) which returns a list of pens and brushes.\n        \"\"\"\n        if self.scatterplot_item_sel is None:\n            return\n        pen, brush = self.get_colors_sel()\n        self.scatterplot_item_sel.setPen(pen, update=False, mask=None)\n        self.scatterplot_item_sel.setBrush(brush, mask=None)\n\n    def get_colors_sel(self):\n        \"\"\"\n        Return pens and brushes for selection markers.\n\n        A pen can is set to `Qt.NoPen` if a point is not selected.\n\n        All brushes are completely transparent whites.\n\n        Returns:\n            (tuple): a list of pens and a list of brushes\n        \"\"\"\n        nopen = QPen(Qt.NoPen)\n        if self.selection is None:\n            pen = [nopen] * self.n_shown\n        else:\n            sels = np.max(self.selection)\n            if sels == 1:\n                pen = np.where(\n                    self._filter_visible(self.selection),\n                    _make_pen(QColor(255, 190, 0, 255), SELECTION_WIDTH + 1),\n                    nopen)\n            else:\n                palette = ColorPaletteGenerator(number_of_colors=sels + 1)\n                pen = np.choose(\n                    self._filter_visible(self.selection),\n                    [nopen] + [_make_pen(palette[i], SELECTION_WIDTH + 1)\n                               for i in range(sels)])\n        return pen, [QBrush(QColor(255, 255, 255, 0))] * self.n_shown\n\n    # Labels\n    def get_labels(self):\n        \"\"\"\n        Prepare data for labels for points\n\n        The method returns the results of the widget's `get_label_data`\n\n        Returns:\n            (labels): a sequence of labels\n        \"\"\"\n        return self._filter_visible(self.master.get_label_data())\n\n    def update_labels(self):\n        \"\"\"\n        Trigger an update of labels\n\n        The method calls `get_labels` which in turn calls the widget's\n        `get_label_data`. The obtained labels are shown if the corresponding\n        points are selected or if `label_only_selected` is `false`.\n        \"\"\"\n        for label in self.labels:\n            self.plot_widget.removeItem(label)\n        self.labels = []\n\n        mask = None\n        if self.scatterplot_item is not None:\n            x, y = self.scatterplot_item.getData()\n            mask = self._label_mask(x, y)\n\n        if mask is not None:\n            labels = self.get_labels()\n            if labels is None:\n                mask = None\n\n        self._signal_too_many_labels(\n            mask is not None and mask.sum() > self.MAX_VISIBLE_LABELS)\n        if self._too_many_labels or mask is None or not np.any(mask):\n            return\n\n        black = pg.mkColor(0, 0, 0)\n        labels = labels[mask]\n        x = x[mask]\n        y = y[mask]\n        for label, xp, yp in zip(labels, x, y):\n            ti = TextItem(label, black)\n            ti.setPos(xp, yp)\n            self.plot_widget.addItem(ti)\n            self.labels.append(ti)\n\n    def _signal_too_many_labels(self, too_many):\n        if self._too_many_labels != too_many:\n            self._too_many_labels = too_many\n            self.too_many_labels.emit(too_many)\n\n    def _label_mask(self, x, y):\n        (x0, x1), (y0, y1) = self.view_box.viewRange()\n        mask = np.logical_and(\n            np.logical_and(x >= x0, x <= x1),\n            np.logical_and(y >= y0, y <= y1))\n        if self.label_only_selected:\n            sub_mask = self._filter_visible(self.master.get_subset_mask())\n            if self.selection is None:\n                if sub_mask is None:\n                    return None\n                else:\n                    sel_mask = sub_mask\n            else:\n                sel_mask = self._filter_visible(self.selection) != 0\n                if sub_mask is not None:\n                    sel_mask = np.logical_or(sel_mask, sub_mask)\n            mask = np.logical_and(mask, sel_mask)\n        return mask\n\n    # Shapes\n    def get_shapes(self):\n        \"\"\"\n        Prepare data for shapes of points in the plot\n\n        The method is called by `update_shapes`. It gets the data from\n        the widget's `get_shape_data`, and then calls its `impute_shapes`\n        to impute the missing shape (usually with some default shape).\n\n        Returns:\n            (np.ndarray): an array of symbols (e.g. o, x, + ...)\n        \"\"\"\n        shape_data = self.master.get_shape_data()\n        shape_data = self._filter_visible(shape_data)\n        # Data has to be copied so the imputation can change it in-place\n        # TODO: Try avoiding this when we move imputation to the widget\n        if shape_data is not None:\n            shape_data = np.copy(shape_data)\n        shape_imputer = getattr(\n            self.master, \"impute_shapes\", self.default_impute_shapes)\n        shape_imputer(shape_data, len(self.CurveSymbols) - 1)\n        if isinstance(shape_data, np.ndarray):\n            shape_data = shape_data.astype(int)\n        else:\n            shape_data = np.zeros(self.n_shown, dtype=int)\n        return self.CurveSymbols[shape_data]\n\n    @staticmethod\n    def default_impute_shapes(shape_data, default_symbol):\n        \"\"\"\n        Fallback imputation for shapes.\n\n        Use the default symbol, usually the last symbol in the list.\n\n        Returns:\n            (bool): True if there was any missing data\n        \"\"\"\n        if shape_data is None:\n            return False\n        nans = np.isnan(shape_data)\n        if np.any(nans):\n            shape_data[nans] = default_symbol\n            return True\n        else:\n            return False\n\n    def update_shapes(self):\n        \"\"\"\n        Trigger an update of point symbols\n\n        The method calls `get_shapes` to obtain an array with a symbol\n        for each point and uses it to update the symbols.\n\n        Finally, the method updates the legend.\n        \"\"\"\n        if self.scatterplot_item:\n            shape_data = self.get_shapes()\n            self.scatterplot_item.setSymbol(shape_data)\n        self.update_legends()\n\n    def update_grid_visibility(self):\n        \"\"\"Show or hide the grid\"\"\"\n        self.plot_widget.showGrid(x=self.show_grid, y=self.show_grid)\n\n    def update_legend_visibility(self):\n        \"\"\"\n        Show or hide legends based on whether they are enabled and non-empty\n        \"\"\"\n        self.shape_legend.setVisible(\n            self.show_legend and bool(self.shape_legend.items))\n        self.color_legend.setVisible(\n            self.show_legend and bool(self.color_legend.items))\n\n    def update_legends(self):\n        \"\"\"Update content of legends and their visibility\"\"\"\n        cont_color = self.master.is_continuous_color()\n        shape_labels = self.master.get_shape_labels()\n        color_labels = self.master.get_color_labels()\n        if shape_labels == color_labels and shape_labels is not None:\n            self._update_combined_legend(shape_labels)\n        else:\n            self._update_shape_legend(shape_labels)\n            if cont_color:\n                self._update_continuous_color_legend(color_labels)\n            else:\n                self._update_color_legend(color_labels)\n        self.update_legend_visibility()\n\n    def _update_shape_legend(self, labels):\n        self.shape_legend.clear()\n        if labels is None or self.scatterplot_item is None:\n            return\n        color = QColor(0, 0, 0)\n        color.setAlpha(self.alpha_value)\n        for label, symbol in zip(labels, self.CurveSymbols):\n            self.shape_legend.addItem(\n                ScatterPlotItem(pen=color, brush=color, size=10, symbol=symbol),\n                escape(label))\n\n    def _update_continuous_color_legend(self, label_formatter):\n        self.color_legend.clear()\n        if self.scale is None or self.scatterplot_item is None:\n            return\n        label = PaletteItemSample(self.palette, self.scale, label_formatter)\n        self.color_legend.addItem(label, \"\")\n        self.color_legend.setGeometry(label.boundingRect())\n\n    def _update_color_legend(self, labels):\n        self.color_legend.clear()\n        if labels is None:\n            return\n        self._update_colored_legend(self.color_legend, labels, 'o')\n\n    def _update_combined_legend(self, labels):\n        # update_colored_legend will already clear the shape legend\n        # so we remove colors here\n        use_legend = \\\n            self.shape_legend if self.shape_legend.items else self.color_legend\n        self.color_legend.clear()\n        self.shape_legend.clear()\n        self._update_colored_legend(use_legend, labels, self.CurveSymbols)\n\n    def _update_colored_legend(self, legend, labels, symbols):\n        if self.scatterplot_item is None or not self.palette:\n            return\n        if isinstance(symbols, str):\n            symbols = itertools.repeat(symbols, times=len(labels))\n        for i, (label, symbol) in enumerate(zip(labels, symbols)):\n            color = QColor(*self.palette.getRGB(i))\n            pen = _make_pen(color.darker(self.DarkerValue), 1.5)\n            color.setAlpha(255 if self.subset_is_shown else self.alpha_value)\n            brush = QBrush(color)\n            legend.addItem(\n                ScatterPlotItem(pen=pen, brush=brush, size=10, symbol=symbol),\n                escape(label))\n\n    def zoom_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().RectMode)\n\n    def pan_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().PanMode)\n\n    def select_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().RectMode)\n\n    def reset_button_clicked(self):\n        self.plot_widget.getViewBox().autoRange()\n        self.update_labels()\n\n    def select_by_click(self, _, points):\n        if self.scatterplot_item is not None:\n            self.select(points)\n\n    def select_by_rectangle(self, rect):\n        if self.scatterplot_item is not None:\n            x0, x1 = sorted((rect.topLeft().x(), rect.bottomRight().x()))\n            y0, y1 = sorted((rect.topLeft().y(), rect.bottomRight().y()))\n            x, y = self.master.get_coordinates_data()\n            indices = np.flatnonzero(\n                (x0 <= x) & (x <= x1) & (y0 <= y) & (y <= y1))\n            self.select_by_indices(indices.astype(int))\n\n    def unselect_all(self):\n        if self.selection is not None:\n            self.selection = None\n            self.update_selection_colors()\n            if self.label_only_selected:\n                self.update_labels()\n            self.master.selection_changed()\n\n    def select(self, points):\n        # noinspection PyArgumentList\n        if self.scatterplot_item is None:\n            return\n        indices = [p.data() for p in points]\n        self.select_by_indices(indices)\n\n    def select_by_indices(self, indices):\n        if self.selection is None:\n            self.selection = np.zeros(self.n_valid, dtype=np.uint8)\n        keys = QApplication.keyboardModifiers()\n        if keys & Qt.AltModifier:\n            self.selection_remove(indices)\n        elif keys & Qt.ShiftModifier and keys & Qt.ControlModifier:\n            self.selection_append(indices)\n        elif keys & Qt.ShiftModifier:\n            self.selection_new_group(indices)\n        else:\n            self.selection_select(indices)\n\n    def selection_select(self, indices):\n        self.selection = np.zeros(self.n_valid, dtype=np.uint8)\n        self.selection[indices] = 1\n        self._update_after_selection()\n\n    def selection_append(self, indices):\n        self.selection[indices] = np.max(self.selection)\n        self._update_after_selection()\n\n    def selection_new_group(self, indices):\n        self.selection[indices] = np.max(self.selection) + 1\n        self._update_after_selection()\n\n    def selection_remove(self, indices):\n        self.selection[indices] = 0\n        self._update_after_selection()\n\n    def _update_after_selection(self):\n        self._compress_indices()\n        self.update_selection_colors()\n        if self.label_only_selected:\n            self.update_labels()\n        self.master.selection_changed()\n\n    def _compress_indices(self):\n        indices = sorted(set(self.selection) | {0})\n        if len(indices) == max(indices) + 1:\n            return\n        mapping = np.zeros((max(indices) + 1,), dtype=int)\n        for i, ind in enumerate(indices):\n            mapping[ind] = i\n        self.selection = mapping[self.selection]\n\n    def get_selection(self):\n        if self.selection is None:\n            return np.array([], dtype=np.uint8)\n        else:\n            return np.flatnonzero(self.selection)\n\n    def help_event(self, event):\n        \"\"\"\n        Create a `QToolTip` for the point hovered by the mouse\n        \"\"\"\n        if self.scatterplot_item is None:\n            return False\n        act_pos = self.scatterplot_item.mapFromScene(event.scenePos())\n        point_data = [p.data() for p in self.scatterplot_item.pointsAt(act_pos)]\n        text = self.master.get_tooltip(point_data)\n        if text:\n            QToolTip.showText(event.screenPos(), text, widget=self.plot_widget)\n            return True\n        else:\n            return False",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 270,
                            "end_lineno": 1378,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "# pylint: disable=missing-docstring,too-many-lines,too-many-public-methods\n# pylint: disable=protected-access\nfrom unittest.mock import patch, Mock\nimport numpy as np\n\nfrom AnyQt.QtCore import QRectF, Qt\nfrom AnyQt.QtGui import QColor\nfrom AnyQt.QtTest import QSignalSpy\n\nfrom pyqtgraph import mkPen\n\nfrom Orange.widgets.settings import SettingProvider\nfrom Orange.widgets.tests.base import WidgetTest\nfrom Orange.widgets.utils.colorpalette import ColorPaletteGenerator, \\\n    ContinuousPaletteGenerator, NAN_GREY\nfrom Orange.widgets.visualize.owscatterplotgraph import OWScatterPlotBase, \\\n    ScatterPlotItem, SELECTION_WIDTH\nfrom Orange.widgets.widget import OWWidget\n\n\nclass MockWidget(OWWidget):\n    name = \"Mock\"\n\n    get_coordinates_data = Mock(return_value=(None, None))\n    get_size_data = Mock(return_value=None)\n    get_shape_data = Mock(return_value=None)\n    get_color_data = Mock(return_value=None)\n    get_label_data = Mock(return_value=None)\n    get_color_labels = Mock(return_value=None)\n    get_shape_labels = Mock(return_value=None)\n    get_subset_mask = Mock(return_value=None)\n    get_tooltip = Mock(return_value=\"\")\n\n    is_continuous_color = Mock(return_value=False)\n    can_draw_density = Mock(return_value=True)\n    combined_legend = Mock(return_value=False)\n    selection_changed = Mock(return_value=None)\n\n    GRAPH_CLASS = OWScatterPlotBase\n    graph = SettingProvider(OWScatterPlotBase)\n\n    def get_palette(self):\n        if self.is_continuous_color():\n            return ContinuousPaletteGenerator(Qt.white, Qt.black, False)\n        else:\n            return ColorPaletteGenerator(12)\n\n\nclass TestOWScatterPlotBase(WidgetTest):\n    def setUp(self):\n        self.master = MockWidget()\n        self.graph = OWScatterPlotBase(self.master)\n\n        self.xy = (np.arange(10, dtype=float), np.arange(10, dtype=float))\n        self.master.get_coordinates_data = lambda: self.xy\n\n    # pylint: disable=keyword-arg-before-vararg\n    def setRange(self, rect=None, *_, **__):\n        if isinstance(rect, QRectF):\n            self.last_setRange = [[rect.left(), rect.right()],\n                                  [rect.top(), rect.bottom()]]\n\n    def test_update_coordinates_no_data(self):\n        self.xy = None, None\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n        self.xy = [], []\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        graph.reset_graph()\n\n        scatterplot_item = graph.scatterplot_item\n        scatterplot_item_sel = graph.scatterplot_item_sel\n        data = scatterplot_item.data\n\n        np.testing.assert_almost_equal(scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(scatterplot_item_sel.getData(), xy)\n        scatterplot_item.setSize([5, 6])\n        scatterplot_item.setSymbol([7, 8])\n        scatterplot_item.setPen([mkPen(9), mkPen(10)])\n        scatterplot_item.setBrush([11, 12])\n        data[\"data\"] = np.array([13, 14])\n\n        xy[0][0] = 0\n        graph.update_coordinates()\n        np.testing.assert_almost_equal(graph.scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(graph.scatterplot_item_sel.getData(), xy)\n\n        # Graph updates coordinates instead of creating new items\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        self.assertIs(scatterplot_item_sel, graph.scatterplot_item_sel)\n        np.testing.assert_almost_equal(data[\"size\"], [5, 6])\n        np.testing.assert_almost_equal(data[\"symbol\"], [7, 8])\n        self.assertEqual(data[\"pen\"][0], mkPen(9))\n        self.assertEqual(data[\"pen\"][1], mkPen(10))\n        np.testing.assert_almost_equal(data[\"brush\"], [11, 12])\n        np.testing.assert_almost_equal(data[\"data\"], [13, 14])\n\n    def test_update_coordinates_and_labels(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1., 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 1.5\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 1.5)\n        xy[0][0] = 0  # This label goes out of the range\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 2)\n\n    def test_update_coordinates_and_density(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 0\n        graph.update_density = Mock()\n        graph.update_coordinates()\n        graph.update_density.assert_called_with()\n\n    def test_update_coordinates_reset_view(self):\n        graph = self.graph\n        graph.view_box.setRange = self.setRange\n        xy = self.xy = (np.array([2, 1]), np.array([3, 10]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(self.last_setRange, [[1, 2], [3, 10]])\n\n        xy[0][1] = 0\n        graph.update_coordinates()\n        self.assertEqual(self.last_setRange, [[0, 2], [3, 10]])\n\n    def test_reset_graph_no_data(self):\n        self.xy = (None, None)\n        self.graph.scatterplot_item = ScatterPlotItem([1, 2], [3, 4])\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates_indices(self):\n        graph = self.graph\n        self.xy = (np.array([2, 1]), np.array([3, 10]))\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item.data[\"data\"], [0, 1])\n\n    def test_sampling(self):\n        graph = self.graph\n        master = self.master\n\n        # Enable sampling before getting the data\n        graph.set_sample_size(3)\n        xy = self.xy = (np.arange(10, dtype=float),\n                        np.arange(0, 30, 3, dtype=float))\n        d = np.arange(10, dtype=float)\n        master.get_size_data = lambda: d\n        master.get_shape_data = lambda: d % 5 if d is not None else None\n        master.get_color_data = lambda: d\n        master.get_label_data = lambda: \\\n            np.array([str(x) for x in d], dtype=object)\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n        # Check proper sampling\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertNotEqual(x[0], x[1])\n        self.assertNotEqual(x[0], x[2])\n        self.assertNotEqual(x[1], x[2])\n        np.testing.assert_almost_equal(3 * x, y)\n\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Check that sample is extended when sample size is changed\n        graph.set_sample_size(4)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s = data[\"size\"] - graph.MinShapeSize\n        precise_s = (x - min(x)) / (max(x) - min(x)) * max(s)\n        np.testing.assert_almost_equal(s, precise_s, decimal=0)\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Disable sampling\n        graph.set_sample_size(None)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        np.testing.assert_almost_equal(x, xy[0])\n        np.testing.assert_almost_equal(y, xy[1])\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in d])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in d])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in d])\n\n        # Enable sampling when data is already present and not sampled\n        graph.set_sample_size(3)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Update data when data is present and sampling is enabled\n        xy[0][:] = np.arange(9, -1, -1, dtype=float)\n        d = xy[0]\n        graph.update_coordinates()\n        x1, _ = scatterplot_item.getData()\n        np.testing.assert_almost_equal(9 - x, x1)\n        graph.update_sizes()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Reset graph when data is present and sampling is enabled\n        self.xy = (np.arange(100, 105, dtype=float),\n                   np.arange(100, 105, dtype=float))\n        d = self.xy[0] - 100\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertTrue(np.all(x > 99))\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Don't sample when unnecessary\n        self.xy = (np.arange(100, dtype=float), ) * 2\n        d = None\n        delattr(master, \"get_label_data\")\n        graph.reset_graph()\n        graph.set_sample_size(120)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_almost_equal(x, np.arange(100))\n\n    def test_sampling_keeps_selection(self):\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n        graph.reset_graph()\n        graph.select_by_indices(np.arange(1, 100, 2))\n        graph.set_sample_size(30)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n        graph.set_sample_size(None)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n\n    base = \"Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase.\"\n\n    @patch(base + \"update_sizes\")\n    @patch(base + \"update_colors\")\n    @patch(base + \"update_selection_colors\")\n    @patch(base + \"update_shapes\")\n    @patch(base + \"update_labels\")\n    def test_reset_calls_all_updates_and_update_doesnt(self, *mocks):\n        master = MockWidget()\n        graph = OWScatterPlotBase(master)\n        for mock in mocks:\n            mock.assert_not_called()\n\n        graph.reset_graph()\n        for mock in mocks:\n            mock.assert_called_with()\n            mock.reset_mock()\n\n        graph.update_coordinates()\n        for mock in mocks:\n            mock.assert_not_called()\n\n    def test_jittering(self):\n        graph = self.graph\n        graph.jitter_size = 10\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        a10 = np.arange(10)\n        self.assertTrue(np.any(np.nonzero(a10 - x)))\n        self.assertTrue(np.any(np.nonzero(a10 - y)))\n        np.testing.assert_array_less(a10 - x, 1)\n        np.testing.assert_array_less(a10 - y, 1)\n\n        graph.jitter_size = 0\n        graph.update_coordinates()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_equal(a10, x)\n\n    def test_size_normalization(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, [6, 7.5, 9.5, 11, 12.5, 14.5, 16, 17.5, 19.5, 21])\n\n        d = np.arange(10, 20, dtype=float)\n        graph.update_sizes()\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        size2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, size2)\n\n    def test_size_rounding_half_pixel(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size*2 - (size*2).round(), 0)\n\n    def test_size_with_nans(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n\n        d[4] = np.nan\n        graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        sizes2 = scatterplot_item.data[\"size\"]\n\n        self.assertEqual(sizes[1] - sizes[0], sizes2[1] - sizes2[0])\n        self.assertLess(sizes2[4], self.graph.MinShapeSize)\n\n        d[:] = np.nan\n        graph.update_sizes()\n        sizes3 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes3)\n\n    def test_sizes_all_same_or_nan(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.full((10, ), 3.0)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n        self.assertEqual(len(set(sizes)), 1)\n        self.assertGreater(sizes[0], self.graph.MinShapeSize)\n\n        d = None\n        graph.update_sizes()\n        scatterplot_item = graph.scatterplot_item\n        sizes2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes2)\n\n    def test_sizes_point_width_is_linear(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.point_width = 1\n        graph.reset_graph()\n        sizes1 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 2\n        graph.update_sizes()\n        sizes2 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 3\n        graph.update_sizes()\n        sizes3 = graph.scatterplot_item.data[\"size\"]\n\n        np.testing.assert_almost_equal(2 * (sizes2 - sizes1), sizes3 - sizes1)\n\n    def test_sizes_custom_imputation(self):\n\n        def impute_max(size_data):\n            size_data[np.isnan(size_data)] = np.nanmax(size_data)\n\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        self.master.impute_sizes = impute_max\n        d = np.arange(10, dtype=float)\n        d[4] = np.nan\n        graph.reset_graph()\n        sizes = graph.scatterplot_item.data[\"size\"]\n        self.assertAlmostEqual(sizes[4], sizes[9])\n\n    def test_sizes_selection(self):\n        graph = self.graph\n        graph.get_size = lambda: np.arange(10, dtype=float)\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item_sel.data[\"size\"]\n            - graph.scatterplot_item.data[\"size\"],\n            SELECTION_WIDTH)\n\n    @patch(\"Orange.widgets.visualize.owscatterplotgraph\"\n           \".MAX_N_VALID_SIZE_ANIMATE\", 5)\n    def test_size_animation(self):\n        begin_resizing = QSignalSpy(self.graph.begin_resizing)\n        step_resizing = QSignalSpy(self.graph.step_resizing)\n        end_resizing = QSignalSpy(self.graph.end_resizing)\n        self._update_sizes_for_points(5)\n        # first end_resizing is triggered in reset, thus wait for step_resizing\n        step_resizing.wait(200)\n        end_resizing.wait(200)\n        self.assertEqual(len(begin_resizing), 2)  # reset and update\n        self.assertEqual(len(step_resizing), 5)\n        self.assertEqual(len(end_resizing), 2)  # reset and update\n        self.assertEqual(self.graph.scatterplot_item.setSize.call_count, 6)\n        self._update_sizes_for_points(6)\n        self.graph.scatterplot_item.setSize.assert_called_once()\n\n    def _update_sizes_for_points(self, n: int):\n        arr = np.arange(n, dtype=float)\n        self.master.get_coordinates_data = lambda: (arr, arr)\n        self.master.get_size_data = lambda: arr\n        self.graph.reset_graph()\n        self.graph.scatterplot_item.setSize = Mock(\n            wraps=self.graph.scatterplot_item.setSize)\n        self.master.get_size_data = lambda: arr[::-1]\n        self.graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n    def test_colors_discrete(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        self.master.get_color_data = lambda: d\n        d = np.arange(10, dtype=float) % 2\n\n        graph.reset_graph()\n        data = graph.scatterplot_item.data\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"pen\"])))\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"brush\"])))\n\n        # confirm that QPen/QBrush were reused\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 2)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)\n\n    def test_colors_discrete_nan(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        self.assertEqual(pens[0].color().hue(), palette[0].hue())\n        self.assertEqual(pens[1].color().hue(), palette[1].hue())\n        self.assertEqual(brushes[0].color().hue(), palette[0].hue())\n        self.assertEqual(brushes[1].color().hue(), palette[1].hue())\n        self.assertEqual(pens[4].color().hue(), QColor(128, 128, 128).hue())\n        self.assertEqual(brushes[4].color().hue(), QColor(128, 128, 128).hue())\n\n    def test_colors_continuous(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()  # I don't have a good test ... just don't crash\n\n        d[4] = np.nan\n        graph.update_colors()  # Ditto\n\n    def test_colors_continuous_reused(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n\n        d = np.arange(100, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n\n        data = graph.scatterplot_item.data\n\n        self.assertEqual(len(data[\"pen\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"pen\"]))), 10)\n        self.assertEqual(len(data[\"brush\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"brush\"]))), 10)\n\n    def test_colors_continuous_nan(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        nan_color = QColor(*NAN_GREY)\n        self.assertEqual(pens[4].color().hue(), nan_color.hue())\n        self.assertEqual(brushes[4].color().hue(), nan_color.hue())\n\n    def test_colors_subset(self):\n        def run_tests():\n            self.master.get_subset_mask = lambda: None\n\n            graph.alpha_value = 42\n            graph.reset_graph()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 42)\n            self.assertEqual(brushes[1].color().alpha(), 42)\n            self.assertEqual(brushes[4].color().alpha(), 42)\n\n            graph.alpha_value = 123\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 123)\n            self.assertEqual(brushes[1].color().alpha(), 123)\n            self.assertEqual(brushes[4].color().alpha(), 123)\n\n            self.master.get_subset_mask = lambda: np.arange(10) >= 5\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 0)\n            self.assertEqual(brushes[1].color().alpha(), 0)\n            self.assertEqual(brushes[4].color().alpha(), 0)\n            self.assertEqual(brushes[5].color().alpha(), 255)\n            self.assertEqual(brushes[6].color().alpha(), 255)\n            self.assertEqual(brushes[7].color().alpha(), 255)\n\n        graph = self.graph\n\n        self.master.get_color_data = lambda: None\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n        d = np.arange(10, dtype=float) % 2\n        d[4:6] = np.nan\n        self.master.get_color_data = lambda: d\n\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n    def test_colors_none(self):\n        graph = self.graph\n        graph.reset_graph()\n        hue = QColor(128, 128, 128).hue()\n\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)  # test QPen/QBrush reuse\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 1)\n\n        self.master.get_subset_mask = lambda: np.arange(10) < 5\n        graph.update_colors()\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)  # transparent and colored\n\n    def test_colors_update_legend_and_density(self):\n        graph = self.graph\n        graph.update_legends = Mock()\n        graph.update_density = Mock()\n        graph.reset_graph()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n        graph.update_legends.reset_mock()\n        graph.update_density.reset_mock()\n\n        graph.update_coordinates()\n        graph.update_legends.assert_not_called()\n\n        graph.update_colors()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n    def test_selection_colors(self):\n        graph = self.graph\n        graph.reset_graph()\n        data = graph.scatterplot_item_sel.data\n\n        # One group\n        graph.select_by_indices(np.array([0, 1, 2, 3]))\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(4):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(4, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n\n        # Two groups\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_indices(np.array([4, 5, 6]))\n\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(7):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(7, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n        self.assertEqual(len({pen.color().hue() for pen in pens[:4]}), 1)\n        self.assertEqual(len({pen.color().hue() for pen in pens[4:7]}), 1)\n        color1 = pens[3].color().hue()\n        color2 = pens[4].color().hue()\n        self.assertNotEqual(color1, color2)\n\n        # Two groups + sampling\n        graph.set_sample_size(7)\n        x = graph.scatterplot_item.getData()[0]\n        pens = graph.scatterplot_item_sel.data[\"pen\"]\n        for xi, pen in zip(x, pens):\n            if xi < 4:\n                self.assertEqual(pen.color().hue(), color1)\n            elif xi < 7:\n                self.assertEqual(pen.color().hue(), color2)\n            else:\n                self.assertEqual(pen.style(), Qt.NoPen)\n\n    def test_density(self):\n        graph = self.graph\n        density = object()\n        with patch(\"Orange.widgets.utils.classdensity.class_density_image\",\n                   return_value=density):\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n\n            graph.plot_widget.addItem = Mock()\n            graph.plot_widget.removeItem = Mock()\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.ones((10, ), dtype=float)\n            self.master.get_color_data = lambda: d\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.arange(10) % 2\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.class_density = False\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.update_coordinates = lambda: (None, None)\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n    def test_labels(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n\n        # Label only selected\n        selected = [1, 3, 5]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(x) for x in selected])\n        x, y = graph.scatterplot_item.getData()\n        for i, index in enumerate(selected):\n            self.assertEqual(x[index], graph.labels[i].x())\n            self.assertEqual(y[index], graph.labels[i].y())\n\n        # Disable label only selected\n        self.graph.label_only_selected = False\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        # Label only selected + sampling\n        selected = [1, 3, 4, 5, 6, 7, 9]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        graph.set_sample_size(5)\n        for label in graph.labels:\n            ind = int(label.textItem.toPlainText())\n            self.assertIn(ind, selected)\n            self.assertEqual(label.x(), x[ind])\n            self.assertEqual(label.y(), y[ind])\n\n    def test_label_mask_all_visible(self):\n        graph = self.graph\n\n        x, y = np.arange(10) / 10, np.arange(10) / 10\n        sel = np.array(\n            [True, True, False, False, False, True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False, True, True, False, False, False])\n        trues = np.ones(10, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel)\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), np.array(\n            [True, True, True, True, False, True, True, True, False, False]\n        ))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset)\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5, 10) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, False, True])\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        trues = np.ones(5, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel[5:])\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([True, True, True, False, True]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset[5:])\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible_and_view(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])  # first and last out of the view\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, True, True])  # first and last out of the view\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        graph.view_box.viewRange = lambda: ((0.6, 1), (0, 0.3))\n        viewed = np.array([False, True, True, True, False])\n\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, False, False]))\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, True, False]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, False, True, False]))\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_labels_observes_mask(self):\n        graph = self.graph\n        get_label_data = graph.master.get_label_data\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        get_label_data.reset_mock()\n        graph._label_mask = lambda *_: None\n        graph.update_labels()\n        get_label_data.assert_not_called()\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph._label_mask = \\\n            lambda *_: np.array([False, True, True] + [False] * 7)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [\"1\", \"2\"])\n\n    def test_labels_update_coordinates(self):\n        graph = self.graph\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n\n        graph.reset_graph()\n        graph.set_sample_size(7)\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        self.master.get_coordinates_data = \\\n            lambda: (np.arange(10, 20), np.arange(50, 60))\n        graph.update_coordinates()\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n    def test_shapes(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 3]\n                            for i, symbol in enumerate(symbols)))\n\n        d = np.arange(10, dtype=float) % 2\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 2]\n                            for i, symbol in enumerate(symbols)))\n\n        d = None\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertEqual(len(set(symbols)), 1)\n\n    def test_shapes_nan(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n\n        graph.reset_graph()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2], '?')\n\n        d[:] = np.nan\n        graph.update_shapes()\n        self.assertTrue(\n            all(symbol == '?'\n                for symbol in graph.scatterplot_item.data[\"symbol\"]))\n\n        def impute0(data, _):\n            data[np.isnan(data)] = 0\n\n        self.master.impute_shapes = impute0\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n        graph.update_shapes()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2],\n                         graph.CurveSymbols[0])\n\n    def test_show_grid(self):\n        graph = self.graph\n        show_grid = self.graph.plot_widget.showGrid = Mock()\n        graph.show_grid = False\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=False, y=False))\n\n        graph.show_grid = True\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=True, y=True))\n\n    def test_show_legend(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        shape_labels = color_labels = None  # Avoid pylint warning\n        self.master.get_shape_labels = lambda: shape_labels\n        self.master.get_color_labels = lambda: color_labels\n        for shape_labels in (None, [\"a\", \"b\"]):\n            for color_labels in (None, [\"c\", \"d\"], None):\n                for visible in (True, False, True):\n                    graph.show_legend = visible\n                    graph.update_legends()\n                    self.assertIs(\n                        shape_legend.call_args[0][0],\n                        visible and bool(shape_labels),\n                        msg=\"error at {}, {}\".format(visible, shape_labels))\n                    self.assertIs(\n                        color_legend.call_args[0][0],\n                        visible and bool(color_labels),\n                        msg=\"error at {}, {}\".format(visible, color_labels))\n\n    def test_show_legend_no_data(self):\n        graph = self.graph\n        self.master.get_shape_labels = lambda: [\"a\", \"b\"]\n        self.master.get_color_labels = lambda: [\"c\", \"d\"]\n        self.master.get_shape_data = lambda: np.arange(10) % 2\n        self.master.get_color_data = lambda: np.arange(10) < 6\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        self.master.get_coordinates_data = lambda: (None, None)\n        graph.reset_graph()\n        self.assertFalse(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n\n    def test_legend_combine(self):\n        master = self.master\n        graph = self.graph\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n\n        master.get_shape_labels = lambda: [\"a\", \"b\"]\n        master.get_color_labels = lambda: [\"c\", \"d\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n\n        master.get_color_labels = lambda: [\"a\", \"b\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.is_continuous_color = lambda: True\n        master.get_color_data = lambda: np.arange(10, dtype=float)\n        master.get_color_labels = lambda: None\n        graph.update_colors()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n    def test_select_by_click(self):\n        graph = self.graph\n        graph.reset_graph()\n        points = graph.scatterplot_item.points()\n        graph.select_by_click(None, [points[2]])\n        np.testing.assert_almost_equal(graph.get_selection(), [2])\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_click(None, points[3:6])\n        np.testing.assert_almost_equal(\n            list(graph.get_selection()), [2, 3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 1, 2, 2, 2, 0, 0, 0, 0])\n\n    def test_select_by_rectangle(self):\n        graph = self.graph\n        coords = np.array(\n            [(x, y) for y in range(10) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n\n        graph.reset_graph()\n        graph.select_by_rectangle(QRectF(3, 5, 3.9, 2.9))\n        self.assertTrue(\n            all(selected == (3 <= coords[0][i] <= 6 and 5 <= coords[1][i] <= 7)\n                for i, selected in enumerate(graph.selection)))\n\n    def test_select_by_indices(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        def select(modifiers, indices):\n            with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                       lambda: modifiers):\n                graph.update_selection_colors = Mock()\n                graph.update_labels = Mock()\n                self.master.selection_changed = Mock()\n\n                graph.select_by_indices(np.array(indices))\n                graph.update_selection_colors.assert_called_with()\n                if graph.label_only_selected:\n                    graph.update_labels.assert_called_with()\n                else:\n                    graph.update_labels.assert_not_called()\n                self.master.selection_changed.assert_called_with()\n\n        select(0, [7, 8, 9])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 0, 0, 1, 1, 1])\n\n        select(Qt.ShiftModifier | Qt.ControlModifier, [5, 6])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 1, 1, 1, 1, 1])\n\n        select(Qt.ShiftModifier, [3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 2, 2, 2, 1, 1, 1, 1])\n\n        select(Qt.AltModifier, [1, 3, 7])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 2, 2, 1, 0, 1, 1])\n\n        select(0, [1, 8])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 1, 0, 0, 0, 0, 0, 0, 1, 0])\n\n        graph.label_only_selected = False\n        select(0, [3, 4])\n\n    def test_unselect_all(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        graph.select_by_indices([3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 1, 1, 1, 0, 0, 0, 0])\n\n        graph.update_selection_colors = Mock()\n        graph.update_labels = Mock()\n        self.master.selection_changed = Mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_called_with()\n        graph.update_labels.assert_called_with()\n        self.master.selection_changed.assert_called_with()\n\n        graph.update_selection_colors.reset_mock()\n        graph.update_labels.reset_mock()\n        self.master.selection_changed.reset_mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_not_called()\n        graph.update_labels.assert_not_called()\n        self.master.selection_changed.assert_not_called()\n\n    def test_hiding_too_many_labels(self):\n        spy = QSignalSpy(self.graph.too_many_labels)\n        self.graph.MAX_VISIBLE_LABELS = 5\n\n        graph = self.graph\n        coords = np.array(\n            [(x, 0) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n        graph.reset_graph()\n\n        self.assertFalse(spy and spy[-1][0])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 4, 4))\n        graph.view_box.sigRangeChangedManually.emit(((1, 5), (-1, 3)))\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 8, 8))\n        graph.view_box.sigRangeChangedManually.emit(((1, 9), (-1, 7)))\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.label_only_selected = True\n        graph.update_labels()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3, 4, 5, 6])\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3])\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.label_only_selected = False\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.clear()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n    def test_no_needless_buildatlas(self):\n        graph = self.graph\n        graph.reset_graph()\n        self.assertIsNone(graph.scatterplot_item.fragmentAtlas.atlas)\n\n\nif __name__ == \"__main__\":\n    import unittest\n    unittest.main()\n",
            "new_file_content": "# pylint: disable=missing-docstring,too-many-lines,too-many-public-methods\n# pylint: disable=protected-access\nfrom unittest.mock import patch, Mock\nimport numpy as np\n\nfrom AnyQt.QtCore import QRectF, Qt\nfrom AnyQt.QtGui import QColor\nfrom AnyQt.QtTest import QSignalSpy\n\nfrom pyqtgraph import mkPen\n\nfrom Orange.widgets.settings import SettingProvider\nfrom Orange.widgets.tests.base import WidgetTest\nfrom Orange.widgets.utils.colorpalette import ColorPaletteGenerator, \\\n    ContinuousPaletteGenerator, NAN_GREY\nfrom Orange.widgets.visualize.owscatterplotgraph import OWScatterPlotBase, \\\n    ScatterPlotItem, SELECTION_WIDTH\nfrom Orange.widgets.widget import OWWidget\n\n\nclass MockWidget(OWWidget):\n    name = \"Mock\"\n\n    get_coordinates_data = Mock(return_value=(None, None))\n    get_size_data = Mock(return_value=None)\n    get_shape_data = Mock(return_value=None)\n    get_color_data = Mock(return_value=None)\n    get_label_data = Mock(return_value=None)\n    get_color_labels = Mock(return_value=None)\n    get_shape_labels = Mock(return_value=None)\n    get_subset_mask = Mock(return_value=None)\n    get_tooltip = Mock(return_value=\"\")\n\n    is_continuous_color = Mock(return_value=False)\n    can_draw_density = Mock(return_value=True)\n    combined_legend = Mock(return_value=False)\n    selection_changed = Mock(return_value=None)\n\n    GRAPH_CLASS = OWScatterPlotBase\n    graph = SettingProvider(OWScatterPlotBase)\n\n    def get_palette(self):\n        if self.is_continuous_color():\n            return ContinuousPaletteGenerator(Qt.white, Qt.black, False)\n        else:\n            return ColorPaletteGenerator(12)\n\n\nclass TestOWScatterPlotBase(WidgetTest):\n    def setUp(self):\n        self.master = MockWidget()\n        self.graph = OWScatterPlotBase(self.master)\n\n        self.xy = (np.arange(10, dtype=float), np.arange(10, dtype=float))\n        self.master.get_coordinates_data = lambda: self.xy\n\n    # pylint: disable=keyword-arg-before-vararg\n    def setRange(self, rect=None, *_, **__):\n        if isinstance(rect, QRectF):\n            self.last_setRange = [[rect.left(), rect.right()],\n                                  [rect.top(), rect.bottom()]]\n\n    def test_update_coordinates_no_data(self):\n        self.xy = None, None\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n        self.xy = [], []\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        graph.reset_graph()\n\n        scatterplot_item = graph.scatterplot_item\n        scatterplot_item_sel = graph.scatterplot_item_sel\n        data = scatterplot_item.data\n\n        np.testing.assert_almost_equal(scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(scatterplot_item_sel.getData(), xy)\n        scatterplot_item.setSize([5, 6])\n        scatterplot_item.setSymbol([7, 8])\n        scatterplot_item.setPen([mkPen(9), mkPen(10)])\n        scatterplot_item.setBrush([11, 12])\n        data[\"data\"] = np.array([13, 14])\n\n        xy[0][0] = 0\n        graph.update_coordinates()\n        np.testing.assert_almost_equal(graph.scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(graph.scatterplot_item_sel.getData(), xy)\n\n        # Graph updates coordinates instead of creating new items\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        self.assertIs(scatterplot_item_sel, graph.scatterplot_item_sel)\n        np.testing.assert_almost_equal(data[\"size\"], [5, 6])\n        np.testing.assert_almost_equal(data[\"symbol\"], [7, 8])\n        self.assertEqual(data[\"pen\"][0], mkPen(9))\n        self.assertEqual(data[\"pen\"][1], mkPen(10))\n        np.testing.assert_almost_equal(data[\"brush\"], [11, 12])\n        np.testing.assert_almost_equal(data[\"data\"], [13, 14])\n\n    def test_update_coordinates_and_labels(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1., 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 1.5\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 1.5)\n        xy[0][0] = 0  # This label goes out of the range\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 2)\n\n    def test_update_coordinates_and_density(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 0\n        graph.update_density = Mock()\n        graph.update_coordinates()\n        graph.update_density.assert_called_with()\n\n    def test_update_coordinates_reset_view(self):\n        graph = self.graph\n        graph.view_box.setRange = self.setRange\n        xy = self.xy = (np.array([2, 1]), np.array([3, 10]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(self.last_setRange, [[1, 2], [3, 10]])\n\n        xy[0][1] = 0\n        graph.update_coordinates()\n        self.assertEqual(self.last_setRange, [[0, 2], [3, 10]])\n\n    def test_reset_graph_no_data(self):\n        self.xy = (None, None)\n        self.graph.scatterplot_item = ScatterPlotItem([1, 2], [3, 4])\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates_indices(self):\n        graph = self.graph\n        self.xy = (np.array([2, 1]), np.array([3, 10]))\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item.data[\"data\"], [0, 1])\n\n    def test_sampling(self):\n        graph = self.graph\n        master = self.master\n\n        # Enable sampling before getting the data\n        graph.set_sample_size(3)\n        xy = self.xy = (np.arange(10, dtype=float),\n                        np.arange(0, 30, 3, dtype=float))\n        d = np.arange(10, dtype=float)\n        master.get_size_data = lambda: d\n        master.get_shape_data = lambda: d % 5 if d is not None else None\n        master.get_color_data = lambda: d\n        master.get_label_data = lambda: \\\n            np.array([str(x) for x in d], dtype=object)\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n        # Check proper sampling\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertNotEqual(x[0], x[1])\n        self.assertNotEqual(x[0], x[2])\n        self.assertNotEqual(x[1], x[2])\n        np.testing.assert_almost_equal(3 * x, y)\n\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Check that sample is extended when sample size is changed\n        graph.set_sample_size(4)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s = data[\"size\"] - graph.MinShapeSize\n        precise_s = (x - min(x)) / (max(x) - min(x)) * max(s)\n        np.testing.assert_almost_equal(s, precise_s, decimal=0)\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Disable sampling\n        graph.set_sample_size(None)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        np.testing.assert_almost_equal(x, xy[0])\n        np.testing.assert_almost_equal(y, xy[1])\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in d])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in d])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in d])\n\n        # Enable sampling when data is already present and not sampled\n        graph.set_sample_size(3)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Update data when data is present and sampling is enabled\n        xy[0][:] = np.arange(9, -1, -1, dtype=float)\n        d = xy[0]\n        graph.update_coordinates()\n        x1, _ = scatterplot_item.getData()\n        np.testing.assert_almost_equal(9 - x, x1)\n        graph.update_sizes()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Reset graph when data is present and sampling is enabled\n        self.xy = (np.arange(100, 105, dtype=float),\n                   np.arange(100, 105, dtype=float))\n        d = self.xy[0] - 100\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertTrue(np.all(x > 99))\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Don't sample when unnecessary\n        self.xy = (np.arange(100, dtype=float), ) * 2\n        d = None\n        delattr(master, \"get_label_data\")\n        graph.reset_graph()\n        graph.set_sample_size(120)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_almost_equal(x, np.arange(100))\n\n    def test_sampling_keeps_selection(self):\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n        graph.reset_graph()\n        graph.select_by_indices(np.arange(1, 100, 2))\n        graph.set_sample_size(30)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n        graph.set_sample_size(None)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n\n    base = \"Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase.\"\n\n    @patch(base + \"update_sizes\")\n    @patch(base + \"update_colors\")\n    @patch(base + \"update_selection_colors\")\n    @patch(base + \"update_shapes\")\n    @patch(base + \"update_labels\")\n    def test_reset_calls_all_updates_and_update_doesnt(self, *mocks):\n        master = MockWidget()\n        graph = OWScatterPlotBase(master)\n        for mock in mocks:\n            mock.assert_not_called()\n\n        graph.reset_graph()\n        for mock in mocks:\n            mock.assert_called_with()\n            mock.reset_mock()\n\n        graph.update_coordinates()\n        for mock in mocks:\n            mock.assert_not_called()\n\n    def test_jittering(self):\n        graph = self.graph\n        graph.jitter_size = 10\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        a10 = np.arange(10)\n        self.assertTrue(np.any(np.nonzero(a10 - x)))\n        self.assertTrue(np.any(np.nonzero(a10 - y)))\n        np.testing.assert_array_less(a10 - x, 1)\n        np.testing.assert_array_less(a10 - y, 1)\n\n        graph.jitter_size = 0\n        graph.update_coordinates()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_equal(a10, x)\n\n    def test_size_normalization(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, [6, 7.5, 9.5, 11, 12.5, 14.5, 16, 17.5, 19.5, 21])\n\n        d = np.arange(10, 20, dtype=float)\n        graph.update_sizes()\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        size2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, size2)\n\n    def test_size_rounding_half_pixel(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size*2 - (size*2).round(), 0)\n\n    def test_size_with_nans(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n\n        d[4] = np.nan\n        graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        sizes2 = scatterplot_item.data[\"size\"]\n\n        self.assertEqual(sizes[1] - sizes[0], sizes2[1] - sizes2[0])\n        self.assertLess(sizes2[4], self.graph.MinShapeSize)\n\n        d[:] = np.nan\n        graph.update_sizes()\n        sizes3 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes3)\n\n    def test_sizes_all_same_or_nan(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.full((10, ), 3.0)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n        self.assertEqual(len(set(sizes)), 1)\n        self.assertGreater(sizes[0], self.graph.MinShapeSize)\n\n        d = None\n        graph.update_sizes()\n        scatterplot_item = graph.scatterplot_item\n        sizes2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes2)\n\n    def test_sizes_point_width_is_linear(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.point_width = 1\n        graph.reset_graph()\n        sizes1 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 2\n        graph.update_sizes()\n        sizes2 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 3\n        graph.update_sizes()\n        sizes3 = graph.scatterplot_item.data[\"size\"]\n\n        np.testing.assert_almost_equal(2 * (sizes2 - sizes1), sizes3 - sizes1)\n\n    def test_sizes_custom_imputation(self):\n\n        def impute_max(size_data):\n            size_data[np.isnan(size_data)] = np.nanmax(size_data)\n\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        self.master.impute_sizes = impute_max\n        d = np.arange(10, dtype=float)\n        d[4] = np.nan\n        graph.reset_graph()\n        sizes = graph.scatterplot_item.data[\"size\"]\n        self.assertAlmostEqual(sizes[4], sizes[9])\n\n    def test_sizes_selection(self):\n        graph = self.graph\n        graph.get_size = lambda: np.arange(10, dtype=float)\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item_sel.data[\"size\"]\n            - graph.scatterplot_item.data[\"size\"],\n            SELECTION_WIDTH)\n\n    @patch(\"Orange.widgets.visualize.owscatterplotgraph\"\n           \".MAX_N_VALID_SIZE_ANIMATE\", 5)\n    def test_size_animation(self):\n        begin_resizing = QSignalSpy(self.graph.begin_resizing)\n        step_resizing = QSignalSpy(self.graph.step_resizing)\n        end_resizing = QSignalSpy(self.graph.end_resizing)\n        self._update_sizes_for_points(5)\n        # first end_resizing is triggered in reset, thus wait for step_resizing\n        step_resizing.wait(200)\n        end_resizing.wait(200)\n        self.assertEqual(len(begin_resizing), 2)  # reset and update\n        self.assertEqual(len(step_resizing), 5)\n        self.assertEqual(len(end_resizing), 2)  # reset and update\n        self.assertEqual(self.graph.scatterplot_item.setSize.call_count, 6)\n        self._update_sizes_for_points(6)\n        self.graph.scatterplot_item.setSize.assert_called_once()\n\n    def _update_sizes_for_points(self, n: int):\n        arr = np.arange(n, dtype=float)\n        self.master.get_coordinates_data = lambda: (arr, arr)\n        self.master.get_size_data = lambda: arr\n        self.graph.reset_graph()\n        self.graph.scatterplot_item.setSize = Mock(\n            wraps=self.graph.scatterplot_item.setSize)\n        self.master.get_size_data = lambda: arr[::-1]\n        self.graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n    def test_colors_discrete(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        self.master.get_color_data = lambda: d\n        d = np.arange(10, dtype=float) % 2\n\n        graph.reset_graph()\n        data = graph.scatterplot_item.data\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"pen\"])))\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"brush\"])))\n\n        # confirm that QPen/QBrush were reused\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 2)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)\n\n    def test_colors_discrete_nan(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        self.assertEqual(pens[0].color().hue(), palette[0].hue())\n        self.assertEqual(pens[1].color().hue(), palette[1].hue())\n        self.assertEqual(brushes[0].color().hue(), palette[0].hue())\n        self.assertEqual(brushes[1].color().hue(), palette[1].hue())\n        self.assertEqual(pens[4].color().hue(), QColor(128, 128, 128).hue())\n        self.assertEqual(brushes[4].color().hue(), QColor(128, 128, 128).hue())\n\n    def test_colors_continuous(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()  # I don't have a good test ... just don't crash\n\n        d[4] = np.nan\n        graph.update_colors()  # Ditto\n\n    def test_colors_continuous_reused(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n\n        d = np.arange(100, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n\n        data = graph.scatterplot_item.data\n\n        self.assertEqual(len(data[\"pen\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"pen\"]))), 10)\n        self.assertEqual(len(data[\"brush\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"brush\"]))), 10)\n\n    def test_colors_continuous_nan(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        nan_color = QColor(*NAN_GREY)\n        self.assertEqual(pens[4].color().hue(), nan_color.hue())\n        self.assertEqual(brushes[4].color().hue(), nan_color.hue())\n\n    def test_colors_subset(self):\n        def run_tests():\n            self.master.get_subset_mask = lambda: None\n\n            graph.alpha_value = 42\n            graph.reset_graph()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 42)\n            self.assertEqual(brushes[1].color().alpha(), 42)\n            self.assertEqual(brushes[4].color().alpha(), 42)\n\n            graph.alpha_value = 123\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 123)\n            self.assertEqual(brushes[1].color().alpha(), 123)\n            self.assertEqual(brushes[4].color().alpha(), 123)\n\n            self.master.get_subset_mask = lambda: np.arange(10) >= 5\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 0)\n            self.assertEqual(brushes[1].color().alpha(), 0)\n            self.assertEqual(brushes[4].color().alpha(), 0)\n            self.assertEqual(brushes[5].color().alpha(), 255)\n            self.assertEqual(brushes[6].color().alpha(), 255)\n            self.assertEqual(brushes[7].color().alpha(), 255)\n\n        graph = self.graph\n\n        self.master.get_color_data = lambda: None\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n        d = np.arange(10, dtype=float) % 2\n        d[4:6] = np.nan\n        self.master.get_color_data = lambda: d\n\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n    def test_colors_none(self):\n        graph = self.graph\n        graph.reset_graph()\n        hue = QColor(128, 128, 128).hue()\n\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)  # test QPen/QBrush reuse\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 1)\n\n        self.master.get_subset_mask = lambda: np.arange(10) < 5\n        graph.update_colors()\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)  # transparent and colored\n\n    def test_colors_update_legend_and_density(self):\n        graph = self.graph\n        graph.update_legends = Mock()\n        graph.update_density = Mock()\n        graph.reset_graph()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n        graph.update_legends.reset_mock()\n        graph.update_density.reset_mock()\n\n        graph.update_coordinates()\n        graph.update_legends.assert_not_called()\n\n        graph.update_colors()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n    def test_selection_colors(self):\n        graph = self.graph\n        graph.reset_graph()\n        data = graph.scatterplot_item_sel.data\n\n        # One group\n        graph.select_by_indices(np.array([0, 1, 2, 3]))\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(4):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(4, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n\n        # Two groups\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_indices(np.array([4, 5, 6]))\n\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(7):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(7, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n        self.assertEqual(len({pen.color().hue() for pen in pens[:4]}), 1)\n        self.assertEqual(len({pen.color().hue() for pen in pens[4:7]}), 1)\n        color1 = pens[3].color().hue()\n        color2 = pens[4].color().hue()\n        self.assertNotEqual(color1, color2)\n\n        # Two groups + sampling\n        graph.set_sample_size(7)\n        x = graph.scatterplot_item.getData()[0]\n        pens = graph.scatterplot_item_sel.data[\"pen\"]\n        for xi, pen in zip(x, pens):\n            if xi < 4:\n                self.assertEqual(pen.color().hue(), color1)\n            elif xi < 7:\n                self.assertEqual(pen.color().hue(), color2)\n            else:\n                self.assertEqual(pen.style(), Qt.NoPen)\n\n    def test_density(self):\n        graph = self.graph\n        density = object()\n        with patch(\"Orange.widgets.utils.classdensity.class_density_image\",\n                   return_value=density):\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n\n            graph.plot_widget.addItem = Mock()\n            graph.plot_widget.removeItem = Mock()\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.ones((10, ), dtype=float)\n            self.master.get_color_data = lambda: d\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.arange(10) % 2\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.class_density = False\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.update_coordinates = lambda: (None, None)\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n    def test_labels(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n\n        # Label only selected\n        selected = [1, 3, 5]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(x) for x in selected])\n        x, y = graph.scatterplot_item.getData()\n        for i, index in enumerate(selected):\n            self.assertEqual(x[index], graph.labels[i].x())\n            self.assertEqual(y[index], graph.labels[i].y())\n\n        # Disable label only selected\n        self.graph.label_only_selected = False\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        # Label only selected + sampling\n        selected = [1, 3, 4, 5, 6, 7, 9]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        graph.set_sample_size(5)\n        for label in graph.labels:\n            ind = int(label.textItem.toPlainText())\n            self.assertIn(ind, selected)\n            self.assertEqual(label.x(), x[ind])\n            self.assertEqual(label.y(), y[ind])\n\n    def test_label_mask_all_visible(self):\n        graph = self.graph\n\n        x, y = np.arange(10) / 10, np.arange(10) / 10\n        sel = np.array(\n            [True, True, False, False, False, True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False, True, True, False, False, False])\n        trues = np.ones(10, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel)\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), np.array(\n            [True, True, True, True, False, True, True, True, False, False]\n        ))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset)\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5, 10) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, False, True])\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        trues = np.ones(5, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel[5:])\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([True, True, True, False, True]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset[5:])\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible_and_view(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])  # first and last out of the view\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, True, True])  # first and last out of the view\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        graph.view_box.viewRange = lambda: ((0.6, 1), (0, 0.3))\n        viewed = np.array([False, True, True, True, False])\n\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, False, False]))\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, True, False]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, False, True, False]))\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_labels_observes_mask(self):\n        graph = self.graph\n        get_label_data = graph.master.get_label_data\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        get_label_data.reset_mock()\n        graph._label_mask = lambda *_: None\n        graph.update_labels()\n        get_label_data.assert_not_called()\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph._label_mask = \\\n            lambda *_: np.array([False, True, True] + [False] * 7)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [\"1\", \"2\"])\n\n    def test_labels_update_coordinates(self):\n        graph = self.graph\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n\n        graph.reset_graph()\n        graph.set_sample_size(7)\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        self.master.get_coordinates_data = \\\n            lambda: (np.arange(10, 20), np.arange(50, 60))\n        graph.update_coordinates()\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n    def test_shapes(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 3]\n                            for i, symbol in enumerate(symbols)))\n\n        d = np.arange(10, dtype=float) % 2\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 2]\n                            for i, symbol in enumerate(symbols)))\n\n        d = None\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertEqual(len(set(symbols)), 1)\n\n    def test_shapes_nan(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n\n        graph.reset_graph()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2], '?')\n\n        d[:] = np.nan\n        graph.update_shapes()\n        self.assertTrue(\n            all(symbol == '?'\n                for symbol in graph.scatterplot_item.data[\"symbol\"]))\n\n        def impute0(data, _):\n            data[np.isnan(data)] = 0\n\n        self.master.impute_shapes = impute0\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n        graph.update_shapes()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2],\n                         graph.CurveSymbols[0])\n\n    def test_show_grid(self):\n        graph = self.graph\n        show_grid = self.graph.plot_widget.showGrid = Mock()\n        graph.show_grid = False\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=False, y=False))\n\n        graph.show_grid = True\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=True, y=True))\n\n    def test_show_legend(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        shape_labels = color_labels = None  # Avoid pylint warning\n        self.master.get_shape_labels = lambda: shape_labels\n        self.master.get_color_labels = lambda: color_labels\n        for shape_labels in (None, [\"a\", \"b\"]):\n            for color_labels in (None, [\"c\", \"d\"], None):\n                for visible in (True, False, True):\n                    graph.show_legend = visible\n                    graph.update_legends()\n                    self.assertIs(\n                        shape_legend.call_args[0][0],\n                        visible and bool(shape_labels),\n                        msg=\"error at {}, {}\".format(visible, shape_labels))\n                    self.assertIs(\n                        color_legend.call_args[0][0],\n                        visible and bool(color_labels),\n                        msg=\"error at {}, {}\".format(visible, color_labels))\n\n    def test_show_legend_no_data(self):\n        graph = self.graph\n        self.master.get_shape_labels = lambda: [\"a\", \"b\"]\n        self.master.get_color_labels = lambda: [\"c\", \"d\"]\n        self.master.get_shape_data = lambda: np.arange(10) % 2\n        self.master.get_color_data = lambda: np.arange(10) < 6\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        self.master.get_coordinates_data = lambda: (None, None)\n        graph.reset_graph()\n        self.assertFalse(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n\n    def test_legend_combine(self):\n        master = self.master\n        graph = self.graph\n\n        master.get_shape_data = lambda: np.arange(10, dtype=float) % 3\n        master.get_color_data = lambda: 2 * np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n\n        master.get_shape_labels = lambda: [\"a\", \"b\"]\n        master.get_color_labels = lambda: [\"c\", \"d\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n\n        master.get_color_labels = lambda: [\"a\", \"b\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.get_color_data = lambda: np.arange(10, dtype=float) % 3\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.is_continuous_color = lambda: True\n        master.get_color_data = lambda: np.arange(10, dtype=float)\n        master.get_color_labels = lambda: None\n        graph.update_colors()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n    def test_select_by_click(self):\n        graph = self.graph\n        graph.reset_graph()\n        points = graph.scatterplot_item.points()\n        graph.select_by_click(None, [points[2]])\n        np.testing.assert_almost_equal(graph.get_selection(), [2])\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_click(None, points[3:6])\n        np.testing.assert_almost_equal(\n            list(graph.get_selection()), [2, 3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 1, 2, 2, 2, 0, 0, 0, 0])\n\n    def test_select_by_rectangle(self):\n        graph = self.graph\n        coords = np.array(\n            [(x, y) for y in range(10) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n\n        graph.reset_graph()\n        graph.select_by_rectangle(QRectF(3, 5, 3.9, 2.9))\n        self.assertTrue(\n            all(selected == (3 <= coords[0][i] <= 6 and 5 <= coords[1][i] <= 7)\n                for i, selected in enumerate(graph.selection)))\n\n    def test_select_by_indices(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        def select(modifiers, indices):\n            with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                       lambda: modifiers):\n                graph.update_selection_colors = Mock()\n                graph.update_labels = Mock()\n                self.master.selection_changed = Mock()\n\n                graph.select_by_indices(np.array(indices))\n                graph.update_selection_colors.assert_called_with()\n                if graph.label_only_selected:\n                    graph.update_labels.assert_called_with()\n                else:\n                    graph.update_labels.assert_not_called()\n                self.master.selection_changed.assert_called_with()\n\n        select(0, [7, 8, 9])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 0, 0, 1, 1, 1])\n\n        select(Qt.ShiftModifier | Qt.ControlModifier, [5, 6])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 1, 1, 1, 1, 1])\n\n        select(Qt.ShiftModifier, [3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 2, 2, 2, 1, 1, 1, 1])\n\n        select(Qt.AltModifier, [1, 3, 7])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 2, 2, 1, 0, 1, 1])\n\n        select(0, [1, 8])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 1, 0, 0, 0, 0, 0, 0, 1, 0])\n\n        graph.label_only_selected = False\n        select(0, [3, 4])\n\n    def test_unselect_all(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        graph.select_by_indices([3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 1, 1, 1, 0, 0, 0, 0])\n\n        graph.update_selection_colors = Mock()\n        graph.update_labels = Mock()\n        self.master.selection_changed = Mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_called_with()\n        graph.update_labels.assert_called_with()\n        self.master.selection_changed.assert_called_with()\n\n        graph.update_selection_colors.reset_mock()\n        graph.update_labels.reset_mock()\n        self.master.selection_changed.reset_mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_not_called()\n        graph.update_labels.assert_not_called()\n        self.master.selection_changed.assert_not_called()\n\n    def test_hiding_too_many_labels(self):\n        spy = QSignalSpy(self.graph.too_many_labels)\n        self.graph.MAX_VISIBLE_LABELS = 5\n\n        graph = self.graph\n        coords = np.array(\n            [(x, 0) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n        graph.reset_graph()\n\n        self.assertFalse(spy and spy[-1][0])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 4, 4))\n        graph.view_box.sigRangeChangedManually.emit(((1, 5), (-1, 3)))\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 8, 8))\n        graph.view_box.sigRangeChangedManually.emit(((1, 9), (-1, 7)))\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.label_only_selected = True\n        graph.update_labels()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3, 4, 5, 6])\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3])\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.label_only_selected = False\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.clear()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n    def test_no_needless_buildatlas(self):\n        graph = self.graph\n        graph.reset_graph()\n        self.assertIsNone(graph.scatterplot_item.fragmentAtlas.atlas)\n\n\nif __name__ == \"__main__\":\n    import unittest\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "Orange/widgets/visualize/tests/test_owscatterplotbase.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "ed1b780a8",
                "new_commit_hash": "080f83a71",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/widgets/visualize/tests/test_owscatterplotbase.py"
            },
            "plus_file": {
                "path": "b/Orange/widgets/visualize/tests/test_owscatterplotbase.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1105,
                            "length": 6
                        },
                        "new_range": {
                            "start": 1105,
                            "length": 10
                        },
                        "section": "class TestOWScatterPlotBase(WidgetTest):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    def test_legend_combine(self):",
                                "type": "context"
                            },
                            {
                                "content": "        master = self.master",
                                "type": "context"
                            },
                            {
                                "content": "        graph = self.graph",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        master.get_shape_data = lambda: np.arange(10, dtype=float) % 3",
                                "type": "added"
                            },
                            {
                                "content": "        master.get_color_data = lambda: 2 * np.arange(10, dtype=float) % 3",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        graph.reset_graph()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        shape_legend = self.graph.shape_legend.setVisible = Mock()",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/visualize/tests/test_owscatterplotbase.py",
                            "type": "method",
                            "name": "TestOWScatterPlotBase.test_legend_combine",
                            "content": "class TestOWScatterPlotBase(WidgetTest):\n    def setUp(self):\n        self.master = MockWidget()\n        self.graph = OWScatterPlotBase(self.master)\n\n        self.xy = (np.arange(10, dtype=float), np.arange(10, dtype=float))\n        self.master.get_coordinates_data = lambda: self.xy\n\n    # pylint: disable=keyword-arg-before-vararg\n    def setRange(self, rect=None, *_, **__):\n        if isinstance(rect, QRectF):\n            self.last_setRange = [[rect.left(), rect.right()],\n                                  [rect.top(), rect.bottom()]]\n\n    def test_update_coordinates_no_data(self):\n        self.xy = None, None\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n        self.xy = [], []\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        graph.reset_graph()\n\n        scatterplot_item = graph.scatterplot_item\n        scatterplot_item_sel = graph.scatterplot_item_sel\n        data = scatterplot_item.data\n\n        np.testing.assert_almost_equal(scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(scatterplot_item_sel.getData(), xy)\n        scatterplot_item.setSize([5, 6])\n        scatterplot_item.setSymbol([7, 8])\n        scatterplot_item.setPen([mkPen(9), mkPen(10)])\n        scatterplot_item.setBrush([11, 12])\n        data[\"data\"] = np.array([13, 14])\n\n        xy[0][0] = 0\n        graph.update_coordinates()\n        np.testing.assert_almost_equal(graph.scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(graph.scatterplot_item_sel.getData(), xy)\n\n        # Graph updates coordinates instead of creating new items\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        self.assertIs(scatterplot_item_sel, graph.scatterplot_item_sel)\n        np.testing.assert_almost_equal(data[\"size\"], [5, 6])\n        np.testing.assert_almost_equal(data[\"symbol\"], [7, 8])\n        self.assertEqual(data[\"pen\"][0], mkPen(9))\n        self.assertEqual(data[\"pen\"][1], mkPen(10))\n        np.testing.assert_almost_equal(data[\"brush\"], [11, 12])\n        np.testing.assert_almost_equal(data[\"data\"], [13, 14])\n\n    def test_update_coordinates_and_labels(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1., 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 1.5\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 1.5)\n        xy[0][0] = 0  # This label goes out of the range\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 2)\n\n    def test_update_coordinates_and_density(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 0\n        graph.update_density = Mock()\n        graph.update_coordinates()\n        graph.update_density.assert_called_with()\n\n    def test_update_coordinates_reset_view(self):\n        graph = self.graph\n        graph.view_box.setRange = self.setRange\n        xy = self.xy = (np.array([2, 1]), np.array([3, 10]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(self.last_setRange, [[1, 2], [3, 10]])\n\n        xy[0][1] = 0\n        graph.update_coordinates()\n        self.assertEqual(self.last_setRange, [[0, 2], [3, 10]])\n\n    def test_reset_graph_no_data(self):\n        self.xy = (None, None)\n        self.graph.scatterplot_item = ScatterPlotItem([1, 2], [3, 4])\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates_indices(self):\n        graph = self.graph\n        self.xy = (np.array([2, 1]), np.array([3, 10]))\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item.data[\"data\"], [0, 1])\n\n    def test_sampling(self):\n        graph = self.graph\n        master = self.master\n\n        # Enable sampling before getting the data\n        graph.set_sample_size(3)\n        xy = self.xy = (np.arange(10, dtype=float),\n                        np.arange(0, 30, 3, dtype=float))\n        d = np.arange(10, dtype=float)\n        master.get_size_data = lambda: d\n        master.get_shape_data = lambda: d % 5 if d is not None else None\n        master.get_color_data = lambda: d\n        master.get_label_data = lambda: \\\n            np.array([str(x) for x in d], dtype=object)\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n        # Check proper sampling\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertNotEqual(x[0], x[1])\n        self.assertNotEqual(x[0], x[2])\n        self.assertNotEqual(x[1], x[2])\n        np.testing.assert_almost_equal(3 * x, y)\n\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Check that sample is extended when sample size is changed\n        graph.set_sample_size(4)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s = data[\"size\"] - graph.MinShapeSize\n        precise_s = (x - min(x)) / (max(x) - min(x)) * max(s)\n        np.testing.assert_almost_equal(s, precise_s, decimal=0)\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Disable sampling\n        graph.set_sample_size(None)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        np.testing.assert_almost_equal(x, xy[0])\n        np.testing.assert_almost_equal(y, xy[1])\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in d])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in d])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in d])\n\n        # Enable sampling when data is already present and not sampled\n        graph.set_sample_size(3)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Update data when data is present and sampling is enabled\n        xy[0][:] = np.arange(9, -1, -1, dtype=float)\n        d = xy[0]\n        graph.update_coordinates()\n        x1, _ = scatterplot_item.getData()\n        np.testing.assert_almost_equal(9 - x, x1)\n        graph.update_sizes()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Reset graph when data is present and sampling is enabled\n        self.xy = (np.arange(100, 105, dtype=float),\n                   np.arange(100, 105, dtype=float))\n        d = self.xy[0] - 100\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertTrue(np.all(x > 99))\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Don't sample when unnecessary\n        self.xy = (np.arange(100, dtype=float), ) * 2\n        d = None\n        delattr(master, \"get_label_data\")\n        graph.reset_graph()\n        graph.set_sample_size(120)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_almost_equal(x, np.arange(100))\n\n    def test_sampling_keeps_selection(self):\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n        graph.reset_graph()\n        graph.select_by_indices(np.arange(1, 100, 2))\n        graph.set_sample_size(30)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n        graph.set_sample_size(None)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n\n    base = \"Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase.\"\n\n    @patch(base + \"update_sizes\")\n    @patch(base + \"update_colors\")\n    @patch(base + \"update_selection_colors\")\n    @patch(base + \"update_shapes\")\n    @patch(base + \"update_labels\")\n    def test_reset_calls_all_updates_and_update_doesnt(self, *mocks):\n        master = MockWidget()\n        graph = OWScatterPlotBase(master)\n        for mock in mocks:\n            mock.assert_not_called()\n\n        graph.reset_graph()\n        for mock in mocks:\n            mock.assert_called_with()\n            mock.reset_mock()\n\n        graph.update_coordinates()\n        for mock in mocks:\n            mock.assert_not_called()\n\n    def test_jittering(self):\n        graph = self.graph\n        graph.jitter_size = 10\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        a10 = np.arange(10)\n        self.assertTrue(np.any(np.nonzero(a10 - x)))\n        self.assertTrue(np.any(np.nonzero(a10 - y)))\n        np.testing.assert_array_less(a10 - x, 1)\n        np.testing.assert_array_less(a10 - y, 1)\n\n        graph.jitter_size = 0\n        graph.update_coordinates()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_equal(a10, x)\n\n    def test_size_normalization(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, [6, 7.5, 9.5, 11, 12.5, 14.5, 16, 17.5, 19.5, 21])\n\n        d = np.arange(10, 20, dtype=float)\n        graph.update_sizes()\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        size2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, size2)\n\n    def test_size_rounding_half_pixel(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size*2 - (size*2).round(), 0)\n\n    def test_size_with_nans(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n\n        d[4] = np.nan\n        graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        sizes2 = scatterplot_item.data[\"size\"]\n\n        self.assertEqual(sizes[1] - sizes[0], sizes2[1] - sizes2[0])\n        self.assertLess(sizes2[4], self.graph.MinShapeSize)\n\n        d[:] = np.nan\n        graph.update_sizes()\n        sizes3 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes3)\n\n    def test_sizes_all_same_or_nan(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.full((10, ), 3.0)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n        self.assertEqual(len(set(sizes)), 1)\n        self.assertGreater(sizes[0], self.graph.MinShapeSize)\n\n        d = None\n        graph.update_sizes()\n        scatterplot_item = graph.scatterplot_item\n        sizes2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes2)\n\n    def test_sizes_point_width_is_linear(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.point_width = 1\n        graph.reset_graph()\n        sizes1 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 2\n        graph.update_sizes()\n        sizes2 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 3\n        graph.update_sizes()\n        sizes3 = graph.scatterplot_item.data[\"size\"]\n\n        np.testing.assert_almost_equal(2 * (sizes2 - sizes1), sizes3 - sizes1)\n\n    def test_sizes_custom_imputation(self):\n\n        def impute_max(size_data):\n            size_data[np.isnan(size_data)] = np.nanmax(size_data)\n\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        self.master.impute_sizes = impute_max\n        d = np.arange(10, dtype=float)\n        d[4] = np.nan\n        graph.reset_graph()\n        sizes = graph.scatterplot_item.data[\"size\"]\n        self.assertAlmostEqual(sizes[4], sizes[9])\n\n    def test_sizes_selection(self):\n        graph = self.graph\n        graph.get_size = lambda: np.arange(10, dtype=float)\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item_sel.data[\"size\"]\n            - graph.scatterplot_item.data[\"size\"],\n            SELECTION_WIDTH)\n\n    @patch(\"Orange.widgets.visualize.owscatterplotgraph\"\n           \".MAX_N_VALID_SIZE_ANIMATE\", 5)\n    def test_size_animation(self):\n        begin_resizing = QSignalSpy(self.graph.begin_resizing)\n        step_resizing = QSignalSpy(self.graph.step_resizing)\n        end_resizing = QSignalSpy(self.graph.end_resizing)\n        self._update_sizes_for_points(5)\n        # first end_resizing is triggered in reset, thus wait for step_resizing\n        step_resizing.wait(200)\n        end_resizing.wait(200)\n        self.assertEqual(len(begin_resizing), 2)  # reset and update\n        self.assertEqual(len(step_resizing), 5)\n        self.assertEqual(len(end_resizing), 2)  # reset and update\n        self.assertEqual(self.graph.scatterplot_item.setSize.call_count, 6)\n        self._update_sizes_for_points(6)\n        self.graph.scatterplot_item.setSize.assert_called_once()\n\n    def _update_sizes_for_points(self, n: int):\n        arr = np.arange(n, dtype=float)\n        self.master.get_coordinates_data = lambda: (arr, arr)\n        self.master.get_size_data = lambda: arr\n        self.graph.reset_graph()\n        self.graph.scatterplot_item.setSize = Mock(\n            wraps=self.graph.scatterplot_item.setSize)\n        self.master.get_size_data = lambda: arr[::-1]\n        self.graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n    def test_colors_discrete(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        self.master.get_color_data = lambda: d\n        d = np.arange(10, dtype=float) % 2\n\n        graph.reset_graph()\n        data = graph.scatterplot_item.data\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"pen\"])))\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"brush\"])))\n\n        # confirm that QPen/QBrush were reused\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 2)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)\n\n    def test_colors_discrete_nan(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        self.assertEqual(pens[0].color().hue(), palette[0].hue())\n        self.assertEqual(pens[1].color().hue(), palette[1].hue())\n        self.assertEqual(brushes[0].color().hue(), palette[0].hue())\n        self.assertEqual(brushes[1].color().hue(), palette[1].hue())\n        self.assertEqual(pens[4].color().hue(), QColor(128, 128, 128).hue())\n        self.assertEqual(brushes[4].color().hue(), QColor(128, 128, 128).hue())\n\n    def test_colors_continuous(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()  # I don't have a good test ... just don't crash\n\n        d[4] = np.nan\n        graph.update_colors()  # Ditto\n\n    def test_colors_continuous_reused(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n\n        d = np.arange(100, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n\n        data = graph.scatterplot_item.data\n\n        self.assertEqual(len(data[\"pen\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"pen\"]))), 10)\n        self.assertEqual(len(data[\"brush\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"brush\"]))), 10)\n\n    def test_colors_continuous_nan(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        nan_color = QColor(*NAN_GREY)\n        self.assertEqual(pens[4].color().hue(), nan_color.hue())\n        self.assertEqual(brushes[4].color().hue(), nan_color.hue())\n\n    def test_colors_subset(self):\n        def run_tests():\n            self.master.get_subset_mask = lambda: None\n\n            graph.alpha_value = 42\n            graph.reset_graph()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 42)\n            self.assertEqual(brushes[1].color().alpha(), 42)\n            self.assertEqual(brushes[4].color().alpha(), 42)\n\n            graph.alpha_value = 123\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 123)\n            self.assertEqual(brushes[1].color().alpha(), 123)\n            self.assertEqual(brushes[4].color().alpha(), 123)\n\n            self.master.get_subset_mask = lambda: np.arange(10) >= 5\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 0)\n            self.assertEqual(brushes[1].color().alpha(), 0)\n            self.assertEqual(brushes[4].color().alpha(), 0)\n            self.assertEqual(brushes[5].color().alpha(), 255)\n            self.assertEqual(brushes[6].color().alpha(), 255)\n            self.assertEqual(brushes[7].color().alpha(), 255)\n\n        graph = self.graph\n\n        self.master.get_color_data = lambda: None\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n        d = np.arange(10, dtype=float) % 2\n        d[4:6] = np.nan\n        self.master.get_color_data = lambda: d\n\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n    def test_colors_none(self):\n        graph = self.graph\n        graph.reset_graph()\n        hue = QColor(128, 128, 128).hue()\n\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)  # test QPen/QBrush reuse\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 1)\n\n        self.master.get_subset_mask = lambda: np.arange(10) < 5\n        graph.update_colors()\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)  # transparent and colored\n\n    def test_colors_update_legend_and_density(self):\n        graph = self.graph\n        graph.update_legends = Mock()\n        graph.update_density = Mock()\n        graph.reset_graph()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n        graph.update_legends.reset_mock()\n        graph.update_density.reset_mock()\n\n        graph.update_coordinates()\n        graph.update_legends.assert_not_called()\n\n        graph.update_colors()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n    def test_selection_colors(self):\n        graph = self.graph\n        graph.reset_graph()\n        data = graph.scatterplot_item_sel.data\n\n        # One group\n        graph.select_by_indices(np.array([0, 1, 2, 3]))\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(4):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(4, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n\n        # Two groups\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_indices(np.array([4, 5, 6]))\n\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(7):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(7, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n        self.assertEqual(len({pen.color().hue() for pen in pens[:4]}), 1)\n        self.assertEqual(len({pen.color().hue() for pen in pens[4:7]}), 1)\n        color1 = pens[3].color().hue()\n        color2 = pens[4].color().hue()\n        self.assertNotEqual(color1, color2)\n\n        # Two groups + sampling\n        graph.set_sample_size(7)\n        x = graph.scatterplot_item.getData()[0]\n        pens = graph.scatterplot_item_sel.data[\"pen\"]\n        for xi, pen in zip(x, pens):\n            if xi < 4:\n                self.assertEqual(pen.color().hue(), color1)\n            elif xi < 7:\n                self.assertEqual(pen.color().hue(), color2)\n            else:\n                self.assertEqual(pen.style(), Qt.NoPen)\n\n    def test_density(self):\n        graph = self.graph\n        density = object()\n        with patch(\"Orange.widgets.utils.classdensity.class_density_image\",\n                   return_value=density):\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n\n            graph.plot_widget.addItem = Mock()\n            graph.plot_widget.removeItem = Mock()\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.ones((10, ), dtype=float)\n            self.master.get_color_data = lambda: d\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.arange(10) % 2\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.class_density = False\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.update_coordinates = lambda: (None, None)\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n    def test_labels(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n\n        # Label only selected\n        selected = [1, 3, 5]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(x) for x in selected])\n        x, y = graph.scatterplot_item.getData()\n        for i, index in enumerate(selected):\n            self.assertEqual(x[index], graph.labels[i].x())\n            self.assertEqual(y[index], graph.labels[i].y())\n\n        # Disable label only selected\n        self.graph.label_only_selected = False\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        # Label only selected + sampling\n        selected = [1, 3, 4, 5, 6, 7, 9]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        graph.set_sample_size(5)\n        for label in graph.labels:\n            ind = int(label.textItem.toPlainText())\n            self.assertIn(ind, selected)\n            self.assertEqual(label.x(), x[ind])\n            self.assertEqual(label.y(), y[ind])\n\n    def test_label_mask_all_visible(self):\n        graph = self.graph\n\n        x, y = np.arange(10) / 10, np.arange(10) / 10\n        sel = np.array(\n            [True, True, False, False, False, True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False, True, True, False, False, False])\n        trues = np.ones(10, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel)\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), np.array(\n            [True, True, True, True, False, True, True, True, False, False]\n        ))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset)\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5, 10) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, False, True])\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        trues = np.ones(5, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel[5:])\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([True, True, True, False, True]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset[5:])\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible_and_view(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])  # first and last out of the view\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, True, True])  # first and last out of the view\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        graph.view_box.viewRange = lambda: ((0.6, 1), (0, 0.3))\n        viewed = np.array([False, True, True, True, False])\n\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, False, False]))\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, True, False]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, False, True, False]))\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_labels_observes_mask(self):\n        graph = self.graph\n        get_label_data = graph.master.get_label_data\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        get_label_data.reset_mock()\n        graph._label_mask = lambda *_: None\n        graph.update_labels()\n        get_label_data.assert_not_called()\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph._label_mask = \\\n            lambda *_: np.array([False, True, True] + [False] * 7)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [\"1\", \"2\"])\n\n    def test_labels_update_coordinates(self):\n        graph = self.graph\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n\n        graph.reset_graph()\n        graph.set_sample_size(7)\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        self.master.get_coordinates_data = \\\n            lambda: (np.arange(10, 20), np.arange(50, 60))\n        graph.update_coordinates()\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n    def test_shapes(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 3]\n                            for i, symbol in enumerate(symbols)))\n\n        d = np.arange(10, dtype=float) % 2\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 2]\n                            for i, symbol in enumerate(symbols)))\n\n        d = None\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertEqual(len(set(symbols)), 1)\n\n    def test_shapes_nan(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n\n        graph.reset_graph()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2], '?')\n\n        d[:] = np.nan\n        graph.update_shapes()\n        self.assertTrue(\n            all(symbol == '?'\n                for symbol in graph.scatterplot_item.data[\"symbol\"]))\n\n        def impute0(data, _):\n            data[np.isnan(data)] = 0\n\n        self.master.impute_shapes = impute0\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n        graph.update_shapes()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2],\n                         graph.CurveSymbols[0])\n\n    def test_show_grid(self):\n        graph = self.graph\n        show_grid = self.graph.plot_widget.showGrid = Mock()\n        graph.show_grid = False\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=False, y=False))\n\n        graph.show_grid = True\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=True, y=True))\n\n    def test_show_legend(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        shape_labels = color_labels = None  # Avoid pylint warning\n        self.master.get_shape_labels = lambda: shape_labels\n        self.master.get_color_labels = lambda: color_labels\n        for shape_labels in (None, [\"a\", \"b\"]):\n            for color_labels in (None, [\"c\", \"d\"], None):\n                for visible in (True, False, True):\n                    graph.show_legend = visible\n                    graph.update_legends()\n                    self.assertIs(\n                        shape_legend.call_args[0][0],\n                        visible and bool(shape_labels),\n                        msg=\"error at {}, {}\".format(visible, shape_labels))\n                    self.assertIs(\n                        color_legend.call_args[0][0],\n                        visible and bool(color_labels),\n                        msg=\"error at {}, {}\".format(visible, color_labels))\n\n    def test_show_legend_no_data(self):\n        graph = self.graph\n        self.master.get_shape_labels = lambda: [\"a\", \"b\"]\n        self.master.get_color_labels = lambda: [\"c\", \"d\"]\n        self.master.get_shape_data = lambda: np.arange(10) % 2\n        self.master.get_color_data = lambda: np.arange(10) < 6\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        self.master.get_coordinates_data = lambda: (None, None)\n        graph.reset_graph()\n        self.assertFalse(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n\n    def test_legend_combine(self):\n        master = self.master\n        graph = self.graph\n\n        master.get_shape_data = lambda: np.arange(10, dtype=float) % 3\n        master.get_color_data = lambda: 2 * np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n\n        master.get_shape_labels = lambda: [\"a\", \"b\"]\n        master.get_color_labels = lambda: [\"c\", \"d\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n\n        master.get_color_labels = lambda: [\"a\", \"b\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.get_color_data = lambda: np.arange(10, dtype=float) % 3\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.is_continuous_color = lambda: True\n        master.get_color_data = lambda: np.arange(10, dtype=float)\n        master.get_color_labels = lambda: None\n        graph.update_colors()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n    def test_select_by_click(self):\n        graph = self.graph\n        graph.reset_graph()\n        points = graph.scatterplot_item.points()\n        graph.select_by_click(None, [points[2]])\n        np.testing.assert_almost_equal(graph.get_selection(), [2])\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_click(None, points[3:6])\n        np.testing.assert_almost_equal(\n            list(graph.get_selection()), [2, 3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 1, 2, 2, 2, 0, 0, 0, 0])\n\n    def test_select_by_rectangle(self):\n        graph = self.graph\n        coords = np.array(\n            [(x, y) for y in range(10) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n\n        graph.reset_graph()\n        graph.select_by_rectangle(QRectF(3, 5, 3.9, 2.9))\n        self.assertTrue(\n            all(selected == (3 <= coords[0][i] <= 6 and 5 <= coords[1][i] <= 7)\n                for i, selected in enumerate(graph.selection)))\n\n    def test_select_by_indices(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        def select(modifiers, indices):\n            with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                       lambda: modifiers):\n                graph.update_selection_colors = Mock()\n                graph.update_labels = Mock()\n                self.master.selection_changed = Mock()\n\n                graph.select_by_indices(np.array(indices))\n                graph.update_selection_colors.assert_called_with()\n                if graph.label_only_selected:\n                    graph.update_labels.assert_called_with()\n                else:\n                    graph.update_labels.assert_not_called()\n                self.master.selection_changed.assert_called_with()\n\n        select(0, [7, 8, 9])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 0, 0, 1, 1, 1])\n\n        select(Qt.ShiftModifier | Qt.ControlModifier, [5, 6])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 1, 1, 1, 1, 1])\n\n        select(Qt.ShiftModifier, [3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 2, 2, 2, 1, 1, 1, 1])\n\n        select(Qt.AltModifier, [1, 3, 7])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 2, 2, 1, 0, 1, 1])\n\n        select(0, [1, 8])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 1, 0, 0, 0, 0, 0, 0, 1, 0])\n\n        graph.label_only_selected = False\n        select(0, [3, 4])\n\n    def test_unselect_all(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        graph.select_by_indices([3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 1, 1, 1, 0, 0, 0, 0])\n\n        graph.update_selection_colors = Mock()\n        graph.update_labels = Mock()\n        self.master.selection_changed = Mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_called_with()\n        graph.update_labels.assert_called_with()\n        self.master.selection_changed.assert_called_with()\n\n        graph.update_selection_colors.reset_mock()\n        graph.update_labels.reset_mock()\n        self.master.selection_changed.reset_mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_not_called()\n        graph.update_labels.assert_not_called()\n        self.master.selection_changed.assert_not_called()\n\n    def test_hiding_too_many_labels(self):\n        spy = QSignalSpy(self.graph.too_many_labels)\n        self.graph.MAX_VISIBLE_LABELS = 5\n\n        graph = self.graph\n        coords = np.array(\n            [(x, 0) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n        graph.reset_graph()\n\n        self.assertFalse(spy and spy[-1][0])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 4, 4))\n        graph.view_box.sigRangeChangedManually.emit(((1, 5), (-1, 3)))\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 8, 8))\n        graph.view_box.sigRangeChangedManually.emit(((1, 9), (-1, 7)))\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.label_only_selected = True\n        graph.update_labels()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3, 4, 5, 6])\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3])\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.label_only_selected = False\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.clear()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n    def test_no_needless_buildatlas(self):\n        graph = self.graph\n        graph.reset_graph()\n        self.assertIsNone(graph.scatterplot_item.fragmentAtlas.atlas)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1105,
                            "end_lineno": 1141,
                            "parent": {
                                "file_name": "Orange/widgets/visualize/tests/test_owscatterplotbase.py",
                                "type": "class",
                                "name": "TestOWScatterPlotBase",
                                "content": "class TestOWScatterPlotBase(WidgetTest):\n    def setUp(self):\n        self.master = MockWidget()\n        self.graph = OWScatterPlotBase(self.master)\n\n        self.xy = (np.arange(10, dtype=float), np.arange(10, dtype=float))\n        self.master.get_coordinates_data = lambda: self.xy\n\n    # pylint: disable=keyword-arg-before-vararg\n    def setRange(self, rect=None, *_, **__):\n        if isinstance(rect, QRectF):\n            self.last_setRange = [[rect.left(), rect.right()],\n                                  [rect.top(), rect.bottom()]]\n\n    def test_update_coordinates_no_data(self):\n        self.xy = None, None\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n        self.xy = [], []\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        graph.reset_graph()\n\n        scatterplot_item = graph.scatterplot_item\n        scatterplot_item_sel = graph.scatterplot_item_sel\n        data = scatterplot_item.data\n\n        np.testing.assert_almost_equal(scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(scatterplot_item_sel.getData(), xy)\n        scatterplot_item.setSize([5, 6])\n        scatterplot_item.setSymbol([7, 8])\n        scatterplot_item.setPen([mkPen(9), mkPen(10)])\n        scatterplot_item.setBrush([11, 12])\n        data[\"data\"] = np.array([13, 14])\n\n        xy[0][0] = 0\n        graph.update_coordinates()\n        np.testing.assert_almost_equal(graph.scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(graph.scatterplot_item_sel.getData(), xy)\n\n        # Graph updates coordinates instead of creating new items\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        self.assertIs(scatterplot_item_sel, graph.scatterplot_item_sel)\n        np.testing.assert_almost_equal(data[\"size\"], [5, 6])\n        np.testing.assert_almost_equal(data[\"symbol\"], [7, 8])\n        self.assertEqual(data[\"pen\"][0], mkPen(9))\n        self.assertEqual(data[\"pen\"][1], mkPen(10))\n        np.testing.assert_almost_equal(data[\"brush\"], [11, 12])\n        np.testing.assert_almost_equal(data[\"data\"], [13, 14])\n\n    def test_update_coordinates_and_labels(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1., 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 1.5\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 1.5)\n        xy[0][0] = 0  # This label goes out of the range\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 2)\n\n    def test_update_coordinates_and_density(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 0\n        graph.update_density = Mock()\n        graph.update_coordinates()\n        graph.update_density.assert_called_with()\n\n    def test_update_coordinates_reset_view(self):\n        graph = self.graph\n        graph.view_box.setRange = self.setRange\n        xy = self.xy = (np.array([2, 1]), np.array([3, 10]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(self.last_setRange, [[1, 2], [3, 10]])\n\n        xy[0][1] = 0\n        graph.update_coordinates()\n        self.assertEqual(self.last_setRange, [[0, 2], [3, 10]])\n\n    def test_reset_graph_no_data(self):\n        self.xy = (None, None)\n        self.graph.scatterplot_item = ScatterPlotItem([1, 2], [3, 4])\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates_indices(self):\n        graph = self.graph\n        self.xy = (np.array([2, 1]), np.array([3, 10]))\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item.data[\"data\"], [0, 1])\n\n    def test_sampling(self):\n        graph = self.graph\n        master = self.master\n\n        # Enable sampling before getting the data\n        graph.set_sample_size(3)\n        xy = self.xy = (np.arange(10, dtype=float),\n                        np.arange(0, 30, 3, dtype=float))\n        d = np.arange(10, dtype=float)\n        master.get_size_data = lambda: d\n        master.get_shape_data = lambda: d % 5 if d is not None else None\n        master.get_color_data = lambda: d\n        master.get_label_data = lambda: \\\n            np.array([str(x) for x in d], dtype=object)\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n        # Check proper sampling\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertNotEqual(x[0], x[1])\n        self.assertNotEqual(x[0], x[2])\n        self.assertNotEqual(x[1], x[2])\n        np.testing.assert_almost_equal(3 * x, y)\n\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Check that sample is extended when sample size is changed\n        graph.set_sample_size(4)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s = data[\"size\"] - graph.MinShapeSize\n        precise_s = (x - min(x)) / (max(x) - min(x)) * max(s)\n        np.testing.assert_almost_equal(s, precise_s, decimal=0)\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Disable sampling\n        graph.set_sample_size(None)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        np.testing.assert_almost_equal(x, xy[0])\n        np.testing.assert_almost_equal(y, xy[1])\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in d])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in d])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in d])\n\n        # Enable sampling when data is already present and not sampled\n        graph.set_sample_size(3)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Update data when data is present and sampling is enabled\n        xy[0][:] = np.arange(9, -1, -1, dtype=float)\n        d = xy[0]\n        graph.update_coordinates()\n        x1, _ = scatterplot_item.getData()\n        np.testing.assert_almost_equal(9 - x, x1)\n        graph.update_sizes()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Reset graph when data is present and sampling is enabled\n        self.xy = (np.arange(100, 105, dtype=float),\n                   np.arange(100, 105, dtype=float))\n        d = self.xy[0] - 100\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertTrue(np.all(x > 99))\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Don't sample when unnecessary\n        self.xy = (np.arange(100, dtype=float), ) * 2\n        d = None\n        delattr(master, \"get_label_data\")\n        graph.reset_graph()\n        graph.set_sample_size(120)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_almost_equal(x, np.arange(100))\n\n    def test_sampling_keeps_selection(self):\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n        graph.reset_graph()\n        graph.select_by_indices(np.arange(1, 100, 2))\n        graph.set_sample_size(30)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n        graph.set_sample_size(None)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n\n    base = \"Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase.\"\n\n    @patch(base + \"update_sizes\")\n    @patch(base + \"update_colors\")\n    @patch(base + \"update_selection_colors\")\n    @patch(base + \"update_shapes\")\n    @patch(base + \"update_labels\")\n    def test_reset_calls_all_updates_and_update_doesnt(self, *mocks):\n        master = MockWidget()\n        graph = OWScatterPlotBase(master)\n        for mock in mocks:\n            mock.assert_not_called()\n\n        graph.reset_graph()\n        for mock in mocks:\n            mock.assert_called_with()\n            mock.reset_mock()\n\n        graph.update_coordinates()\n        for mock in mocks:\n            mock.assert_not_called()\n\n    def test_jittering(self):\n        graph = self.graph\n        graph.jitter_size = 10\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        a10 = np.arange(10)\n        self.assertTrue(np.any(np.nonzero(a10 - x)))\n        self.assertTrue(np.any(np.nonzero(a10 - y)))\n        np.testing.assert_array_less(a10 - x, 1)\n        np.testing.assert_array_less(a10 - y, 1)\n\n        graph.jitter_size = 0\n        graph.update_coordinates()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_equal(a10, x)\n\n    def test_size_normalization(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, [6, 7.5, 9.5, 11, 12.5, 14.5, 16, 17.5, 19.5, 21])\n\n        d = np.arange(10, 20, dtype=float)\n        graph.update_sizes()\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        size2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, size2)\n\n    def test_size_rounding_half_pixel(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size*2 - (size*2).round(), 0)\n\n    def test_size_with_nans(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n\n        d[4] = np.nan\n        graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        sizes2 = scatterplot_item.data[\"size\"]\n\n        self.assertEqual(sizes[1] - sizes[0], sizes2[1] - sizes2[0])\n        self.assertLess(sizes2[4], self.graph.MinShapeSize)\n\n        d[:] = np.nan\n        graph.update_sizes()\n        sizes3 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes3)\n\n    def test_sizes_all_same_or_nan(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.full((10, ), 3.0)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n        self.assertEqual(len(set(sizes)), 1)\n        self.assertGreater(sizes[0], self.graph.MinShapeSize)\n\n        d = None\n        graph.update_sizes()\n        scatterplot_item = graph.scatterplot_item\n        sizes2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes2)\n\n    def test_sizes_point_width_is_linear(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.point_width = 1\n        graph.reset_graph()\n        sizes1 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 2\n        graph.update_sizes()\n        sizes2 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 3\n        graph.update_sizes()\n        sizes3 = graph.scatterplot_item.data[\"size\"]\n\n        np.testing.assert_almost_equal(2 * (sizes2 - sizes1), sizes3 - sizes1)\n\n    def test_sizes_custom_imputation(self):\n\n        def impute_max(size_data):\n            size_data[np.isnan(size_data)] = np.nanmax(size_data)\n\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        self.master.impute_sizes = impute_max\n        d = np.arange(10, dtype=float)\n        d[4] = np.nan\n        graph.reset_graph()\n        sizes = graph.scatterplot_item.data[\"size\"]\n        self.assertAlmostEqual(sizes[4], sizes[9])\n\n    def test_sizes_selection(self):\n        graph = self.graph\n        graph.get_size = lambda: np.arange(10, dtype=float)\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item_sel.data[\"size\"]\n            - graph.scatterplot_item.data[\"size\"],\n            SELECTION_WIDTH)\n\n    @patch(\"Orange.widgets.visualize.owscatterplotgraph\"\n           \".MAX_N_VALID_SIZE_ANIMATE\", 5)\n    def test_size_animation(self):\n        begin_resizing = QSignalSpy(self.graph.begin_resizing)\n        step_resizing = QSignalSpy(self.graph.step_resizing)\n        end_resizing = QSignalSpy(self.graph.end_resizing)\n        self._update_sizes_for_points(5)\n        # first end_resizing is triggered in reset, thus wait for step_resizing\n        step_resizing.wait(200)\n        end_resizing.wait(200)\n        self.assertEqual(len(begin_resizing), 2)  # reset and update\n        self.assertEqual(len(step_resizing), 5)\n        self.assertEqual(len(end_resizing), 2)  # reset and update\n        self.assertEqual(self.graph.scatterplot_item.setSize.call_count, 6)\n        self._update_sizes_for_points(6)\n        self.graph.scatterplot_item.setSize.assert_called_once()\n\n    def _update_sizes_for_points(self, n: int):\n        arr = np.arange(n, dtype=float)\n        self.master.get_coordinates_data = lambda: (arr, arr)\n        self.master.get_size_data = lambda: arr\n        self.graph.reset_graph()\n        self.graph.scatterplot_item.setSize = Mock(\n            wraps=self.graph.scatterplot_item.setSize)\n        self.master.get_size_data = lambda: arr[::-1]\n        self.graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n    def test_colors_discrete(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        self.master.get_color_data = lambda: d\n        d = np.arange(10, dtype=float) % 2\n\n        graph.reset_graph()\n        data = graph.scatterplot_item.data\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"pen\"])))\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"brush\"])))\n\n        # confirm that QPen/QBrush were reused\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 2)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)\n\n    def test_colors_discrete_nan(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        self.assertEqual(pens[0].color().hue(), palette[0].hue())\n        self.assertEqual(pens[1].color().hue(), palette[1].hue())\n        self.assertEqual(brushes[0].color().hue(), palette[0].hue())\n        self.assertEqual(brushes[1].color().hue(), palette[1].hue())\n        self.assertEqual(pens[4].color().hue(), QColor(128, 128, 128).hue())\n        self.assertEqual(brushes[4].color().hue(), QColor(128, 128, 128).hue())\n\n    def test_colors_continuous(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()  # I don't have a good test ... just don't crash\n\n        d[4] = np.nan\n        graph.update_colors()  # Ditto\n\n    def test_colors_continuous_reused(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n\n        d = np.arange(100, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n\n        data = graph.scatterplot_item.data\n\n        self.assertEqual(len(data[\"pen\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"pen\"]))), 10)\n        self.assertEqual(len(data[\"brush\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"brush\"]))), 10)\n\n    def test_colors_continuous_nan(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        nan_color = QColor(*NAN_GREY)\n        self.assertEqual(pens[4].color().hue(), nan_color.hue())\n        self.assertEqual(brushes[4].color().hue(), nan_color.hue())\n\n    def test_colors_subset(self):\n        def run_tests():\n            self.master.get_subset_mask = lambda: None\n\n            graph.alpha_value = 42\n            graph.reset_graph()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 42)\n            self.assertEqual(brushes[1].color().alpha(), 42)\n            self.assertEqual(brushes[4].color().alpha(), 42)\n\n            graph.alpha_value = 123\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 123)\n            self.assertEqual(brushes[1].color().alpha(), 123)\n            self.assertEqual(brushes[4].color().alpha(), 123)\n\n            self.master.get_subset_mask = lambda: np.arange(10) >= 5\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 0)\n            self.assertEqual(brushes[1].color().alpha(), 0)\n            self.assertEqual(brushes[4].color().alpha(), 0)\n            self.assertEqual(brushes[5].color().alpha(), 255)\n            self.assertEqual(brushes[6].color().alpha(), 255)\n            self.assertEqual(brushes[7].color().alpha(), 255)\n\n        graph = self.graph\n\n        self.master.get_color_data = lambda: None\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n        d = np.arange(10, dtype=float) % 2\n        d[4:6] = np.nan\n        self.master.get_color_data = lambda: d\n\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n    def test_colors_none(self):\n        graph = self.graph\n        graph.reset_graph()\n        hue = QColor(128, 128, 128).hue()\n\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)  # test QPen/QBrush reuse\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 1)\n\n        self.master.get_subset_mask = lambda: np.arange(10) < 5\n        graph.update_colors()\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)  # transparent and colored\n\n    def test_colors_update_legend_and_density(self):\n        graph = self.graph\n        graph.update_legends = Mock()\n        graph.update_density = Mock()\n        graph.reset_graph()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n        graph.update_legends.reset_mock()\n        graph.update_density.reset_mock()\n\n        graph.update_coordinates()\n        graph.update_legends.assert_not_called()\n\n        graph.update_colors()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n    def test_selection_colors(self):\n        graph = self.graph\n        graph.reset_graph()\n        data = graph.scatterplot_item_sel.data\n\n        # One group\n        graph.select_by_indices(np.array([0, 1, 2, 3]))\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(4):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(4, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n\n        # Two groups\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_indices(np.array([4, 5, 6]))\n\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(7):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(7, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n        self.assertEqual(len({pen.color().hue() for pen in pens[:4]}), 1)\n        self.assertEqual(len({pen.color().hue() for pen in pens[4:7]}), 1)\n        color1 = pens[3].color().hue()\n        color2 = pens[4].color().hue()\n        self.assertNotEqual(color1, color2)\n\n        # Two groups + sampling\n        graph.set_sample_size(7)\n        x = graph.scatterplot_item.getData()[0]\n        pens = graph.scatterplot_item_sel.data[\"pen\"]\n        for xi, pen in zip(x, pens):\n            if xi < 4:\n                self.assertEqual(pen.color().hue(), color1)\n            elif xi < 7:\n                self.assertEqual(pen.color().hue(), color2)\n            else:\n                self.assertEqual(pen.style(), Qt.NoPen)\n\n    def test_density(self):\n        graph = self.graph\n        density = object()\n        with patch(\"Orange.widgets.utils.classdensity.class_density_image\",\n                   return_value=density):\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n\n            graph.plot_widget.addItem = Mock()\n            graph.plot_widget.removeItem = Mock()\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.ones((10, ), dtype=float)\n            self.master.get_color_data = lambda: d\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.arange(10) % 2\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.class_density = False\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.update_coordinates = lambda: (None, None)\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n    def test_labels(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n\n        # Label only selected\n        selected = [1, 3, 5]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(x) for x in selected])\n        x, y = graph.scatterplot_item.getData()\n        for i, index in enumerate(selected):\n            self.assertEqual(x[index], graph.labels[i].x())\n            self.assertEqual(y[index], graph.labels[i].y())\n\n        # Disable label only selected\n        self.graph.label_only_selected = False\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        # Label only selected + sampling\n        selected = [1, 3, 4, 5, 6, 7, 9]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        graph.set_sample_size(5)\n        for label in graph.labels:\n            ind = int(label.textItem.toPlainText())\n            self.assertIn(ind, selected)\n            self.assertEqual(label.x(), x[ind])\n            self.assertEqual(label.y(), y[ind])\n\n    def test_label_mask_all_visible(self):\n        graph = self.graph\n\n        x, y = np.arange(10) / 10, np.arange(10) / 10\n        sel = np.array(\n            [True, True, False, False, False, True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False, True, True, False, False, False])\n        trues = np.ones(10, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel)\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), np.array(\n            [True, True, True, True, False, True, True, True, False, False]\n        ))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset)\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5, 10) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, False, True])\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        trues = np.ones(5, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel[5:])\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([True, True, True, False, True]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset[5:])\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible_and_view(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])  # first and last out of the view\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, True, True])  # first and last out of the view\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        graph.view_box.viewRange = lambda: ((0.6, 1), (0, 0.3))\n        viewed = np.array([False, True, True, True, False])\n\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, False, False]))\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, True, False]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, False, True, False]))\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_labels_observes_mask(self):\n        graph = self.graph\n        get_label_data = graph.master.get_label_data\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        get_label_data.reset_mock()\n        graph._label_mask = lambda *_: None\n        graph.update_labels()\n        get_label_data.assert_not_called()\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph._label_mask = \\\n            lambda *_: np.array([False, True, True] + [False] * 7)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [\"1\", \"2\"])\n\n    def test_labels_update_coordinates(self):\n        graph = self.graph\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n\n        graph.reset_graph()\n        graph.set_sample_size(7)\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        self.master.get_coordinates_data = \\\n            lambda: (np.arange(10, 20), np.arange(50, 60))\n        graph.update_coordinates()\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n    def test_shapes(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 3]\n                            for i, symbol in enumerate(symbols)))\n\n        d = np.arange(10, dtype=float) % 2\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 2]\n                            for i, symbol in enumerate(symbols)))\n\n        d = None\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertEqual(len(set(symbols)), 1)\n\n    def test_shapes_nan(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n\n        graph.reset_graph()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2], '?')\n\n        d[:] = np.nan\n        graph.update_shapes()\n        self.assertTrue(\n            all(symbol == '?'\n                for symbol in graph.scatterplot_item.data[\"symbol\"]))\n\n        def impute0(data, _):\n            data[np.isnan(data)] = 0\n\n        self.master.impute_shapes = impute0\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n        graph.update_shapes()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2],\n                         graph.CurveSymbols[0])\n\n    def test_show_grid(self):\n        graph = self.graph\n        show_grid = self.graph.plot_widget.showGrid = Mock()\n        graph.show_grid = False\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=False, y=False))\n\n        graph.show_grid = True\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=True, y=True))\n\n    def test_show_legend(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        shape_labels = color_labels = None  # Avoid pylint warning\n        self.master.get_shape_labels = lambda: shape_labels\n        self.master.get_color_labels = lambda: color_labels\n        for shape_labels in (None, [\"a\", \"b\"]):\n            for color_labels in (None, [\"c\", \"d\"], None):\n                for visible in (True, False, True):\n                    graph.show_legend = visible\n                    graph.update_legends()\n                    self.assertIs(\n                        shape_legend.call_args[0][0],\n                        visible and bool(shape_labels),\n                        msg=\"error at {}, {}\".format(visible, shape_labels))\n                    self.assertIs(\n                        color_legend.call_args[0][0],\n                        visible and bool(color_labels),\n                        msg=\"error at {}, {}\".format(visible, color_labels))\n\n    def test_show_legend_no_data(self):\n        graph = self.graph\n        self.master.get_shape_labels = lambda: [\"a\", \"b\"]\n        self.master.get_color_labels = lambda: [\"c\", \"d\"]\n        self.master.get_shape_data = lambda: np.arange(10) % 2\n        self.master.get_color_data = lambda: np.arange(10) < 6\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        self.master.get_coordinates_data = lambda: (None, None)\n        graph.reset_graph()\n        self.assertFalse(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n\n    def test_legend_combine(self):\n        master = self.master\n        graph = self.graph\n\n        master.get_shape_data = lambda: np.arange(10, dtype=float) % 3\n        master.get_color_data = lambda: 2 * np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n\n        master.get_shape_labels = lambda: [\"a\", \"b\"]\n        master.get_color_labels = lambda: [\"c\", \"d\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n\n        master.get_color_labels = lambda: [\"a\", \"b\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.get_color_data = lambda: np.arange(10, dtype=float) % 3\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.is_continuous_color = lambda: True\n        master.get_color_data = lambda: np.arange(10, dtype=float)\n        master.get_color_labels = lambda: None\n        graph.update_colors()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n    def test_select_by_click(self):\n        graph = self.graph\n        graph.reset_graph()\n        points = graph.scatterplot_item.points()\n        graph.select_by_click(None, [points[2]])\n        np.testing.assert_almost_equal(graph.get_selection(), [2])\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_click(None, points[3:6])\n        np.testing.assert_almost_equal(\n            list(graph.get_selection()), [2, 3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 1, 2, 2, 2, 0, 0, 0, 0])\n\n    def test_select_by_rectangle(self):\n        graph = self.graph\n        coords = np.array(\n            [(x, y) for y in range(10) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n\n        graph.reset_graph()\n        graph.select_by_rectangle(QRectF(3, 5, 3.9, 2.9))\n        self.assertTrue(\n            all(selected == (3 <= coords[0][i] <= 6 and 5 <= coords[1][i] <= 7)\n                for i, selected in enumerate(graph.selection)))\n\n    def test_select_by_indices(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        def select(modifiers, indices):\n            with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                       lambda: modifiers):\n                graph.update_selection_colors = Mock()\n                graph.update_labels = Mock()\n                self.master.selection_changed = Mock()\n\n                graph.select_by_indices(np.array(indices))\n                graph.update_selection_colors.assert_called_with()\n                if graph.label_only_selected:\n                    graph.update_labels.assert_called_with()\n                else:\n                    graph.update_labels.assert_not_called()\n                self.master.selection_changed.assert_called_with()\n\n        select(0, [7, 8, 9])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 0, 0, 1, 1, 1])\n\n        select(Qt.ShiftModifier | Qt.ControlModifier, [5, 6])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 1, 1, 1, 1, 1])\n\n        select(Qt.ShiftModifier, [3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 2, 2, 2, 1, 1, 1, 1])\n\n        select(Qt.AltModifier, [1, 3, 7])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 2, 2, 1, 0, 1, 1])\n\n        select(0, [1, 8])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 1, 0, 0, 0, 0, 0, 0, 1, 0])\n\n        graph.label_only_selected = False\n        select(0, [3, 4])\n\n    def test_unselect_all(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        graph.select_by_indices([3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 1, 1, 1, 0, 0, 0, 0])\n\n        graph.update_selection_colors = Mock()\n        graph.update_labels = Mock()\n        self.master.selection_changed = Mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_called_with()\n        graph.update_labels.assert_called_with()\n        self.master.selection_changed.assert_called_with()\n\n        graph.update_selection_colors.reset_mock()\n        graph.update_labels.reset_mock()\n        self.master.selection_changed.reset_mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_not_called()\n        graph.update_labels.assert_not_called()\n        self.master.selection_changed.assert_not_called()\n\n    def test_hiding_too_many_labels(self):\n        spy = QSignalSpy(self.graph.too_many_labels)\n        self.graph.MAX_VISIBLE_LABELS = 5\n\n        graph = self.graph\n        coords = np.array(\n            [(x, 0) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n        graph.reset_graph()\n\n        self.assertFalse(spy and spy[-1][0])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 4, 4))\n        graph.view_box.sigRangeChangedManually.emit(((1, 5), (-1, 3)))\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 8, 8))\n        graph.view_box.sigRangeChangedManually.emit(((1, 9), (-1, 7)))\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.label_only_selected = True\n        graph.update_labels()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3, 4, 5, 6])\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3])\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.label_only_selected = False\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.clear()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n    def test_no_needless_buildatlas(self):\n        graph = self.graph\n        graph.reset_graph()\n        self.assertIsNone(graph.scatterplot_item.fragmentAtlas.atlas)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 49,
                                "end_lineno": 1294,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/widgets/visualize/tests/test_owscatterplotbase.py",
                            "type": "class",
                            "name": "TestOWScatterPlotBase",
                            "content": "class TestOWScatterPlotBase(WidgetTest):\n    def setUp(self):\n        self.master = MockWidget()\n        self.graph = OWScatterPlotBase(self.master)\n\n        self.xy = (np.arange(10, dtype=float), np.arange(10, dtype=float))\n        self.master.get_coordinates_data = lambda: self.xy\n\n    # pylint: disable=keyword-arg-before-vararg\n    def setRange(self, rect=None, *_, **__):\n        if isinstance(rect, QRectF):\n            self.last_setRange = [[rect.left(), rect.right()],\n                                  [rect.top(), rect.bottom()]]\n\n    def test_update_coordinates_no_data(self):\n        self.xy = None, None\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n        self.xy = [], []\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        graph.reset_graph()\n\n        scatterplot_item = graph.scatterplot_item\n        scatterplot_item_sel = graph.scatterplot_item_sel\n        data = scatterplot_item.data\n\n        np.testing.assert_almost_equal(scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(scatterplot_item_sel.getData(), xy)\n        scatterplot_item.setSize([5, 6])\n        scatterplot_item.setSymbol([7, 8])\n        scatterplot_item.setPen([mkPen(9), mkPen(10)])\n        scatterplot_item.setBrush([11, 12])\n        data[\"data\"] = np.array([13, 14])\n\n        xy[0][0] = 0\n        graph.update_coordinates()\n        np.testing.assert_almost_equal(graph.scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(graph.scatterplot_item_sel.getData(), xy)\n\n        # Graph updates coordinates instead of creating new items\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        self.assertIs(scatterplot_item_sel, graph.scatterplot_item_sel)\n        np.testing.assert_almost_equal(data[\"size\"], [5, 6])\n        np.testing.assert_almost_equal(data[\"symbol\"], [7, 8])\n        self.assertEqual(data[\"pen\"][0], mkPen(9))\n        self.assertEqual(data[\"pen\"][1], mkPen(10))\n        np.testing.assert_almost_equal(data[\"brush\"], [11, 12])\n        np.testing.assert_almost_equal(data[\"data\"], [13, 14])\n\n    def test_update_coordinates_and_labels(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1., 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 1.5\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 1.5)\n        xy[0][0] = 0  # This label goes out of the range\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 2)\n\n    def test_update_coordinates_and_density(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 0\n        graph.update_density = Mock()\n        graph.update_coordinates()\n        graph.update_density.assert_called_with()\n\n    def test_update_coordinates_reset_view(self):\n        graph = self.graph\n        graph.view_box.setRange = self.setRange\n        xy = self.xy = (np.array([2, 1]), np.array([3, 10]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(self.last_setRange, [[1, 2], [3, 10]])\n\n        xy[0][1] = 0\n        graph.update_coordinates()\n        self.assertEqual(self.last_setRange, [[0, 2], [3, 10]])\n\n    def test_reset_graph_no_data(self):\n        self.xy = (None, None)\n        self.graph.scatterplot_item = ScatterPlotItem([1, 2], [3, 4])\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates_indices(self):\n        graph = self.graph\n        self.xy = (np.array([2, 1]), np.array([3, 10]))\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item.data[\"data\"], [0, 1])\n\n    def test_sampling(self):\n        graph = self.graph\n        master = self.master\n\n        # Enable sampling before getting the data\n        graph.set_sample_size(3)\n        xy = self.xy = (np.arange(10, dtype=float),\n                        np.arange(0, 30, 3, dtype=float))\n        d = np.arange(10, dtype=float)\n        master.get_size_data = lambda: d\n        master.get_shape_data = lambda: d % 5 if d is not None else None\n        master.get_color_data = lambda: d\n        master.get_label_data = lambda: \\\n            np.array([str(x) for x in d], dtype=object)\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n        # Check proper sampling\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertNotEqual(x[0], x[1])\n        self.assertNotEqual(x[0], x[2])\n        self.assertNotEqual(x[1], x[2])\n        np.testing.assert_almost_equal(3 * x, y)\n\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Check that sample is extended when sample size is changed\n        graph.set_sample_size(4)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s = data[\"size\"] - graph.MinShapeSize\n        precise_s = (x - min(x)) / (max(x) - min(x)) * max(s)\n        np.testing.assert_almost_equal(s, precise_s, decimal=0)\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Disable sampling\n        graph.set_sample_size(None)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        np.testing.assert_almost_equal(x, xy[0])\n        np.testing.assert_almost_equal(y, xy[1])\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in d])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in d])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in d])\n\n        # Enable sampling when data is already present and not sampled\n        graph.set_sample_size(3)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Update data when data is present and sampling is enabled\n        xy[0][:] = np.arange(9, -1, -1, dtype=float)\n        d = xy[0]\n        graph.update_coordinates()\n        x1, _ = scatterplot_item.getData()\n        np.testing.assert_almost_equal(9 - x, x1)\n        graph.update_sizes()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Reset graph when data is present and sampling is enabled\n        self.xy = (np.arange(100, 105, dtype=float),\n                   np.arange(100, 105, dtype=float))\n        d = self.xy[0] - 100\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertTrue(np.all(x > 99))\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Don't sample when unnecessary\n        self.xy = (np.arange(100, dtype=float), ) * 2\n        d = None\n        delattr(master, \"get_label_data\")\n        graph.reset_graph()\n        graph.set_sample_size(120)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_almost_equal(x, np.arange(100))\n\n    def test_sampling_keeps_selection(self):\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n        graph.reset_graph()\n        graph.select_by_indices(np.arange(1, 100, 2))\n        graph.set_sample_size(30)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n        graph.set_sample_size(None)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n\n    base = \"Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase.\"\n\n    @patch(base + \"update_sizes\")\n    @patch(base + \"update_colors\")\n    @patch(base + \"update_selection_colors\")\n    @patch(base + \"update_shapes\")\n    @patch(base + \"update_labels\")\n    def test_reset_calls_all_updates_and_update_doesnt(self, *mocks):\n        master = MockWidget()\n        graph = OWScatterPlotBase(master)\n        for mock in mocks:\n            mock.assert_not_called()\n\n        graph.reset_graph()\n        for mock in mocks:\n            mock.assert_called_with()\n            mock.reset_mock()\n\n        graph.update_coordinates()\n        for mock in mocks:\n            mock.assert_not_called()\n\n    def test_jittering(self):\n        graph = self.graph\n        graph.jitter_size = 10\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        a10 = np.arange(10)\n        self.assertTrue(np.any(np.nonzero(a10 - x)))\n        self.assertTrue(np.any(np.nonzero(a10 - y)))\n        np.testing.assert_array_less(a10 - x, 1)\n        np.testing.assert_array_less(a10 - y, 1)\n\n        graph.jitter_size = 0\n        graph.update_coordinates()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_equal(a10, x)\n\n    def test_size_normalization(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, [6, 7.5, 9.5, 11, 12.5, 14.5, 16, 17.5, 19.5, 21])\n\n        d = np.arange(10, 20, dtype=float)\n        graph.update_sizes()\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        size2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, size2)\n\n    def test_size_rounding_half_pixel(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size*2 - (size*2).round(), 0)\n\n    def test_size_with_nans(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n\n        d[4] = np.nan\n        graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        sizes2 = scatterplot_item.data[\"size\"]\n\n        self.assertEqual(sizes[1] - sizes[0], sizes2[1] - sizes2[0])\n        self.assertLess(sizes2[4], self.graph.MinShapeSize)\n\n        d[:] = np.nan\n        graph.update_sizes()\n        sizes3 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes3)\n\n    def test_sizes_all_same_or_nan(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.full((10, ), 3.0)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n        self.assertEqual(len(set(sizes)), 1)\n        self.assertGreater(sizes[0], self.graph.MinShapeSize)\n\n        d = None\n        graph.update_sizes()\n        scatterplot_item = graph.scatterplot_item\n        sizes2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes2)\n\n    def test_sizes_point_width_is_linear(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.point_width = 1\n        graph.reset_graph()\n        sizes1 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 2\n        graph.update_sizes()\n        sizes2 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 3\n        graph.update_sizes()\n        sizes3 = graph.scatterplot_item.data[\"size\"]\n\n        np.testing.assert_almost_equal(2 * (sizes2 - sizes1), sizes3 - sizes1)\n\n    def test_sizes_custom_imputation(self):\n\n        def impute_max(size_data):\n            size_data[np.isnan(size_data)] = np.nanmax(size_data)\n\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        self.master.impute_sizes = impute_max\n        d = np.arange(10, dtype=float)\n        d[4] = np.nan\n        graph.reset_graph()\n        sizes = graph.scatterplot_item.data[\"size\"]\n        self.assertAlmostEqual(sizes[4], sizes[9])\n\n    def test_sizes_selection(self):\n        graph = self.graph\n        graph.get_size = lambda: np.arange(10, dtype=float)\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item_sel.data[\"size\"]\n            - graph.scatterplot_item.data[\"size\"],\n            SELECTION_WIDTH)\n\n    @patch(\"Orange.widgets.visualize.owscatterplotgraph\"\n           \".MAX_N_VALID_SIZE_ANIMATE\", 5)\n    def test_size_animation(self):\n        begin_resizing = QSignalSpy(self.graph.begin_resizing)\n        step_resizing = QSignalSpy(self.graph.step_resizing)\n        end_resizing = QSignalSpy(self.graph.end_resizing)\n        self._update_sizes_for_points(5)\n        # first end_resizing is triggered in reset, thus wait for step_resizing\n        step_resizing.wait(200)\n        end_resizing.wait(200)\n        self.assertEqual(len(begin_resizing), 2)  # reset and update\n        self.assertEqual(len(step_resizing), 5)\n        self.assertEqual(len(end_resizing), 2)  # reset and update\n        self.assertEqual(self.graph.scatterplot_item.setSize.call_count, 6)\n        self._update_sizes_for_points(6)\n        self.graph.scatterplot_item.setSize.assert_called_once()\n\n    def _update_sizes_for_points(self, n: int):\n        arr = np.arange(n, dtype=float)\n        self.master.get_coordinates_data = lambda: (arr, arr)\n        self.master.get_size_data = lambda: arr\n        self.graph.reset_graph()\n        self.graph.scatterplot_item.setSize = Mock(\n            wraps=self.graph.scatterplot_item.setSize)\n        self.master.get_size_data = lambda: arr[::-1]\n        self.graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n    def test_colors_discrete(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        self.master.get_color_data = lambda: d\n        d = np.arange(10, dtype=float) % 2\n\n        graph.reset_graph()\n        data = graph.scatterplot_item.data\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"pen\"])))\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"brush\"])))\n\n        # confirm that QPen/QBrush were reused\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 2)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)\n\n    def test_colors_discrete_nan(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        self.assertEqual(pens[0].color().hue(), palette[0].hue())\n        self.assertEqual(pens[1].color().hue(), palette[1].hue())\n        self.assertEqual(brushes[0].color().hue(), palette[0].hue())\n        self.assertEqual(brushes[1].color().hue(), palette[1].hue())\n        self.assertEqual(pens[4].color().hue(), QColor(128, 128, 128).hue())\n        self.assertEqual(brushes[4].color().hue(), QColor(128, 128, 128).hue())\n\n    def test_colors_continuous(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()  # I don't have a good test ... just don't crash\n\n        d[4] = np.nan\n        graph.update_colors()  # Ditto\n\n    def test_colors_continuous_reused(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n\n        d = np.arange(100, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n\n        data = graph.scatterplot_item.data\n\n        self.assertEqual(len(data[\"pen\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"pen\"]))), 10)\n        self.assertEqual(len(data[\"brush\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"brush\"]))), 10)\n\n    def test_colors_continuous_nan(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        nan_color = QColor(*NAN_GREY)\n        self.assertEqual(pens[4].color().hue(), nan_color.hue())\n        self.assertEqual(brushes[4].color().hue(), nan_color.hue())\n\n    def test_colors_subset(self):\n        def run_tests():\n            self.master.get_subset_mask = lambda: None\n\n            graph.alpha_value = 42\n            graph.reset_graph()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 42)\n            self.assertEqual(brushes[1].color().alpha(), 42)\n            self.assertEqual(brushes[4].color().alpha(), 42)\n\n            graph.alpha_value = 123\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 123)\n            self.assertEqual(brushes[1].color().alpha(), 123)\n            self.assertEqual(brushes[4].color().alpha(), 123)\n\n            self.master.get_subset_mask = lambda: np.arange(10) >= 5\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 0)\n            self.assertEqual(brushes[1].color().alpha(), 0)\n            self.assertEqual(brushes[4].color().alpha(), 0)\n            self.assertEqual(brushes[5].color().alpha(), 255)\n            self.assertEqual(brushes[6].color().alpha(), 255)\n            self.assertEqual(brushes[7].color().alpha(), 255)\n\n        graph = self.graph\n\n        self.master.get_color_data = lambda: None\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n        d = np.arange(10, dtype=float) % 2\n        d[4:6] = np.nan\n        self.master.get_color_data = lambda: d\n\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n    def test_colors_none(self):\n        graph = self.graph\n        graph.reset_graph()\n        hue = QColor(128, 128, 128).hue()\n\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)  # test QPen/QBrush reuse\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 1)\n\n        self.master.get_subset_mask = lambda: np.arange(10) < 5\n        graph.update_colors()\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)  # transparent and colored\n\n    def test_colors_update_legend_and_density(self):\n        graph = self.graph\n        graph.update_legends = Mock()\n        graph.update_density = Mock()\n        graph.reset_graph()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n        graph.update_legends.reset_mock()\n        graph.update_density.reset_mock()\n\n        graph.update_coordinates()\n        graph.update_legends.assert_not_called()\n\n        graph.update_colors()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n    def test_selection_colors(self):\n        graph = self.graph\n        graph.reset_graph()\n        data = graph.scatterplot_item_sel.data\n\n        # One group\n        graph.select_by_indices(np.array([0, 1, 2, 3]))\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(4):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(4, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n\n        # Two groups\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_indices(np.array([4, 5, 6]))\n\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(7):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(7, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n        self.assertEqual(len({pen.color().hue() for pen in pens[:4]}), 1)\n        self.assertEqual(len({pen.color().hue() for pen in pens[4:7]}), 1)\n        color1 = pens[3].color().hue()\n        color2 = pens[4].color().hue()\n        self.assertNotEqual(color1, color2)\n\n        # Two groups + sampling\n        graph.set_sample_size(7)\n        x = graph.scatterplot_item.getData()[0]\n        pens = graph.scatterplot_item_sel.data[\"pen\"]\n        for xi, pen in zip(x, pens):\n            if xi < 4:\n                self.assertEqual(pen.color().hue(), color1)\n            elif xi < 7:\n                self.assertEqual(pen.color().hue(), color2)\n            else:\n                self.assertEqual(pen.style(), Qt.NoPen)\n\n    def test_density(self):\n        graph = self.graph\n        density = object()\n        with patch(\"Orange.widgets.utils.classdensity.class_density_image\",\n                   return_value=density):\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n\n            graph.plot_widget.addItem = Mock()\n            graph.plot_widget.removeItem = Mock()\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.ones((10, ), dtype=float)\n            self.master.get_color_data = lambda: d\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.arange(10) % 2\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.class_density = False\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.update_coordinates = lambda: (None, None)\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n    def test_labels(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n\n        # Label only selected\n        selected = [1, 3, 5]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(x) for x in selected])\n        x, y = graph.scatterplot_item.getData()\n        for i, index in enumerate(selected):\n            self.assertEqual(x[index], graph.labels[i].x())\n            self.assertEqual(y[index], graph.labels[i].y())\n\n        # Disable label only selected\n        self.graph.label_only_selected = False\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        # Label only selected + sampling\n        selected = [1, 3, 4, 5, 6, 7, 9]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        graph.set_sample_size(5)\n        for label in graph.labels:\n            ind = int(label.textItem.toPlainText())\n            self.assertIn(ind, selected)\n            self.assertEqual(label.x(), x[ind])\n            self.assertEqual(label.y(), y[ind])\n\n    def test_label_mask_all_visible(self):\n        graph = self.graph\n\n        x, y = np.arange(10) / 10, np.arange(10) / 10\n        sel = np.array(\n            [True, True, False, False, False, True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False, True, True, False, False, False])\n        trues = np.ones(10, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel)\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), np.array(\n            [True, True, True, True, False, True, True, True, False, False]\n        ))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset)\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5, 10) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, False, True])\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        trues = np.ones(5, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel[5:])\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([True, True, True, False, True]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset[5:])\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible_and_view(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])  # first and last out of the view\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, True, True])  # first and last out of the view\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        graph.view_box.viewRange = lambda: ((0.6, 1), (0, 0.3))\n        viewed = np.array([False, True, True, True, False])\n\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, False, False]))\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, True, False]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, False, True, False]))\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_labels_observes_mask(self):\n        graph = self.graph\n        get_label_data = graph.master.get_label_data\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        get_label_data.reset_mock()\n        graph._label_mask = lambda *_: None\n        graph.update_labels()\n        get_label_data.assert_not_called()\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph._label_mask = \\\n            lambda *_: np.array([False, True, True] + [False] * 7)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [\"1\", \"2\"])\n\n    def test_labels_update_coordinates(self):\n        graph = self.graph\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n\n        graph.reset_graph()\n        graph.set_sample_size(7)\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        self.master.get_coordinates_data = \\\n            lambda: (np.arange(10, 20), np.arange(50, 60))\n        graph.update_coordinates()\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n    def test_shapes(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 3]\n                            for i, symbol in enumerate(symbols)))\n\n        d = np.arange(10, dtype=float) % 2\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 2]\n                            for i, symbol in enumerate(symbols)))\n\n        d = None\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertEqual(len(set(symbols)), 1)\n\n    def test_shapes_nan(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n\n        graph.reset_graph()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2], '?')\n\n        d[:] = np.nan\n        graph.update_shapes()\n        self.assertTrue(\n            all(symbol == '?'\n                for symbol in graph.scatterplot_item.data[\"symbol\"]))\n\n        def impute0(data, _):\n            data[np.isnan(data)] = 0\n\n        self.master.impute_shapes = impute0\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n        graph.update_shapes()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2],\n                         graph.CurveSymbols[0])\n\n    def test_show_grid(self):\n        graph = self.graph\n        show_grid = self.graph.plot_widget.showGrid = Mock()\n        graph.show_grid = False\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=False, y=False))\n\n        graph.show_grid = True\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=True, y=True))\n\n    def test_show_legend(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        shape_labels = color_labels = None  # Avoid pylint warning\n        self.master.get_shape_labels = lambda: shape_labels\n        self.master.get_color_labels = lambda: color_labels\n        for shape_labels in (None, [\"a\", \"b\"]):\n            for color_labels in (None, [\"c\", \"d\"], None):\n                for visible in (True, False, True):\n                    graph.show_legend = visible\n                    graph.update_legends()\n                    self.assertIs(\n                        shape_legend.call_args[0][0],\n                        visible and bool(shape_labels),\n                        msg=\"error at {}, {}\".format(visible, shape_labels))\n                    self.assertIs(\n                        color_legend.call_args[0][0],\n                        visible and bool(color_labels),\n                        msg=\"error at {}, {}\".format(visible, color_labels))\n\n    def test_show_legend_no_data(self):\n        graph = self.graph\n        self.master.get_shape_labels = lambda: [\"a\", \"b\"]\n        self.master.get_color_labels = lambda: [\"c\", \"d\"]\n        self.master.get_shape_data = lambda: np.arange(10) % 2\n        self.master.get_color_data = lambda: np.arange(10) < 6\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        self.master.get_coordinates_data = lambda: (None, None)\n        graph.reset_graph()\n        self.assertFalse(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n\n    def test_legend_combine(self):\n        master = self.master\n        graph = self.graph\n\n        master.get_shape_data = lambda: np.arange(10, dtype=float) % 3\n        master.get_color_data = lambda: 2 * np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n\n        master.get_shape_labels = lambda: [\"a\", \"b\"]\n        master.get_color_labels = lambda: [\"c\", \"d\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n\n        master.get_color_labels = lambda: [\"a\", \"b\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.get_color_data = lambda: np.arange(10, dtype=float) % 3\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.is_continuous_color = lambda: True\n        master.get_color_data = lambda: np.arange(10, dtype=float)\n        master.get_color_labels = lambda: None\n        graph.update_colors()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n    def test_select_by_click(self):\n        graph = self.graph\n        graph.reset_graph()\n        points = graph.scatterplot_item.points()\n        graph.select_by_click(None, [points[2]])\n        np.testing.assert_almost_equal(graph.get_selection(), [2])\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_click(None, points[3:6])\n        np.testing.assert_almost_equal(\n            list(graph.get_selection()), [2, 3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 1, 2, 2, 2, 0, 0, 0, 0])\n\n    def test_select_by_rectangle(self):\n        graph = self.graph\n        coords = np.array(\n            [(x, y) for y in range(10) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n\n        graph.reset_graph()\n        graph.select_by_rectangle(QRectF(3, 5, 3.9, 2.9))\n        self.assertTrue(\n            all(selected == (3 <= coords[0][i] <= 6 and 5 <= coords[1][i] <= 7)\n                for i, selected in enumerate(graph.selection)))\n\n    def test_select_by_indices(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        def select(modifiers, indices):\n            with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                       lambda: modifiers):\n                graph.update_selection_colors = Mock()\n                graph.update_labels = Mock()\n                self.master.selection_changed = Mock()\n\n                graph.select_by_indices(np.array(indices))\n                graph.update_selection_colors.assert_called_with()\n                if graph.label_only_selected:\n                    graph.update_labels.assert_called_with()\n                else:\n                    graph.update_labels.assert_not_called()\n                self.master.selection_changed.assert_called_with()\n\n        select(0, [7, 8, 9])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 0, 0, 1, 1, 1])\n\n        select(Qt.ShiftModifier | Qt.ControlModifier, [5, 6])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 1, 1, 1, 1, 1])\n\n        select(Qt.ShiftModifier, [3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 2, 2, 2, 1, 1, 1, 1])\n\n        select(Qt.AltModifier, [1, 3, 7])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 2, 2, 1, 0, 1, 1])\n\n        select(0, [1, 8])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 1, 0, 0, 0, 0, 0, 0, 1, 0])\n\n        graph.label_only_selected = False\n        select(0, [3, 4])\n\n    def test_unselect_all(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        graph.select_by_indices([3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 1, 1, 1, 0, 0, 0, 0])\n\n        graph.update_selection_colors = Mock()\n        graph.update_labels = Mock()\n        self.master.selection_changed = Mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_called_with()\n        graph.update_labels.assert_called_with()\n        self.master.selection_changed.assert_called_with()\n\n        graph.update_selection_colors.reset_mock()\n        graph.update_labels.reset_mock()\n        self.master.selection_changed.reset_mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_not_called()\n        graph.update_labels.assert_not_called()\n        self.master.selection_changed.assert_not_called()\n\n    def test_hiding_too_many_labels(self):\n        spy = QSignalSpy(self.graph.too_many_labels)\n        self.graph.MAX_VISIBLE_LABELS = 5\n\n        graph = self.graph\n        coords = np.array(\n            [(x, 0) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n        graph.reset_graph()\n\n        self.assertFalse(spy and spy[-1][0])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 4, 4))\n        graph.view_box.sigRangeChangedManually.emit(((1, 5), (-1, 3)))\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 8, 8))\n        graph.view_box.sigRangeChangedManually.emit(((1, 9), (-1, 7)))\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.label_only_selected = True\n        graph.update_labels()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3, 4, 5, 6])\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3])\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.label_only_selected = False\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.clear()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n    def test_no_needless_buildatlas(self):\n        graph = self.graph\n        graph.reset_graph()\n        self.assertIsNone(graph.scatterplot_item.fragmentAtlas.atlas)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 49,
                            "end_lineno": 1294,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1119,
                            "length": 6
                        },
                        "new_range": {
                            "start": 1123,
                            "length": 12
                        },
                        "section": "class TestOWScatterPlotBase(WidgetTest):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        master.get_color_labels = lambda: [\"a\", \"b\"]",
                                "type": "context"
                            },
                            {
                                "content": "        graph.update_legends()",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertTrue(shape_legend.call_args[0][0])",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertTrue(color_legend.call_args[0][0])",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(len(graph.shape_legend.items), 2)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        master.get_color_data = lambda: np.arange(10, dtype=float) % 3",
                                "type": "added"
                            },
                            {
                                "content": "        graph.update_legends()",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertTrue(shape_legend.call_args[0][0])",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertFalse(color_legend.call_args[0][0])",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(len(graph.shape_legend.items), 2)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/visualize/tests/test_owscatterplotbase.py",
                            "type": "method",
                            "name": "TestOWScatterPlotBase.test_legend_combine",
                            "content": "class TestOWScatterPlotBase(WidgetTest):\n    def setUp(self):\n        self.master = MockWidget()\n        self.graph = OWScatterPlotBase(self.master)\n\n        self.xy = (np.arange(10, dtype=float), np.arange(10, dtype=float))\n        self.master.get_coordinates_data = lambda: self.xy\n\n    # pylint: disable=keyword-arg-before-vararg\n    def setRange(self, rect=None, *_, **__):\n        if isinstance(rect, QRectF):\n            self.last_setRange = [[rect.left(), rect.right()],\n                                  [rect.top(), rect.bottom()]]\n\n    def test_update_coordinates_no_data(self):\n        self.xy = None, None\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n        self.xy = [], []\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        graph.reset_graph()\n\n        scatterplot_item = graph.scatterplot_item\n        scatterplot_item_sel = graph.scatterplot_item_sel\n        data = scatterplot_item.data\n\n        np.testing.assert_almost_equal(scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(scatterplot_item_sel.getData(), xy)\n        scatterplot_item.setSize([5, 6])\n        scatterplot_item.setSymbol([7, 8])\n        scatterplot_item.setPen([mkPen(9), mkPen(10)])\n        scatterplot_item.setBrush([11, 12])\n        data[\"data\"] = np.array([13, 14])\n\n        xy[0][0] = 0\n        graph.update_coordinates()\n        np.testing.assert_almost_equal(graph.scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(graph.scatterplot_item_sel.getData(), xy)\n\n        # Graph updates coordinates instead of creating new items\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        self.assertIs(scatterplot_item_sel, graph.scatterplot_item_sel)\n        np.testing.assert_almost_equal(data[\"size\"], [5, 6])\n        np.testing.assert_almost_equal(data[\"symbol\"], [7, 8])\n        self.assertEqual(data[\"pen\"][0], mkPen(9))\n        self.assertEqual(data[\"pen\"][1], mkPen(10))\n        np.testing.assert_almost_equal(data[\"brush\"], [11, 12])\n        np.testing.assert_almost_equal(data[\"data\"], [13, 14])\n\n    def test_update_coordinates_and_labels(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1., 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 1.5\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 1.5)\n        xy[0][0] = 0  # This label goes out of the range\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 2)\n\n    def test_update_coordinates_and_density(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 0\n        graph.update_density = Mock()\n        graph.update_coordinates()\n        graph.update_density.assert_called_with()\n\n    def test_update_coordinates_reset_view(self):\n        graph = self.graph\n        graph.view_box.setRange = self.setRange\n        xy = self.xy = (np.array([2, 1]), np.array([3, 10]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(self.last_setRange, [[1, 2], [3, 10]])\n\n        xy[0][1] = 0\n        graph.update_coordinates()\n        self.assertEqual(self.last_setRange, [[0, 2], [3, 10]])\n\n    def test_reset_graph_no_data(self):\n        self.xy = (None, None)\n        self.graph.scatterplot_item = ScatterPlotItem([1, 2], [3, 4])\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates_indices(self):\n        graph = self.graph\n        self.xy = (np.array([2, 1]), np.array([3, 10]))\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item.data[\"data\"], [0, 1])\n\n    def test_sampling(self):\n        graph = self.graph\n        master = self.master\n\n        # Enable sampling before getting the data\n        graph.set_sample_size(3)\n        xy = self.xy = (np.arange(10, dtype=float),\n                        np.arange(0, 30, 3, dtype=float))\n        d = np.arange(10, dtype=float)\n        master.get_size_data = lambda: d\n        master.get_shape_data = lambda: d % 5 if d is not None else None\n        master.get_color_data = lambda: d\n        master.get_label_data = lambda: \\\n            np.array([str(x) for x in d], dtype=object)\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n        # Check proper sampling\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertNotEqual(x[0], x[1])\n        self.assertNotEqual(x[0], x[2])\n        self.assertNotEqual(x[1], x[2])\n        np.testing.assert_almost_equal(3 * x, y)\n\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Check that sample is extended when sample size is changed\n        graph.set_sample_size(4)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s = data[\"size\"] - graph.MinShapeSize\n        precise_s = (x - min(x)) / (max(x) - min(x)) * max(s)\n        np.testing.assert_almost_equal(s, precise_s, decimal=0)\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Disable sampling\n        graph.set_sample_size(None)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        np.testing.assert_almost_equal(x, xy[0])\n        np.testing.assert_almost_equal(y, xy[1])\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in d])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in d])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in d])\n\n        # Enable sampling when data is already present and not sampled\n        graph.set_sample_size(3)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Update data when data is present and sampling is enabled\n        xy[0][:] = np.arange(9, -1, -1, dtype=float)\n        d = xy[0]\n        graph.update_coordinates()\n        x1, _ = scatterplot_item.getData()\n        np.testing.assert_almost_equal(9 - x, x1)\n        graph.update_sizes()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Reset graph when data is present and sampling is enabled\n        self.xy = (np.arange(100, 105, dtype=float),\n                   np.arange(100, 105, dtype=float))\n        d = self.xy[0] - 100\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertTrue(np.all(x > 99))\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Don't sample when unnecessary\n        self.xy = (np.arange(100, dtype=float), ) * 2\n        d = None\n        delattr(master, \"get_label_data\")\n        graph.reset_graph()\n        graph.set_sample_size(120)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_almost_equal(x, np.arange(100))\n\n    def test_sampling_keeps_selection(self):\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n        graph.reset_graph()\n        graph.select_by_indices(np.arange(1, 100, 2))\n        graph.set_sample_size(30)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n        graph.set_sample_size(None)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n\n    base = \"Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase.\"\n\n    @patch(base + \"update_sizes\")\n    @patch(base + \"update_colors\")\n    @patch(base + \"update_selection_colors\")\n    @patch(base + \"update_shapes\")\n    @patch(base + \"update_labels\")\n    def test_reset_calls_all_updates_and_update_doesnt(self, *mocks):\n        master = MockWidget()\n        graph = OWScatterPlotBase(master)\n        for mock in mocks:\n            mock.assert_not_called()\n\n        graph.reset_graph()\n        for mock in mocks:\n            mock.assert_called_with()\n            mock.reset_mock()\n\n        graph.update_coordinates()\n        for mock in mocks:\n            mock.assert_not_called()\n\n    def test_jittering(self):\n        graph = self.graph\n        graph.jitter_size = 10\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        a10 = np.arange(10)\n        self.assertTrue(np.any(np.nonzero(a10 - x)))\n        self.assertTrue(np.any(np.nonzero(a10 - y)))\n        np.testing.assert_array_less(a10 - x, 1)\n        np.testing.assert_array_less(a10 - y, 1)\n\n        graph.jitter_size = 0\n        graph.update_coordinates()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_equal(a10, x)\n\n    def test_size_normalization(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, [6, 7.5, 9.5, 11, 12.5, 14.5, 16, 17.5, 19.5, 21])\n\n        d = np.arange(10, 20, dtype=float)\n        graph.update_sizes()\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        size2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, size2)\n\n    def test_size_rounding_half_pixel(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size*2 - (size*2).round(), 0)\n\n    def test_size_with_nans(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n\n        d[4] = np.nan\n        graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        sizes2 = scatterplot_item.data[\"size\"]\n\n        self.assertEqual(sizes[1] - sizes[0], sizes2[1] - sizes2[0])\n        self.assertLess(sizes2[4], self.graph.MinShapeSize)\n\n        d[:] = np.nan\n        graph.update_sizes()\n        sizes3 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes3)\n\n    def test_sizes_all_same_or_nan(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.full((10, ), 3.0)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n        self.assertEqual(len(set(sizes)), 1)\n        self.assertGreater(sizes[0], self.graph.MinShapeSize)\n\n        d = None\n        graph.update_sizes()\n        scatterplot_item = graph.scatterplot_item\n        sizes2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes2)\n\n    def test_sizes_point_width_is_linear(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.point_width = 1\n        graph.reset_graph()\n        sizes1 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 2\n        graph.update_sizes()\n        sizes2 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 3\n        graph.update_sizes()\n        sizes3 = graph.scatterplot_item.data[\"size\"]\n\n        np.testing.assert_almost_equal(2 * (sizes2 - sizes1), sizes3 - sizes1)\n\n    def test_sizes_custom_imputation(self):\n\n        def impute_max(size_data):\n            size_data[np.isnan(size_data)] = np.nanmax(size_data)\n\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        self.master.impute_sizes = impute_max\n        d = np.arange(10, dtype=float)\n        d[4] = np.nan\n        graph.reset_graph()\n        sizes = graph.scatterplot_item.data[\"size\"]\n        self.assertAlmostEqual(sizes[4], sizes[9])\n\n    def test_sizes_selection(self):\n        graph = self.graph\n        graph.get_size = lambda: np.arange(10, dtype=float)\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item_sel.data[\"size\"]\n            - graph.scatterplot_item.data[\"size\"],\n            SELECTION_WIDTH)\n\n    @patch(\"Orange.widgets.visualize.owscatterplotgraph\"\n           \".MAX_N_VALID_SIZE_ANIMATE\", 5)\n    def test_size_animation(self):\n        begin_resizing = QSignalSpy(self.graph.begin_resizing)\n        step_resizing = QSignalSpy(self.graph.step_resizing)\n        end_resizing = QSignalSpy(self.graph.end_resizing)\n        self._update_sizes_for_points(5)\n        # first end_resizing is triggered in reset, thus wait for step_resizing\n        step_resizing.wait(200)\n        end_resizing.wait(200)\n        self.assertEqual(len(begin_resizing), 2)  # reset and update\n        self.assertEqual(len(step_resizing), 5)\n        self.assertEqual(len(end_resizing), 2)  # reset and update\n        self.assertEqual(self.graph.scatterplot_item.setSize.call_count, 6)\n        self._update_sizes_for_points(6)\n        self.graph.scatterplot_item.setSize.assert_called_once()\n\n    def _update_sizes_for_points(self, n: int):\n        arr = np.arange(n, dtype=float)\n        self.master.get_coordinates_data = lambda: (arr, arr)\n        self.master.get_size_data = lambda: arr\n        self.graph.reset_graph()\n        self.graph.scatterplot_item.setSize = Mock(\n            wraps=self.graph.scatterplot_item.setSize)\n        self.master.get_size_data = lambda: arr[::-1]\n        self.graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n    def test_colors_discrete(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        self.master.get_color_data = lambda: d\n        d = np.arange(10, dtype=float) % 2\n\n        graph.reset_graph()\n        data = graph.scatterplot_item.data\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"pen\"])))\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"brush\"])))\n\n        # confirm that QPen/QBrush were reused\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 2)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)\n\n    def test_colors_discrete_nan(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        self.assertEqual(pens[0].color().hue(), palette[0].hue())\n        self.assertEqual(pens[1].color().hue(), palette[1].hue())\n        self.assertEqual(brushes[0].color().hue(), palette[0].hue())\n        self.assertEqual(brushes[1].color().hue(), palette[1].hue())\n        self.assertEqual(pens[4].color().hue(), QColor(128, 128, 128).hue())\n        self.assertEqual(brushes[4].color().hue(), QColor(128, 128, 128).hue())\n\n    def test_colors_continuous(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()  # I don't have a good test ... just don't crash\n\n        d[4] = np.nan\n        graph.update_colors()  # Ditto\n\n    def test_colors_continuous_reused(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n\n        d = np.arange(100, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n\n        data = graph.scatterplot_item.data\n\n        self.assertEqual(len(data[\"pen\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"pen\"]))), 10)\n        self.assertEqual(len(data[\"brush\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"brush\"]))), 10)\n\n    def test_colors_continuous_nan(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        nan_color = QColor(*NAN_GREY)\n        self.assertEqual(pens[4].color().hue(), nan_color.hue())\n        self.assertEqual(brushes[4].color().hue(), nan_color.hue())\n\n    def test_colors_subset(self):\n        def run_tests():\n            self.master.get_subset_mask = lambda: None\n\n            graph.alpha_value = 42\n            graph.reset_graph()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 42)\n            self.assertEqual(brushes[1].color().alpha(), 42)\n            self.assertEqual(brushes[4].color().alpha(), 42)\n\n            graph.alpha_value = 123\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 123)\n            self.assertEqual(brushes[1].color().alpha(), 123)\n            self.assertEqual(brushes[4].color().alpha(), 123)\n\n            self.master.get_subset_mask = lambda: np.arange(10) >= 5\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 0)\n            self.assertEqual(brushes[1].color().alpha(), 0)\n            self.assertEqual(brushes[4].color().alpha(), 0)\n            self.assertEqual(brushes[5].color().alpha(), 255)\n            self.assertEqual(brushes[6].color().alpha(), 255)\n            self.assertEqual(brushes[7].color().alpha(), 255)\n\n        graph = self.graph\n\n        self.master.get_color_data = lambda: None\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n        d = np.arange(10, dtype=float) % 2\n        d[4:6] = np.nan\n        self.master.get_color_data = lambda: d\n\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n    def test_colors_none(self):\n        graph = self.graph\n        graph.reset_graph()\n        hue = QColor(128, 128, 128).hue()\n\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)  # test QPen/QBrush reuse\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 1)\n\n        self.master.get_subset_mask = lambda: np.arange(10) < 5\n        graph.update_colors()\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)  # transparent and colored\n\n    def test_colors_update_legend_and_density(self):\n        graph = self.graph\n        graph.update_legends = Mock()\n        graph.update_density = Mock()\n        graph.reset_graph()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n        graph.update_legends.reset_mock()\n        graph.update_density.reset_mock()\n\n        graph.update_coordinates()\n        graph.update_legends.assert_not_called()\n\n        graph.update_colors()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n    def test_selection_colors(self):\n        graph = self.graph\n        graph.reset_graph()\n        data = graph.scatterplot_item_sel.data\n\n        # One group\n        graph.select_by_indices(np.array([0, 1, 2, 3]))\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(4):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(4, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n\n        # Two groups\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_indices(np.array([4, 5, 6]))\n\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(7):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(7, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n        self.assertEqual(len({pen.color().hue() for pen in pens[:4]}), 1)\n        self.assertEqual(len({pen.color().hue() for pen in pens[4:7]}), 1)\n        color1 = pens[3].color().hue()\n        color2 = pens[4].color().hue()\n        self.assertNotEqual(color1, color2)\n\n        # Two groups + sampling\n        graph.set_sample_size(7)\n        x = graph.scatterplot_item.getData()[0]\n        pens = graph.scatterplot_item_sel.data[\"pen\"]\n        for xi, pen in zip(x, pens):\n            if xi < 4:\n                self.assertEqual(pen.color().hue(), color1)\n            elif xi < 7:\n                self.assertEqual(pen.color().hue(), color2)\n            else:\n                self.assertEqual(pen.style(), Qt.NoPen)\n\n    def test_density(self):\n        graph = self.graph\n        density = object()\n        with patch(\"Orange.widgets.utils.classdensity.class_density_image\",\n                   return_value=density):\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n\n            graph.plot_widget.addItem = Mock()\n            graph.plot_widget.removeItem = Mock()\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.ones((10, ), dtype=float)\n            self.master.get_color_data = lambda: d\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.arange(10) % 2\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.class_density = False\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.update_coordinates = lambda: (None, None)\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n    def test_labels(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n\n        # Label only selected\n        selected = [1, 3, 5]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(x) for x in selected])\n        x, y = graph.scatterplot_item.getData()\n        for i, index in enumerate(selected):\n            self.assertEqual(x[index], graph.labels[i].x())\n            self.assertEqual(y[index], graph.labels[i].y())\n\n        # Disable label only selected\n        self.graph.label_only_selected = False\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        # Label only selected + sampling\n        selected = [1, 3, 4, 5, 6, 7, 9]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        graph.set_sample_size(5)\n        for label in graph.labels:\n            ind = int(label.textItem.toPlainText())\n            self.assertIn(ind, selected)\n            self.assertEqual(label.x(), x[ind])\n            self.assertEqual(label.y(), y[ind])\n\n    def test_label_mask_all_visible(self):\n        graph = self.graph\n\n        x, y = np.arange(10) / 10, np.arange(10) / 10\n        sel = np.array(\n            [True, True, False, False, False, True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False, True, True, False, False, False])\n        trues = np.ones(10, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel)\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), np.array(\n            [True, True, True, True, False, True, True, True, False, False]\n        ))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset)\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5, 10) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, False, True])\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        trues = np.ones(5, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel[5:])\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([True, True, True, False, True]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset[5:])\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible_and_view(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])  # first and last out of the view\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, True, True])  # first and last out of the view\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        graph.view_box.viewRange = lambda: ((0.6, 1), (0, 0.3))\n        viewed = np.array([False, True, True, True, False])\n\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, False, False]))\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, True, False]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, False, True, False]))\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_labels_observes_mask(self):\n        graph = self.graph\n        get_label_data = graph.master.get_label_data\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        get_label_data.reset_mock()\n        graph._label_mask = lambda *_: None\n        graph.update_labels()\n        get_label_data.assert_not_called()\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph._label_mask = \\\n            lambda *_: np.array([False, True, True] + [False] * 7)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [\"1\", \"2\"])\n\n    def test_labels_update_coordinates(self):\n        graph = self.graph\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n\n        graph.reset_graph()\n        graph.set_sample_size(7)\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        self.master.get_coordinates_data = \\\n            lambda: (np.arange(10, 20), np.arange(50, 60))\n        graph.update_coordinates()\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n    def test_shapes(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 3]\n                            for i, symbol in enumerate(symbols)))\n\n        d = np.arange(10, dtype=float) % 2\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 2]\n                            for i, symbol in enumerate(symbols)))\n\n        d = None\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertEqual(len(set(symbols)), 1)\n\n    def test_shapes_nan(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n\n        graph.reset_graph()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2], '?')\n\n        d[:] = np.nan\n        graph.update_shapes()\n        self.assertTrue(\n            all(symbol == '?'\n                for symbol in graph.scatterplot_item.data[\"symbol\"]))\n\n        def impute0(data, _):\n            data[np.isnan(data)] = 0\n\n        self.master.impute_shapes = impute0\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n        graph.update_shapes()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2],\n                         graph.CurveSymbols[0])\n\n    def test_show_grid(self):\n        graph = self.graph\n        show_grid = self.graph.plot_widget.showGrid = Mock()\n        graph.show_grid = False\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=False, y=False))\n\n        graph.show_grid = True\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=True, y=True))\n\n    def test_show_legend(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        shape_labels = color_labels = None  # Avoid pylint warning\n        self.master.get_shape_labels = lambda: shape_labels\n        self.master.get_color_labels = lambda: color_labels\n        for shape_labels in (None, [\"a\", \"b\"]):\n            for color_labels in (None, [\"c\", \"d\"], None):\n                for visible in (True, False, True):\n                    graph.show_legend = visible\n                    graph.update_legends()\n                    self.assertIs(\n                        shape_legend.call_args[0][0],\n                        visible and bool(shape_labels),\n                        msg=\"error at {}, {}\".format(visible, shape_labels))\n                    self.assertIs(\n                        color_legend.call_args[0][0],\n                        visible and bool(color_labels),\n                        msg=\"error at {}, {}\".format(visible, color_labels))\n\n    def test_show_legend_no_data(self):\n        graph = self.graph\n        self.master.get_shape_labels = lambda: [\"a\", \"b\"]\n        self.master.get_color_labels = lambda: [\"c\", \"d\"]\n        self.master.get_shape_data = lambda: np.arange(10) % 2\n        self.master.get_color_data = lambda: np.arange(10) < 6\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        self.master.get_coordinates_data = lambda: (None, None)\n        graph.reset_graph()\n        self.assertFalse(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n\n    def test_legend_combine(self):\n        master = self.master\n        graph = self.graph\n\n        master.get_shape_data = lambda: np.arange(10, dtype=float) % 3\n        master.get_color_data = lambda: 2 * np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n\n        master.get_shape_labels = lambda: [\"a\", \"b\"]\n        master.get_color_labels = lambda: [\"c\", \"d\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n\n        master.get_color_labels = lambda: [\"a\", \"b\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.get_color_data = lambda: np.arange(10, dtype=float) % 3\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.is_continuous_color = lambda: True\n        master.get_color_data = lambda: np.arange(10, dtype=float)\n        master.get_color_labels = lambda: None\n        graph.update_colors()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n    def test_select_by_click(self):\n        graph = self.graph\n        graph.reset_graph()\n        points = graph.scatterplot_item.points()\n        graph.select_by_click(None, [points[2]])\n        np.testing.assert_almost_equal(graph.get_selection(), [2])\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_click(None, points[3:6])\n        np.testing.assert_almost_equal(\n            list(graph.get_selection()), [2, 3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 1, 2, 2, 2, 0, 0, 0, 0])\n\n    def test_select_by_rectangle(self):\n        graph = self.graph\n        coords = np.array(\n            [(x, y) for y in range(10) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n\n        graph.reset_graph()\n        graph.select_by_rectangle(QRectF(3, 5, 3.9, 2.9))\n        self.assertTrue(\n            all(selected == (3 <= coords[0][i] <= 6 and 5 <= coords[1][i] <= 7)\n                for i, selected in enumerate(graph.selection)))\n\n    def test_select_by_indices(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        def select(modifiers, indices):\n            with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                       lambda: modifiers):\n                graph.update_selection_colors = Mock()\n                graph.update_labels = Mock()\n                self.master.selection_changed = Mock()\n\n                graph.select_by_indices(np.array(indices))\n                graph.update_selection_colors.assert_called_with()\n                if graph.label_only_selected:\n                    graph.update_labels.assert_called_with()\n                else:\n                    graph.update_labels.assert_not_called()\n                self.master.selection_changed.assert_called_with()\n\n        select(0, [7, 8, 9])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 0, 0, 1, 1, 1])\n\n        select(Qt.ShiftModifier | Qt.ControlModifier, [5, 6])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 1, 1, 1, 1, 1])\n\n        select(Qt.ShiftModifier, [3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 2, 2, 2, 1, 1, 1, 1])\n\n        select(Qt.AltModifier, [1, 3, 7])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 2, 2, 1, 0, 1, 1])\n\n        select(0, [1, 8])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 1, 0, 0, 0, 0, 0, 0, 1, 0])\n\n        graph.label_only_selected = False\n        select(0, [3, 4])\n\n    def test_unselect_all(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        graph.select_by_indices([3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 1, 1, 1, 0, 0, 0, 0])\n\n        graph.update_selection_colors = Mock()\n        graph.update_labels = Mock()\n        self.master.selection_changed = Mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_called_with()\n        graph.update_labels.assert_called_with()\n        self.master.selection_changed.assert_called_with()\n\n        graph.update_selection_colors.reset_mock()\n        graph.update_labels.reset_mock()\n        self.master.selection_changed.reset_mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_not_called()\n        graph.update_labels.assert_not_called()\n        self.master.selection_changed.assert_not_called()\n\n    def test_hiding_too_many_labels(self):\n        spy = QSignalSpy(self.graph.too_many_labels)\n        self.graph.MAX_VISIBLE_LABELS = 5\n\n        graph = self.graph\n        coords = np.array(\n            [(x, 0) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n        graph.reset_graph()\n\n        self.assertFalse(spy and spy[-1][0])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 4, 4))\n        graph.view_box.sigRangeChangedManually.emit(((1, 5), (-1, 3)))\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 8, 8))\n        graph.view_box.sigRangeChangedManually.emit(((1, 9), (-1, 7)))\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.label_only_selected = True\n        graph.update_labels()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3, 4, 5, 6])\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3])\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.label_only_selected = False\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.clear()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n    def test_no_needless_buildatlas(self):\n        graph = self.graph\n        graph.reset_graph()\n        self.assertIsNone(graph.scatterplot_item.fragmentAtlas.atlas)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1105,
                            "end_lineno": 1141,
                            "parent": {
                                "file_name": "Orange/widgets/visualize/tests/test_owscatterplotbase.py",
                                "type": "class",
                                "name": "TestOWScatterPlotBase",
                                "content": "class TestOWScatterPlotBase(WidgetTest):\n    def setUp(self):\n        self.master = MockWidget()\n        self.graph = OWScatterPlotBase(self.master)\n\n        self.xy = (np.arange(10, dtype=float), np.arange(10, dtype=float))\n        self.master.get_coordinates_data = lambda: self.xy\n\n    # pylint: disable=keyword-arg-before-vararg\n    def setRange(self, rect=None, *_, **__):\n        if isinstance(rect, QRectF):\n            self.last_setRange = [[rect.left(), rect.right()],\n                                  [rect.top(), rect.bottom()]]\n\n    def test_update_coordinates_no_data(self):\n        self.xy = None, None\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n        self.xy = [], []\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        graph.reset_graph()\n\n        scatterplot_item = graph.scatterplot_item\n        scatterplot_item_sel = graph.scatterplot_item_sel\n        data = scatterplot_item.data\n\n        np.testing.assert_almost_equal(scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(scatterplot_item_sel.getData(), xy)\n        scatterplot_item.setSize([5, 6])\n        scatterplot_item.setSymbol([7, 8])\n        scatterplot_item.setPen([mkPen(9), mkPen(10)])\n        scatterplot_item.setBrush([11, 12])\n        data[\"data\"] = np.array([13, 14])\n\n        xy[0][0] = 0\n        graph.update_coordinates()\n        np.testing.assert_almost_equal(graph.scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(graph.scatterplot_item_sel.getData(), xy)\n\n        # Graph updates coordinates instead of creating new items\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        self.assertIs(scatterplot_item_sel, graph.scatterplot_item_sel)\n        np.testing.assert_almost_equal(data[\"size\"], [5, 6])\n        np.testing.assert_almost_equal(data[\"symbol\"], [7, 8])\n        self.assertEqual(data[\"pen\"][0], mkPen(9))\n        self.assertEqual(data[\"pen\"][1], mkPen(10))\n        np.testing.assert_almost_equal(data[\"brush\"], [11, 12])\n        np.testing.assert_almost_equal(data[\"data\"], [13, 14])\n\n    def test_update_coordinates_and_labels(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1., 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 1.5\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 1.5)\n        xy[0][0] = 0  # This label goes out of the range\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 2)\n\n    def test_update_coordinates_and_density(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 0\n        graph.update_density = Mock()\n        graph.update_coordinates()\n        graph.update_density.assert_called_with()\n\n    def test_update_coordinates_reset_view(self):\n        graph = self.graph\n        graph.view_box.setRange = self.setRange\n        xy = self.xy = (np.array([2, 1]), np.array([3, 10]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(self.last_setRange, [[1, 2], [3, 10]])\n\n        xy[0][1] = 0\n        graph.update_coordinates()\n        self.assertEqual(self.last_setRange, [[0, 2], [3, 10]])\n\n    def test_reset_graph_no_data(self):\n        self.xy = (None, None)\n        self.graph.scatterplot_item = ScatterPlotItem([1, 2], [3, 4])\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates_indices(self):\n        graph = self.graph\n        self.xy = (np.array([2, 1]), np.array([3, 10]))\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item.data[\"data\"], [0, 1])\n\n    def test_sampling(self):\n        graph = self.graph\n        master = self.master\n\n        # Enable sampling before getting the data\n        graph.set_sample_size(3)\n        xy = self.xy = (np.arange(10, dtype=float),\n                        np.arange(0, 30, 3, dtype=float))\n        d = np.arange(10, dtype=float)\n        master.get_size_data = lambda: d\n        master.get_shape_data = lambda: d % 5 if d is not None else None\n        master.get_color_data = lambda: d\n        master.get_label_data = lambda: \\\n            np.array([str(x) for x in d], dtype=object)\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n        # Check proper sampling\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertNotEqual(x[0], x[1])\n        self.assertNotEqual(x[0], x[2])\n        self.assertNotEqual(x[1], x[2])\n        np.testing.assert_almost_equal(3 * x, y)\n\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Check that sample is extended when sample size is changed\n        graph.set_sample_size(4)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s = data[\"size\"] - graph.MinShapeSize\n        precise_s = (x - min(x)) / (max(x) - min(x)) * max(s)\n        np.testing.assert_almost_equal(s, precise_s, decimal=0)\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Disable sampling\n        graph.set_sample_size(None)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        np.testing.assert_almost_equal(x, xy[0])\n        np.testing.assert_almost_equal(y, xy[1])\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in d])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in d])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in d])\n\n        # Enable sampling when data is already present and not sampled\n        graph.set_sample_size(3)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Update data when data is present and sampling is enabled\n        xy[0][:] = np.arange(9, -1, -1, dtype=float)\n        d = xy[0]\n        graph.update_coordinates()\n        x1, _ = scatterplot_item.getData()\n        np.testing.assert_almost_equal(9 - x, x1)\n        graph.update_sizes()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Reset graph when data is present and sampling is enabled\n        self.xy = (np.arange(100, 105, dtype=float),\n                   np.arange(100, 105, dtype=float))\n        d = self.xy[0] - 100\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertTrue(np.all(x > 99))\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Don't sample when unnecessary\n        self.xy = (np.arange(100, dtype=float), ) * 2\n        d = None\n        delattr(master, \"get_label_data\")\n        graph.reset_graph()\n        graph.set_sample_size(120)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_almost_equal(x, np.arange(100))\n\n    def test_sampling_keeps_selection(self):\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n        graph.reset_graph()\n        graph.select_by_indices(np.arange(1, 100, 2))\n        graph.set_sample_size(30)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n        graph.set_sample_size(None)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n\n    base = \"Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase.\"\n\n    @patch(base + \"update_sizes\")\n    @patch(base + \"update_colors\")\n    @patch(base + \"update_selection_colors\")\n    @patch(base + \"update_shapes\")\n    @patch(base + \"update_labels\")\n    def test_reset_calls_all_updates_and_update_doesnt(self, *mocks):\n        master = MockWidget()\n        graph = OWScatterPlotBase(master)\n        for mock in mocks:\n            mock.assert_not_called()\n\n        graph.reset_graph()\n        for mock in mocks:\n            mock.assert_called_with()\n            mock.reset_mock()\n\n        graph.update_coordinates()\n        for mock in mocks:\n            mock.assert_not_called()\n\n    def test_jittering(self):\n        graph = self.graph\n        graph.jitter_size = 10\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        a10 = np.arange(10)\n        self.assertTrue(np.any(np.nonzero(a10 - x)))\n        self.assertTrue(np.any(np.nonzero(a10 - y)))\n        np.testing.assert_array_less(a10 - x, 1)\n        np.testing.assert_array_less(a10 - y, 1)\n\n        graph.jitter_size = 0\n        graph.update_coordinates()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_equal(a10, x)\n\n    def test_size_normalization(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, [6, 7.5, 9.5, 11, 12.5, 14.5, 16, 17.5, 19.5, 21])\n\n        d = np.arange(10, 20, dtype=float)\n        graph.update_sizes()\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        size2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, size2)\n\n    def test_size_rounding_half_pixel(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size*2 - (size*2).round(), 0)\n\n    def test_size_with_nans(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n\n        d[4] = np.nan\n        graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        sizes2 = scatterplot_item.data[\"size\"]\n\n        self.assertEqual(sizes[1] - sizes[0], sizes2[1] - sizes2[0])\n        self.assertLess(sizes2[4], self.graph.MinShapeSize)\n\n        d[:] = np.nan\n        graph.update_sizes()\n        sizes3 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes3)\n\n    def test_sizes_all_same_or_nan(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.full((10, ), 3.0)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n        self.assertEqual(len(set(sizes)), 1)\n        self.assertGreater(sizes[0], self.graph.MinShapeSize)\n\n        d = None\n        graph.update_sizes()\n        scatterplot_item = graph.scatterplot_item\n        sizes2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes2)\n\n    def test_sizes_point_width_is_linear(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.point_width = 1\n        graph.reset_graph()\n        sizes1 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 2\n        graph.update_sizes()\n        sizes2 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 3\n        graph.update_sizes()\n        sizes3 = graph.scatterplot_item.data[\"size\"]\n\n        np.testing.assert_almost_equal(2 * (sizes2 - sizes1), sizes3 - sizes1)\n\n    def test_sizes_custom_imputation(self):\n\n        def impute_max(size_data):\n            size_data[np.isnan(size_data)] = np.nanmax(size_data)\n\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        self.master.impute_sizes = impute_max\n        d = np.arange(10, dtype=float)\n        d[4] = np.nan\n        graph.reset_graph()\n        sizes = graph.scatterplot_item.data[\"size\"]\n        self.assertAlmostEqual(sizes[4], sizes[9])\n\n    def test_sizes_selection(self):\n        graph = self.graph\n        graph.get_size = lambda: np.arange(10, dtype=float)\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item_sel.data[\"size\"]\n            - graph.scatterplot_item.data[\"size\"],\n            SELECTION_WIDTH)\n\n    @patch(\"Orange.widgets.visualize.owscatterplotgraph\"\n           \".MAX_N_VALID_SIZE_ANIMATE\", 5)\n    def test_size_animation(self):\n        begin_resizing = QSignalSpy(self.graph.begin_resizing)\n        step_resizing = QSignalSpy(self.graph.step_resizing)\n        end_resizing = QSignalSpy(self.graph.end_resizing)\n        self._update_sizes_for_points(5)\n        # first end_resizing is triggered in reset, thus wait for step_resizing\n        step_resizing.wait(200)\n        end_resizing.wait(200)\n        self.assertEqual(len(begin_resizing), 2)  # reset and update\n        self.assertEqual(len(step_resizing), 5)\n        self.assertEqual(len(end_resizing), 2)  # reset and update\n        self.assertEqual(self.graph.scatterplot_item.setSize.call_count, 6)\n        self._update_sizes_for_points(6)\n        self.graph.scatterplot_item.setSize.assert_called_once()\n\n    def _update_sizes_for_points(self, n: int):\n        arr = np.arange(n, dtype=float)\n        self.master.get_coordinates_data = lambda: (arr, arr)\n        self.master.get_size_data = lambda: arr\n        self.graph.reset_graph()\n        self.graph.scatterplot_item.setSize = Mock(\n            wraps=self.graph.scatterplot_item.setSize)\n        self.master.get_size_data = lambda: arr[::-1]\n        self.graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n    def test_colors_discrete(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        self.master.get_color_data = lambda: d\n        d = np.arange(10, dtype=float) % 2\n\n        graph.reset_graph()\n        data = graph.scatterplot_item.data\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"pen\"])))\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"brush\"])))\n\n        # confirm that QPen/QBrush were reused\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 2)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)\n\n    def test_colors_discrete_nan(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        self.assertEqual(pens[0].color().hue(), palette[0].hue())\n        self.assertEqual(pens[1].color().hue(), palette[1].hue())\n        self.assertEqual(brushes[0].color().hue(), palette[0].hue())\n        self.assertEqual(brushes[1].color().hue(), palette[1].hue())\n        self.assertEqual(pens[4].color().hue(), QColor(128, 128, 128).hue())\n        self.assertEqual(brushes[4].color().hue(), QColor(128, 128, 128).hue())\n\n    def test_colors_continuous(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()  # I don't have a good test ... just don't crash\n\n        d[4] = np.nan\n        graph.update_colors()  # Ditto\n\n    def test_colors_continuous_reused(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n\n        d = np.arange(100, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n\n        data = graph.scatterplot_item.data\n\n        self.assertEqual(len(data[\"pen\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"pen\"]))), 10)\n        self.assertEqual(len(data[\"brush\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"brush\"]))), 10)\n\n    def test_colors_continuous_nan(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        nan_color = QColor(*NAN_GREY)\n        self.assertEqual(pens[4].color().hue(), nan_color.hue())\n        self.assertEqual(brushes[4].color().hue(), nan_color.hue())\n\n    def test_colors_subset(self):\n        def run_tests():\n            self.master.get_subset_mask = lambda: None\n\n            graph.alpha_value = 42\n            graph.reset_graph()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 42)\n            self.assertEqual(brushes[1].color().alpha(), 42)\n            self.assertEqual(brushes[4].color().alpha(), 42)\n\n            graph.alpha_value = 123\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 123)\n            self.assertEqual(brushes[1].color().alpha(), 123)\n            self.assertEqual(brushes[4].color().alpha(), 123)\n\n            self.master.get_subset_mask = lambda: np.arange(10) >= 5\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 0)\n            self.assertEqual(brushes[1].color().alpha(), 0)\n            self.assertEqual(brushes[4].color().alpha(), 0)\n            self.assertEqual(brushes[5].color().alpha(), 255)\n            self.assertEqual(brushes[6].color().alpha(), 255)\n            self.assertEqual(brushes[7].color().alpha(), 255)\n\n        graph = self.graph\n\n        self.master.get_color_data = lambda: None\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n        d = np.arange(10, dtype=float) % 2\n        d[4:6] = np.nan\n        self.master.get_color_data = lambda: d\n\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n    def test_colors_none(self):\n        graph = self.graph\n        graph.reset_graph()\n        hue = QColor(128, 128, 128).hue()\n\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)  # test QPen/QBrush reuse\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 1)\n\n        self.master.get_subset_mask = lambda: np.arange(10) < 5\n        graph.update_colors()\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)  # transparent and colored\n\n    def test_colors_update_legend_and_density(self):\n        graph = self.graph\n        graph.update_legends = Mock()\n        graph.update_density = Mock()\n        graph.reset_graph()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n        graph.update_legends.reset_mock()\n        graph.update_density.reset_mock()\n\n        graph.update_coordinates()\n        graph.update_legends.assert_not_called()\n\n        graph.update_colors()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n    def test_selection_colors(self):\n        graph = self.graph\n        graph.reset_graph()\n        data = graph.scatterplot_item_sel.data\n\n        # One group\n        graph.select_by_indices(np.array([0, 1, 2, 3]))\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(4):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(4, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n\n        # Two groups\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_indices(np.array([4, 5, 6]))\n\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(7):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(7, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n        self.assertEqual(len({pen.color().hue() for pen in pens[:4]}), 1)\n        self.assertEqual(len({pen.color().hue() for pen in pens[4:7]}), 1)\n        color1 = pens[3].color().hue()\n        color2 = pens[4].color().hue()\n        self.assertNotEqual(color1, color2)\n\n        # Two groups + sampling\n        graph.set_sample_size(7)\n        x = graph.scatterplot_item.getData()[0]\n        pens = graph.scatterplot_item_sel.data[\"pen\"]\n        for xi, pen in zip(x, pens):\n            if xi < 4:\n                self.assertEqual(pen.color().hue(), color1)\n            elif xi < 7:\n                self.assertEqual(pen.color().hue(), color2)\n            else:\n                self.assertEqual(pen.style(), Qt.NoPen)\n\n    def test_density(self):\n        graph = self.graph\n        density = object()\n        with patch(\"Orange.widgets.utils.classdensity.class_density_image\",\n                   return_value=density):\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n\n            graph.plot_widget.addItem = Mock()\n            graph.plot_widget.removeItem = Mock()\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.ones((10, ), dtype=float)\n            self.master.get_color_data = lambda: d\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.arange(10) % 2\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.class_density = False\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.update_coordinates = lambda: (None, None)\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n    def test_labels(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n\n        # Label only selected\n        selected = [1, 3, 5]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(x) for x in selected])\n        x, y = graph.scatterplot_item.getData()\n        for i, index in enumerate(selected):\n            self.assertEqual(x[index], graph.labels[i].x())\n            self.assertEqual(y[index], graph.labels[i].y())\n\n        # Disable label only selected\n        self.graph.label_only_selected = False\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        # Label only selected + sampling\n        selected = [1, 3, 4, 5, 6, 7, 9]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        graph.set_sample_size(5)\n        for label in graph.labels:\n            ind = int(label.textItem.toPlainText())\n            self.assertIn(ind, selected)\n            self.assertEqual(label.x(), x[ind])\n            self.assertEqual(label.y(), y[ind])\n\n    def test_label_mask_all_visible(self):\n        graph = self.graph\n\n        x, y = np.arange(10) / 10, np.arange(10) / 10\n        sel = np.array(\n            [True, True, False, False, False, True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False, True, True, False, False, False])\n        trues = np.ones(10, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel)\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), np.array(\n            [True, True, True, True, False, True, True, True, False, False]\n        ))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset)\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5, 10) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, False, True])\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        trues = np.ones(5, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel[5:])\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([True, True, True, False, True]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset[5:])\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible_and_view(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])  # first and last out of the view\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, True, True])  # first and last out of the view\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        graph.view_box.viewRange = lambda: ((0.6, 1), (0, 0.3))\n        viewed = np.array([False, True, True, True, False])\n\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, False, False]))\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, True, False]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, False, True, False]))\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_labels_observes_mask(self):\n        graph = self.graph\n        get_label_data = graph.master.get_label_data\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        get_label_data.reset_mock()\n        graph._label_mask = lambda *_: None\n        graph.update_labels()\n        get_label_data.assert_not_called()\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph._label_mask = \\\n            lambda *_: np.array([False, True, True] + [False] * 7)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [\"1\", \"2\"])\n\n    def test_labels_update_coordinates(self):\n        graph = self.graph\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n\n        graph.reset_graph()\n        graph.set_sample_size(7)\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        self.master.get_coordinates_data = \\\n            lambda: (np.arange(10, 20), np.arange(50, 60))\n        graph.update_coordinates()\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n    def test_shapes(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 3]\n                            for i, symbol in enumerate(symbols)))\n\n        d = np.arange(10, dtype=float) % 2\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 2]\n                            for i, symbol in enumerate(symbols)))\n\n        d = None\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertEqual(len(set(symbols)), 1)\n\n    def test_shapes_nan(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n\n        graph.reset_graph()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2], '?')\n\n        d[:] = np.nan\n        graph.update_shapes()\n        self.assertTrue(\n            all(symbol == '?'\n                for symbol in graph.scatterplot_item.data[\"symbol\"]))\n\n        def impute0(data, _):\n            data[np.isnan(data)] = 0\n\n        self.master.impute_shapes = impute0\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n        graph.update_shapes()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2],\n                         graph.CurveSymbols[0])\n\n    def test_show_grid(self):\n        graph = self.graph\n        show_grid = self.graph.plot_widget.showGrid = Mock()\n        graph.show_grid = False\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=False, y=False))\n\n        graph.show_grid = True\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=True, y=True))\n\n    def test_show_legend(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        shape_labels = color_labels = None  # Avoid pylint warning\n        self.master.get_shape_labels = lambda: shape_labels\n        self.master.get_color_labels = lambda: color_labels\n        for shape_labels in (None, [\"a\", \"b\"]):\n            for color_labels in (None, [\"c\", \"d\"], None):\n                for visible in (True, False, True):\n                    graph.show_legend = visible\n                    graph.update_legends()\n                    self.assertIs(\n                        shape_legend.call_args[0][0],\n                        visible and bool(shape_labels),\n                        msg=\"error at {}, {}\".format(visible, shape_labels))\n                    self.assertIs(\n                        color_legend.call_args[0][0],\n                        visible and bool(color_labels),\n                        msg=\"error at {}, {}\".format(visible, color_labels))\n\n    def test_show_legend_no_data(self):\n        graph = self.graph\n        self.master.get_shape_labels = lambda: [\"a\", \"b\"]\n        self.master.get_color_labels = lambda: [\"c\", \"d\"]\n        self.master.get_shape_data = lambda: np.arange(10) % 2\n        self.master.get_color_data = lambda: np.arange(10) < 6\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        self.master.get_coordinates_data = lambda: (None, None)\n        graph.reset_graph()\n        self.assertFalse(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n\n    def test_legend_combine(self):\n        master = self.master\n        graph = self.graph\n\n        master.get_shape_data = lambda: np.arange(10, dtype=float) % 3\n        master.get_color_data = lambda: 2 * np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n\n        master.get_shape_labels = lambda: [\"a\", \"b\"]\n        master.get_color_labels = lambda: [\"c\", \"d\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n\n        master.get_color_labels = lambda: [\"a\", \"b\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.get_color_data = lambda: np.arange(10, dtype=float) % 3\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.is_continuous_color = lambda: True\n        master.get_color_data = lambda: np.arange(10, dtype=float)\n        master.get_color_labels = lambda: None\n        graph.update_colors()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n    def test_select_by_click(self):\n        graph = self.graph\n        graph.reset_graph()\n        points = graph.scatterplot_item.points()\n        graph.select_by_click(None, [points[2]])\n        np.testing.assert_almost_equal(graph.get_selection(), [2])\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_click(None, points[3:6])\n        np.testing.assert_almost_equal(\n            list(graph.get_selection()), [2, 3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 1, 2, 2, 2, 0, 0, 0, 0])\n\n    def test_select_by_rectangle(self):\n        graph = self.graph\n        coords = np.array(\n            [(x, y) for y in range(10) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n\n        graph.reset_graph()\n        graph.select_by_rectangle(QRectF(3, 5, 3.9, 2.9))\n        self.assertTrue(\n            all(selected == (3 <= coords[0][i] <= 6 and 5 <= coords[1][i] <= 7)\n                for i, selected in enumerate(graph.selection)))\n\n    def test_select_by_indices(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        def select(modifiers, indices):\n            with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                       lambda: modifiers):\n                graph.update_selection_colors = Mock()\n                graph.update_labels = Mock()\n                self.master.selection_changed = Mock()\n\n                graph.select_by_indices(np.array(indices))\n                graph.update_selection_colors.assert_called_with()\n                if graph.label_only_selected:\n                    graph.update_labels.assert_called_with()\n                else:\n                    graph.update_labels.assert_not_called()\n                self.master.selection_changed.assert_called_with()\n\n        select(0, [7, 8, 9])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 0, 0, 1, 1, 1])\n\n        select(Qt.ShiftModifier | Qt.ControlModifier, [5, 6])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 1, 1, 1, 1, 1])\n\n        select(Qt.ShiftModifier, [3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 2, 2, 2, 1, 1, 1, 1])\n\n        select(Qt.AltModifier, [1, 3, 7])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 2, 2, 1, 0, 1, 1])\n\n        select(0, [1, 8])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 1, 0, 0, 0, 0, 0, 0, 1, 0])\n\n        graph.label_only_selected = False\n        select(0, [3, 4])\n\n    def test_unselect_all(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        graph.select_by_indices([3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 1, 1, 1, 0, 0, 0, 0])\n\n        graph.update_selection_colors = Mock()\n        graph.update_labels = Mock()\n        self.master.selection_changed = Mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_called_with()\n        graph.update_labels.assert_called_with()\n        self.master.selection_changed.assert_called_with()\n\n        graph.update_selection_colors.reset_mock()\n        graph.update_labels.reset_mock()\n        self.master.selection_changed.reset_mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_not_called()\n        graph.update_labels.assert_not_called()\n        self.master.selection_changed.assert_not_called()\n\n    def test_hiding_too_many_labels(self):\n        spy = QSignalSpy(self.graph.too_many_labels)\n        self.graph.MAX_VISIBLE_LABELS = 5\n\n        graph = self.graph\n        coords = np.array(\n            [(x, 0) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n        graph.reset_graph()\n\n        self.assertFalse(spy and spy[-1][0])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 4, 4))\n        graph.view_box.sigRangeChangedManually.emit(((1, 5), (-1, 3)))\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 8, 8))\n        graph.view_box.sigRangeChangedManually.emit(((1, 9), (-1, 7)))\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.label_only_selected = True\n        graph.update_labels()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3, 4, 5, 6])\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3])\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.label_only_selected = False\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.clear()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n    def test_no_needless_buildatlas(self):\n        graph = self.graph\n        graph.reset_graph()\n        self.assertIsNone(graph.scatterplot_item.fragmentAtlas.atlas)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 49,
                                "end_lineno": 1294,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/widgets/visualize/tests/test_owscatterplotbase.py",
                            "type": "class",
                            "name": "TestOWScatterPlotBase",
                            "content": "class TestOWScatterPlotBase(WidgetTest):\n    def setUp(self):\n        self.master = MockWidget()\n        self.graph = OWScatterPlotBase(self.master)\n\n        self.xy = (np.arange(10, dtype=float), np.arange(10, dtype=float))\n        self.master.get_coordinates_data = lambda: self.xy\n\n    # pylint: disable=keyword-arg-before-vararg\n    def setRange(self, rect=None, *_, **__):\n        if isinstance(rect, QRectF):\n            self.last_setRange = [[rect.left(), rect.right()],\n                                  [rect.top(), rect.bottom()]]\n\n    def test_update_coordinates_no_data(self):\n        self.xy = None, None\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n        self.xy = [], []\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        graph.reset_graph()\n\n        scatterplot_item = graph.scatterplot_item\n        scatterplot_item_sel = graph.scatterplot_item_sel\n        data = scatterplot_item.data\n\n        np.testing.assert_almost_equal(scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(scatterplot_item_sel.getData(), xy)\n        scatterplot_item.setSize([5, 6])\n        scatterplot_item.setSymbol([7, 8])\n        scatterplot_item.setPen([mkPen(9), mkPen(10)])\n        scatterplot_item.setBrush([11, 12])\n        data[\"data\"] = np.array([13, 14])\n\n        xy[0][0] = 0\n        graph.update_coordinates()\n        np.testing.assert_almost_equal(graph.scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(graph.scatterplot_item_sel.getData(), xy)\n\n        # Graph updates coordinates instead of creating new items\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        self.assertIs(scatterplot_item_sel, graph.scatterplot_item_sel)\n        np.testing.assert_almost_equal(data[\"size\"], [5, 6])\n        np.testing.assert_almost_equal(data[\"symbol\"], [7, 8])\n        self.assertEqual(data[\"pen\"][0], mkPen(9))\n        self.assertEqual(data[\"pen\"][1], mkPen(10))\n        np.testing.assert_almost_equal(data[\"brush\"], [11, 12])\n        np.testing.assert_almost_equal(data[\"data\"], [13, 14])\n\n    def test_update_coordinates_and_labels(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1., 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 1.5\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 1.5)\n        xy[0][0] = 0  # This label goes out of the range\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 2)\n\n    def test_update_coordinates_and_density(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 0\n        graph.update_density = Mock()\n        graph.update_coordinates()\n        graph.update_density.assert_called_with()\n\n    def test_update_coordinates_reset_view(self):\n        graph = self.graph\n        graph.view_box.setRange = self.setRange\n        xy = self.xy = (np.array([2, 1]), np.array([3, 10]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(self.last_setRange, [[1, 2], [3, 10]])\n\n        xy[0][1] = 0\n        graph.update_coordinates()\n        self.assertEqual(self.last_setRange, [[0, 2], [3, 10]])\n\n    def test_reset_graph_no_data(self):\n        self.xy = (None, None)\n        self.graph.scatterplot_item = ScatterPlotItem([1, 2], [3, 4])\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates_indices(self):\n        graph = self.graph\n        self.xy = (np.array([2, 1]), np.array([3, 10]))\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item.data[\"data\"], [0, 1])\n\n    def test_sampling(self):\n        graph = self.graph\n        master = self.master\n\n        # Enable sampling before getting the data\n        graph.set_sample_size(3)\n        xy = self.xy = (np.arange(10, dtype=float),\n                        np.arange(0, 30, 3, dtype=float))\n        d = np.arange(10, dtype=float)\n        master.get_size_data = lambda: d\n        master.get_shape_data = lambda: d % 5 if d is not None else None\n        master.get_color_data = lambda: d\n        master.get_label_data = lambda: \\\n            np.array([str(x) for x in d], dtype=object)\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n        # Check proper sampling\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertNotEqual(x[0], x[1])\n        self.assertNotEqual(x[0], x[2])\n        self.assertNotEqual(x[1], x[2])\n        np.testing.assert_almost_equal(3 * x, y)\n\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Check that sample is extended when sample size is changed\n        graph.set_sample_size(4)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s = data[\"size\"] - graph.MinShapeSize\n        precise_s = (x - min(x)) / (max(x) - min(x)) * max(s)\n        np.testing.assert_almost_equal(s, precise_s, decimal=0)\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Disable sampling\n        graph.set_sample_size(None)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        np.testing.assert_almost_equal(x, xy[0])\n        np.testing.assert_almost_equal(y, xy[1])\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in d])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in d])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in d])\n\n        # Enable sampling when data is already present and not sampled\n        graph.set_sample_size(3)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Update data when data is present and sampling is enabled\n        xy[0][:] = np.arange(9, -1, -1, dtype=float)\n        d = xy[0]\n        graph.update_coordinates()\n        x1, _ = scatterplot_item.getData()\n        np.testing.assert_almost_equal(9 - x, x1)\n        graph.update_sizes()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Reset graph when data is present and sampling is enabled\n        self.xy = (np.arange(100, 105, dtype=float),\n                   np.arange(100, 105, dtype=float))\n        d = self.xy[0] - 100\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertTrue(np.all(x > 99))\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Don't sample when unnecessary\n        self.xy = (np.arange(100, dtype=float), ) * 2\n        d = None\n        delattr(master, \"get_label_data\")\n        graph.reset_graph()\n        graph.set_sample_size(120)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_almost_equal(x, np.arange(100))\n\n    def test_sampling_keeps_selection(self):\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n        graph.reset_graph()\n        graph.select_by_indices(np.arange(1, 100, 2))\n        graph.set_sample_size(30)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n        graph.set_sample_size(None)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n\n    base = \"Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase.\"\n\n    @patch(base + \"update_sizes\")\n    @patch(base + \"update_colors\")\n    @patch(base + \"update_selection_colors\")\n    @patch(base + \"update_shapes\")\n    @patch(base + \"update_labels\")\n    def test_reset_calls_all_updates_and_update_doesnt(self, *mocks):\n        master = MockWidget()\n        graph = OWScatterPlotBase(master)\n        for mock in mocks:\n            mock.assert_not_called()\n\n        graph.reset_graph()\n        for mock in mocks:\n            mock.assert_called_with()\n            mock.reset_mock()\n\n        graph.update_coordinates()\n        for mock in mocks:\n            mock.assert_not_called()\n\n    def test_jittering(self):\n        graph = self.graph\n        graph.jitter_size = 10\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        a10 = np.arange(10)\n        self.assertTrue(np.any(np.nonzero(a10 - x)))\n        self.assertTrue(np.any(np.nonzero(a10 - y)))\n        np.testing.assert_array_less(a10 - x, 1)\n        np.testing.assert_array_less(a10 - y, 1)\n\n        graph.jitter_size = 0\n        graph.update_coordinates()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_equal(a10, x)\n\n    def test_size_normalization(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, [6, 7.5, 9.5, 11, 12.5, 14.5, 16, 17.5, 19.5, 21])\n\n        d = np.arange(10, 20, dtype=float)\n        graph.update_sizes()\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        size2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, size2)\n\n    def test_size_rounding_half_pixel(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size*2 - (size*2).round(), 0)\n\n    def test_size_with_nans(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n\n        d[4] = np.nan\n        graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        sizes2 = scatterplot_item.data[\"size\"]\n\n        self.assertEqual(sizes[1] - sizes[0], sizes2[1] - sizes2[0])\n        self.assertLess(sizes2[4], self.graph.MinShapeSize)\n\n        d[:] = np.nan\n        graph.update_sizes()\n        sizes3 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes3)\n\n    def test_sizes_all_same_or_nan(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.full((10, ), 3.0)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n        self.assertEqual(len(set(sizes)), 1)\n        self.assertGreater(sizes[0], self.graph.MinShapeSize)\n\n        d = None\n        graph.update_sizes()\n        scatterplot_item = graph.scatterplot_item\n        sizes2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes2)\n\n    def test_sizes_point_width_is_linear(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.point_width = 1\n        graph.reset_graph()\n        sizes1 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 2\n        graph.update_sizes()\n        sizes2 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 3\n        graph.update_sizes()\n        sizes3 = graph.scatterplot_item.data[\"size\"]\n\n        np.testing.assert_almost_equal(2 * (sizes2 - sizes1), sizes3 - sizes1)\n\n    def test_sizes_custom_imputation(self):\n\n        def impute_max(size_data):\n            size_data[np.isnan(size_data)] = np.nanmax(size_data)\n\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        self.master.impute_sizes = impute_max\n        d = np.arange(10, dtype=float)\n        d[4] = np.nan\n        graph.reset_graph()\n        sizes = graph.scatterplot_item.data[\"size\"]\n        self.assertAlmostEqual(sizes[4], sizes[9])\n\n    def test_sizes_selection(self):\n        graph = self.graph\n        graph.get_size = lambda: np.arange(10, dtype=float)\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item_sel.data[\"size\"]\n            - graph.scatterplot_item.data[\"size\"],\n            SELECTION_WIDTH)\n\n    @patch(\"Orange.widgets.visualize.owscatterplotgraph\"\n           \".MAX_N_VALID_SIZE_ANIMATE\", 5)\n    def test_size_animation(self):\n        begin_resizing = QSignalSpy(self.graph.begin_resizing)\n        step_resizing = QSignalSpy(self.graph.step_resizing)\n        end_resizing = QSignalSpy(self.graph.end_resizing)\n        self._update_sizes_for_points(5)\n        # first end_resizing is triggered in reset, thus wait for step_resizing\n        step_resizing.wait(200)\n        end_resizing.wait(200)\n        self.assertEqual(len(begin_resizing), 2)  # reset and update\n        self.assertEqual(len(step_resizing), 5)\n        self.assertEqual(len(end_resizing), 2)  # reset and update\n        self.assertEqual(self.graph.scatterplot_item.setSize.call_count, 6)\n        self._update_sizes_for_points(6)\n        self.graph.scatterplot_item.setSize.assert_called_once()\n\n    def _update_sizes_for_points(self, n: int):\n        arr = np.arange(n, dtype=float)\n        self.master.get_coordinates_data = lambda: (arr, arr)\n        self.master.get_size_data = lambda: arr\n        self.graph.reset_graph()\n        self.graph.scatterplot_item.setSize = Mock(\n            wraps=self.graph.scatterplot_item.setSize)\n        self.master.get_size_data = lambda: arr[::-1]\n        self.graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n    def test_colors_discrete(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        self.master.get_color_data = lambda: d\n        d = np.arange(10, dtype=float) % 2\n\n        graph.reset_graph()\n        data = graph.scatterplot_item.data\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"pen\"])))\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"brush\"])))\n\n        # confirm that QPen/QBrush were reused\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 2)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)\n\n    def test_colors_discrete_nan(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        self.assertEqual(pens[0].color().hue(), palette[0].hue())\n        self.assertEqual(pens[1].color().hue(), palette[1].hue())\n        self.assertEqual(brushes[0].color().hue(), palette[0].hue())\n        self.assertEqual(brushes[1].color().hue(), palette[1].hue())\n        self.assertEqual(pens[4].color().hue(), QColor(128, 128, 128).hue())\n        self.assertEqual(brushes[4].color().hue(), QColor(128, 128, 128).hue())\n\n    def test_colors_continuous(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()  # I don't have a good test ... just don't crash\n\n        d[4] = np.nan\n        graph.update_colors()  # Ditto\n\n    def test_colors_continuous_reused(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n\n        d = np.arange(100, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n\n        data = graph.scatterplot_item.data\n\n        self.assertEqual(len(data[\"pen\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"pen\"]))), 10)\n        self.assertEqual(len(data[\"brush\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"brush\"]))), 10)\n\n    def test_colors_continuous_nan(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        nan_color = QColor(*NAN_GREY)\n        self.assertEqual(pens[4].color().hue(), nan_color.hue())\n        self.assertEqual(brushes[4].color().hue(), nan_color.hue())\n\n    def test_colors_subset(self):\n        def run_tests():\n            self.master.get_subset_mask = lambda: None\n\n            graph.alpha_value = 42\n            graph.reset_graph()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 42)\n            self.assertEqual(brushes[1].color().alpha(), 42)\n            self.assertEqual(brushes[4].color().alpha(), 42)\n\n            graph.alpha_value = 123\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 123)\n            self.assertEqual(brushes[1].color().alpha(), 123)\n            self.assertEqual(brushes[4].color().alpha(), 123)\n\n            self.master.get_subset_mask = lambda: np.arange(10) >= 5\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 0)\n            self.assertEqual(brushes[1].color().alpha(), 0)\n            self.assertEqual(brushes[4].color().alpha(), 0)\n            self.assertEqual(brushes[5].color().alpha(), 255)\n            self.assertEqual(brushes[6].color().alpha(), 255)\n            self.assertEqual(brushes[7].color().alpha(), 255)\n\n        graph = self.graph\n\n        self.master.get_color_data = lambda: None\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n        d = np.arange(10, dtype=float) % 2\n        d[4:6] = np.nan\n        self.master.get_color_data = lambda: d\n\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n    def test_colors_none(self):\n        graph = self.graph\n        graph.reset_graph()\n        hue = QColor(128, 128, 128).hue()\n\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)  # test QPen/QBrush reuse\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 1)\n\n        self.master.get_subset_mask = lambda: np.arange(10) < 5\n        graph.update_colors()\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)  # transparent and colored\n\n    def test_colors_update_legend_and_density(self):\n        graph = self.graph\n        graph.update_legends = Mock()\n        graph.update_density = Mock()\n        graph.reset_graph()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n        graph.update_legends.reset_mock()\n        graph.update_density.reset_mock()\n\n        graph.update_coordinates()\n        graph.update_legends.assert_not_called()\n\n        graph.update_colors()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n    def test_selection_colors(self):\n        graph = self.graph\n        graph.reset_graph()\n        data = graph.scatterplot_item_sel.data\n\n        # One group\n        graph.select_by_indices(np.array([0, 1, 2, 3]))\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(4):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(4, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n\n        # Two groups\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_indices(np.array([4, 5, 6]))\n\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(7):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(7, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n        self.assertEqual(len({pen.color().hue() for pen in pens[:4]}), 1)\n        self.assertEqual(len({pen.color().hue() for pen in pens[4:7]}), 1)\n        color1 = pens[3].color().hue()\n        color2 = pens[4].color().hue()\n        self.assertNotEqual(color1, color2)\n\n        # Two groups + sampling\n        graph.set_sample_size(7)\n        x = graph.scatterplot_item.getData()[0]\n        pens = graph.scatterplot_item_sel.data[\"pen\"]\n        for xi, pen in zip(x, pens):\n            if xi < 4:\n                self.assertEqual(pen.color().hue(), color1)\n            elif xi < 7:\n                self.assertEqual(pen.color().hue(), color2)\n            else:\n                self.assertEqual(pen.style(), Qt.NoPen)\n\n    def test_density(self):\n        graph = self.graph\n        density = object()\n        with patch(\"Orange.widgets.utils.classdensity.class_density_image\",\n                   return_value=density):\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n\n            graph.plot_widget.addItem = Mock()\n            graph.plot_widget.removeItem = Mock()\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.ones((10, ), dtype=float)\n            self.master.get_color_data = lambda: d\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.arange(10) % 2\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.class_density = False\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.update_coordinates = lambda: (None, None)\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n    def test_labels(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n\n        # Label only selected\n        selected = [1, 3, 5]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(x) for x in selected])\n        x, y = graph.scatterplot_item.getData()\n        for i, index in enumerate(selected):\n            self.assertEqual(x[index], graph.labels[i].x())\n            self.assertEqual(y[index], graph.labels[i].y())\n\n        # Disable label only selected\n        self.graph.label_only_selected = False\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        # Label only selected + sampling\n        selected = [1, 3, 4, 5, 6, 7, 9]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        graph.set_sample_size(5)\n        for label in graph.labels:\n            ind = int(label.textItem.toPlainText())\n            self.assertIn(ind, selected)\n            self.assertEqual(label.x(), x[ind])\n            self.assertEqual(label.y(), y[ind])\n\n    def test_label_mask_all_visible(self):\n        graph = self.graph\n\n        x, y = np.arange(10) / 10, np.arange(10) / 10\n        sel = np.array(\n            [True, True, False, False, False, True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False, True, True, False, False, False])\n        trues = np.ones(10, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel)\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), np.array(\n            [True, True, True, True, False, True, True, True, False, False]\n        ))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset)\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5, 10) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, False, True])\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        trues = np.ones(5, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel[5:])\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([True, True, True, False, True]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset[5:])\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible_and_view(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])  # first and last out of the view\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, True, True])  # first and last out of the view\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        graph.view_box.viewRange = lambda: ((0.6, 1), (0, 0.3))\n        viewed = np.array([False, True, True, True, False])\n\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, False, False]))\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, True, False]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, False, True, False]))\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_labels_observes_mask(self):\n        graph = self.graph\n        get_label_data = graph.master.get_label_data\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        get_label_data.reset_mock()\n        graph._label_mask = lambda *_: None\n        graph.update_labels()\n        get_label_data.assert_not_called()\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph._label_mask = \\\n            lambda *_: np.array([False, True, True] + [False] * 7)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [\"1\", \"2\"])\n\n    def test_labels_update_coordinates(self):\n        graph = self.graph\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n\n        graph.reset_graph()\n        graph.set_sample_size(7)\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        self.master.get_coordinates_data = \\\n            lambda: (np.arange(10, 20), np.arange(50, 60))\n        graph.update_coordinates()\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n    def test_shapes(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 3]\n                            for i, symbol in enumerate(symbols)))\n\n        d = np.arange(10, dtype=float) % 2\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 2]\n                            for i, symbol in enumerate(symbols)))\n\n        d = None\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertEqual(len(set(symbols)), 1)\n\n    def test_shapes_nan(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n\n        graph.reset_graph()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2], '?')\n\n        d[:] = np.nan\n        graph.update_shapes()\n        self.assertTrue(\n            all(symbol == '?'\n                for symbol in graph.scatterplot_item.data[\"symbol\"]))\n\n        def impute0(data, _):\n            data[np.isnan(data)] = 0\n\n        self.master.impute_shapes = impute0\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n        graph.update_shapes()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2],\n                         graph.CurveSymbols[0])\n\n    def test_show_grid(self):\n        graph = self.graph\n        show_grid = self.graph.plot_widget.showGrid = Mock()\n        graph.show_grid = False\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=False, y=False))\n\n        graph.show_grid = True\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=True, y=True))\n\n    def test_show_legend(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        shape_labels = color_labels = None  # Avoid pylint warning\n        self.master.get_shape_labels = lambda: shape_labels\n        self.master.get_color_labels = lambda: color_labels\n        for shape_labels in (None, [\"a\", \"b\"]):\n            for color_labels in (None, [\"c\", \"d\"], None):\n                for visible in (True, False, True):\n                    graph.show_legend = visible\n                    graph.update_legends()\n                    self.assertIs(\n                        shape_legend.call_args[0][0],\n                        visible and bool(shape_labels),\n                        msg=\"error at {}, {}\".format(visible, shape_labels))\n                    self.assertIs(\n                        color_legend.call_args[0][0],\n                        visible and bool(color_labels),\n                        msg=\"error at {}, {}\".format(visible, color_labels))\n\n    def test_show_legend_no_data(self):\n        graph = self.graph\n        self.master.get_shape_labels = lambda: [\"a\", \"b\"]\n        self.master.get_color_labels = lambda: [\"c\", \"d\"]\n        self.master.get_shape_data = lambda: np.arange(10) % 2\n        self.master.get_color_data = lambda: np.arange(10) < 6\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        self.master.get_coordinates_data = lambda: (None, None)\n        graph.reset_graph()\n        self.assertFalse(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n\n    def test_legend_combine(self):\n        master = self.master\n        graph = self.graph\n\n        master.get_shape_data = lambda: np.arange(10, dtype=float) % 3\n        master.get_color_data = lambda: 2 * np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n\n        master.get_shape_labels = lambda: [\"a\", \"b\"]\n        master.get_color_labels = lambda: [\"c\", \"d\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n\n        master.get_color_labels = lambda: [\"a\", \"b\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.get_color_data = lambda: np.arange(10, dtype=float) % 3\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.is_continuous_color = lambda: True\n        master.get_color_data = lambda: np.arange(10, dtype=float)\n        master.get_color_labels = lambda: None\n        graph.update_colors()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n    def test_select_by_click(self):\n        graph = self.graph\n        graph.reset_graph()\n        points = graph.scatterplot_item.points()\n        graph.select_by_click(None, [points[2]])\n        np.testing.assert_almost_equal(graph.get_selection(), [2])\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_click(None, points[3:6])\n        np.testing.assert_almost_equal(\n            list(graph.get_selection()), [2, 3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 1, 2, 2, 2, 0, 0, 0, 0])\n\n    def test_select_by_rectangle(self):\n        graph = self.graph\n        coords = np.array(\n            [(x, y) for y in range(10) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n\n        graph.reset_graph()\n        graph.select_by_rectangle(QRectF(3, 5, 3.9, 2.9))\n        self.assertTrue(\n            all(selected == (3 <= coords[0][i] <= 6 and 5 <= coords[1][i] <= 7)\n                for i, selected in enumerate(graph.selection)))\n\n    def test_select_by_indices(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        def select(modifiers, indices):\n            with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                       lambda: modifiers):\n                graph.update_selection_colors = Mock()\n                graph.update_labels = Mock()\n                self.master.selection_changed = Mock()\n\n                graph.select_by_indices(np.array(indices))\n                graph.update_selection_colors.assert_called_with()\n                if graph.label_only_selected:\n                    graph.update_labels.assert_called_with()\n                else:\n                    graph.update_labels.assert_not_called()\n                self.master.selection_changed.assert_called_with()\n\n        select(0, [7, 8, 9])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 0, 0, 1, 1, 1])\n\n        select(Qt.ShiftModifier | Qt.ControlModifier, [5, 6])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 1, 1, 1, 1, 1])\n\n        select(Qt.ShiftModifier, [3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 2, 2, 2, 1, 1, 1, 1])\n\n        select(Qt.AltModifier, [1, 3, 7])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 2, 2, 1, 0, 1, 1])\n\n        select(0, [1, 8])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 1, 0, 0, 0, 0, 0, 0, 1, 0])\n\n        graph.label_only_selected = False\n        select(0, [3, 4])\n\n    def test_unselect_all(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        graph.select_by_indices([3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 1, 1, 1, 0, 0, 0, 0])\n\n        graph.update_selection_colors = Mock()\n        graph.update_labels = Mock()\n        self.master.selection_changed = Mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_called_with()\n        graph.update_labels.assert_called_with()\n        self.master.selection_changed.assert_called_with()\n\n        graph.update_selection_colors.reset_mock()\n        graph.update_labels.reset_mock()\n        self.master.selection_changed.reset_mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_not_called()\n        graph.update_labels.assert_not_called()\n        self.master.selection_changed.assert_not_called()\n\n    def test_hiding_too_many_labels(self):\n        spy = QSignalSpy(self.graph.too_many_labels)\n        self.graph.MAX_VISIBLE_LABELS = 5\n\n        graph = self.graph\n        coords = np.array(\n            [(x, 0) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n        graph.reset_graph()\n\n        self.assertFalse(spy and spy[-1][0])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 4, 4))\n        graph.view_box.sigRangeChangedManually.emit(((1, 5), (-1, 3)))\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 8, 8))\n        graph.view_box.sigRangeChangedManually.emit(((1, 9), (-1, 7)))\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.label_only_selected = True\n        graph.update_labels()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3, 4, 5, 6])\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3])\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.label_only_selected = False\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.clear()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n    def test_no_needless_buildatlas(self):\n        graph = self.graph\n        graph.reset_graph()\n        self.assertIsNone(graph.scatterplot_item.fragmentAtlas.atlas)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 49,
                            "end_lineno": 1294,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf^",
    "new_commit_hash": "1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf",
    "commit_message": "Merge pull request #4078 from janezd/scatterplotgraph-uncombine-legends\n\nOWScatterPlotGraph: Don't combine color and shape legend for different data",
    "commit_date": "2019-10-11T07:26:17+02:00",
    "metadata": {}
}
{
    "repo_name": "orange3",
    "new_commit_hash": "1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf",
    "test_file_codes": [
        "# pylint: disable=missing-docstring,too-many-lines,too-many-public-methods\n# pylint: disable=protected-access\nfrom unittest.mock import patch, Mock\nimport numpy as np\n\nfrom AnyQt.QtCore import QRectF, Qt\nfrom AnyQt.QtGui import QColor\nfrom AnyQt.QtTest import QSignalSpy\n\nfrom pyqtgraph import mkPen\n\nfrom Orange.widgets.settings import SettingProvider\nfrom Orange.widgets.tests.base import WidgetTest\nfrom Orange.widgets.utils.colorpalette import ColorPaletteGenerator, \\\n    ContinuousPaletteGenerator, NAN_GREY\nfrom Orange.widgets.visualize.owscatterplotgraph import OWScatterPlotBase, \\\n    ScatterPlotItem, SELECTION_WIDTH\nfrom Orange.widgets.widget import OWWidget\n\n\nclass MockWidget(OWWidget):\n    name = \"Mock\"\n\n    get_coordinates_data = Mock(return_value=(None, None))\n    get_size_data = Mock(return_value=None)\n    get_shape_data = Mock(return_value=None)\n    get_color_data = Mock(return_value=None)\n    get_label_data = Mock(return_value=None)\n    get_color_labels = Mock(return_value=None)\n    get_shape_labels = Mock(return_value=None)\n    get_subset_mask = Mock(return_value=None)\n    get_tooltip = Mock(return_value=\"\")\n\n    is_continuous_color = Mock(return_value=False)\n    can_draw_density = Mock(return_value=True)\n    combined_legend = Mock(return_value=False)\n    selection_changed = Mock(return_value=None)\n\n    GRAPH_CLASS = OWScatterPlotBase\n    graph = SettingProvider(OWScatterPlotBase)\n\n    def get_palette(self):\n        if self.is_continuous_color():\n            return ContinuousPaletteGenerator(Qt.white, Qt.black, False)\n        else:\n            return ColorPaletteGenerator(12)\n\n\nclass TestOWScatterPlotBase(WidgetTest):\n    def setUp(self):\n        self.master = MockWidget()\n        self.graph = OWScatterPlotBase(self.master)\n\n        self.xy = (np.arange(10, dtype=float), np.arange(10, dtype=float))\n        self.master.get_coordinates_data = lambda: self.xy\n\n    # pylint: disable=keyword-arg-before-vararg\n    def setRange(self, rect=None, *_, **__):\n        if isinstance(rect, QRectF):\n            self.last_setRange = [[rect.left(), rect.right()],\n                                  [rect.top(), rect.bottom()]]\n\n    def test_update_coordinates_no_data(self):\n        self.xy = None, None\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n        self.xy = [], []\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        graph.reset_graph()\n\n        scatterplot_item = graph.scatterplot_item\n        scatterplot_item_sel = graph.scatterplot_item_sel\n        data = scatterplot_item.data\n\n        np.testing.assert_almost_equal(scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(scatterplot_item_sel.getData(), xy)\n        scatterplot_item.setSize([5, 6])\n        scatterplot_item.setSymbol([7, 8])\n        scatterplot_item.setPen([mkPen(9), mkPen(10)])\n        scatterplot_item.setBrush([11, 12])\n        data[\"data\"] = np.array([13, 14])\n\n        xy[0][0] = 0\n        graph.update_coordinates()\n        np.testing.assert_almost_equal(graph.scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(graph.scatterplot_item_sel.getData(), xy)\n\n        # Graph updates coordinates instead of creating new items\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        self.assertIs(scatterplot_item_sel, graph.scatterplot_item_sel)\n        np.testing.assert_almost_equal(data[\"size\"], [5, 6])\n        np.testing.assert_almost_equal(data[\"symbol\"], [7, 8])\n        self.assertEqual(data[\"pen\"][0], mkPen(9))\n        self.assertEqual(data[\"pen\"][1], mkPen(10))\n        np.testing.assert_almost_equal(data[\"brush\"], [11, 12])\n        np.testing.assert_almost_equal(data[\"data\"], [13, 14])\n\n    def test_update_coordinates_and_labels(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1., 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 1.5\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 1.5)\n        xy[0][0] = 0  # This label goes out of the range\n        graph.update_coordinates()\n        self.assertEqual(graph.labels[0].pos().x(), 2)\n\n    def test_update_coordinates_and_density(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 0\n        graph.update_density = Mock()\n        graph.update_coordinates()\n        graph.update_density.assert_called_with()\n\n    def test_update_coordinates_reset_view(self):\n        graph = self.graph\n        graph.view_box.setRange = self.setRange\n        xy = self.xy = (np.array([2, 1]), np.array([3, 10]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(self.last_setRange, [[1, 2], [3, 10]])\n\n        xy[0][1] = 0\n        graph.update_coordinates()\n        self.assertEqual(self.last_setRange, [[0, 2], [3, 10]])\n\n    def test_reset_graph_no_data(self):\n        self.xy = (None, None)\n        self.graph.scatterplot_item = ScatterPlotItem([1, 2], [3, 4])\n        self.graph.reset_graph()\n        self.assertIsNone(self.graph.scatterplot_item)\n        self.assertIsNone(self.graph.scatterplot_item_sel)\n\n    def test_update_coordinates_indices(self):\n        graph = self.graph\n        self.xy = (np.array([2, 1]), np.array([3, 10]))\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item.data[\"data\"], [0, 1])\n\n    def test_sampling(self):\n        graph = self.graph\n        master = self.master\n\n        # Enable sampling before getting the data\n        graph.set_sample_size(3)\n        xy = self.xy = (np.arange(10, dtype=float),\n                        np.arange(0, 30, 3, dtype=float))\n        d = np.arange(10, dtype=float)\n        master.get_size_data = lambda: d\n        master.get_shape_data = lambda: d % 5 if d is not None else None\n        master.get_color_data = lambda: d\n        master.get_label_data = lambda: \\\n            np.array([str(x) for x in d], dtype=object)\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n        # Check proper sampling\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertNotEqual(x[0], x[1])\n        self.assertNotEqual(x[0], x[2])\n        self.assertNotEqual(x[1], x[2])\n        np.testing.assert_almost_equal(3 * x, y)\n\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Check that sample is extended when sample size is changed\n        graph.set_sample_size(4)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s = data[\"size\"] - graph.MinShapeSize\n        precise_s = (x - min(x)) / (max(x) - min(x)) * max(s)\n        np.testing.assert_almost_equal(s, precise_s, decimal=0)\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Disable sampling\n        graph.set_sample_size(None)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        np.testing.assert_almost_equal(x, xy[0])\n        np.testing.assert_almost_equal(y, xy[1])\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in d])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in d])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in d])\n\n        # Enable sampling when data is already present and not sampled\n        graph.set_sample_size(3)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n\n        # Update data when data is present and sampling is enabled\n        xy[0][:] = np.arange(9, -1, -1, dtype=float)\n        d = xy[0]\n        graph.update_coordinates()\n        x1, _ = scatterplot_item.getData()\n        np.testing.assert_almost_equal(9 - x, x1)\n        graph.update_sizes()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Reset graph when data is present and sampling is enabled\n        self.xy = (np.arange(100, 105, dtype=float),\n                   np.arange(100, 105, dtype=float))\n        d = self.xy[0] - 100\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertTrue(np.all(x > 99))\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n\n        # Don't sample when unnecessary\n        self.xy = (np.arange(100, dtype=float), ) * 2\n        d = None\n        delattr(master, \"get_label_data\")\n        graph.reset_graph()\n        graph.set_sample_size(120)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_almost_equal(x, np.arange(100))\n\n    def test_sampling_keeps_selection(self):\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n        graph.reset_graph()\n        graph.select_by_indices(np.arange(1, 100, 2))\n        graph.set_sample_size(30)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n        graph.set_sample_size(None)\n        np.testing.assert_almost_equal(graph.selection, np.arange(100) % 2)\n\n    base = \"Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase.\"\n\n    @patch(base + \"update_sizes\")\n    @patch(base + \"update_colors\")\n    @patch(base + \"update_selection_colors\")\n    @patch(base + \"update_shapes\")\n    @patch(base + \"update_labels\")\n    def test_reset_calls_all_updates_and_update_doesnt(self, *mocks):\n        master = MockWidget()\n        graph = OWScatterPlotBase(master)\n        for mock in mocks:\n            mock.assert_not_called()\n\n        graph.reset_graph()\n        for mock in mocks:\n            mock.assert_called_with()\n            mock.reset_mock()\n\n        graph.update_coordinates()\n        for mock in mocks:\n            mock.assert_not_called()\n\n    def test_jittering(self):\n        graph = self.graph\n        graph.jitter_size = 10\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        a10 = np.arange(10)\n        self.assertTrue(np.any(np.nonzero(a10 - x)))\n        self.assertTrue(np.any(np.nonzero(a10 - y)))\n        np.testing.assert_array_less(a10 - x, 1)\n        np.testing.assert_array_less(a10 - y, 1)\n\n        graph.jitter_size = 0\n        graph.update_coordinates()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        np.testing.assert_equal(a10, x)\n\n    def test_size_normalization(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, [6, 7.5, 9.5, 11, 12.5, 14.5, 16, 17.5, 19.5, 21])\n\n        d = np.arange(10, 20, dtype=float)\n        graph.update_sizes()\n        self.assertIs(scatterplot_item, graph.scatterplot_item)\n        size2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size, size2)\n\n    def test_size_rounding_half_pixel(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        size = scatterplot_item.data[\"size\"]\n        np.testing.assert_equal(size*2 - (size*2).round(), 0)\n\n    def test_size_with_nans(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n\n        d[4] = np.nan\n        graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        sizes2 = scatterplot_item.data[\"size\"]\n\n        self.assertEqual(sizes[1] - sizes[0], sizes2[1] - sizes2[0])\n        self.assertLess(sizes2[4], self.graph.MinShapeSize)\n\n        d[:] = np.nan\n        graph.update_sizes()\n        sizes3 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes3)\n\n    def test_sizes_all_same_or_nan(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.full((10, ), 3.0)\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        sizes = scatterplot_item.data[\"size\"]\n        self.assertEqual(len(set(sizes)), 1)\n        self.assertGreater(sizes[0], self.graph.MinShapeSize)\n\n        d = None\n        graph.update_sizes()\n        scatterplot_item = graph.scatterplot_item\n        sizes2 = scatterplot_item.data[\"size\"]\n        np.testing.assert_almost_equal(sizes, sizes2)\n\n    def test_sizes_point_width_is_linear(self):\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        d = np.arange(10, dtype=float)\n\n        graph.point_width = 1\n        graph.reset_graph()\n        sizes1 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 2\n        graph.update_sizes()\n        sizes2 = graph.scatterplot_item.data[\"size\"]\n\n        graph.point_width = 3\n        graph.update_sizes()\n        sizes3 = graph.scatterplot_item.data[\"size\"]\n\n        np.testing.assert_almost_equal(2 * (sizes2 - sizes1), sizes3 - sizes1)\n\n    def test_sizes_custom_imputation(self):\n\n        def impute_max(size_data):\n            size_data[np.isnan(size_data)] = np.nanmax(size_data)\n\n        graph = self.graph\n\n        self.master.get_size_data = lambda: d\n        self.master.impute_sizes = impute_max\n        d = np.arange(10, dtype=float)\n        d[4] = np.nan\n        graph.reset_graph()\n        sizes = graph.scatterplot_item.data[\"size\"]\n        self.assertAlmostEqual(sizes[4], sizes[9])\n\n    def test_sizes_selection(self):\n        graph = self.graph\n        graph.get_size = lambda: np.arange(10, dtype=float)\n        graph.reset_graph()\n        np.testing.assert_almost_equal(\n            graph.scatterplot_item_sel.data[\"size\"]\n            - graph.scatterplot_item.data[\"size\"],\n            SELECTION_WIDTH)\n\n    @patch(\"Orange.widgets.visualize.owscatterplotgraph\"\n           \".MAX_N_VALID_SIZE_ANIMATE\", 5)\n    def test_size_animation(self):\n        begin_resizing = QSignalSpy(self.graph.begin_resizing)\n        step_resizing = QSignalSpy(self.graph.step_resizing)\n        end_resizing = QSignalSpy(self.graph.end_resizing)\n        self._update_sizes_for_points(5)\n        # first end_resizing is triggered in reset, thus wait for step_resizing\n        step_resizing.wait(200)\n        end_resizing.wait(200)\n        self.assertEqual(len(begin_resizing), 2)  # reset and update\n        self.assertEqual(len(step_resizing), 5)\n        self.assertEqual(len(end_resizing), 2)  # reset and update\n        self.assertEqual(self.graph.scatterplot_item.setSize.call_count, 6)\n        self._update_sizes_for_points(6)\n        self.graph.scatterplot_item.setSize.assert_called_once()\n\n    def _update_sizes_for_points(self, n: int):\n        arr = np.arange(n, dtype=float)\n        self.master.get_coordinates_data = lambda: (arr, arr)\n        self.master.get_size_data = lambda: arr\n        self.graph.reset_graph()\n        self.graph.scatterplot_item.setSize = Mock(\n            wraps=self.graph.scatterplot_item.setSize)\n        self.master.get_size_data = lambda: arr[::-1]\n        self.graph.update_sizes()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n\n    def test_colors_discrete(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        self.master.get_color_data = lambda: d\n        d = np.arange(10, dtype=float) % 2\n\n        graph.reset_graph()\n        data = graph.scatterplot_item.data\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"pen\"])))\n        self.assertTrue(\n            all(pen.color().hue() is palette[i % 2].hue()\n                for i, pen in enumerate(data[\"brush\"])))\n\n        # confirm that QPen/QBrush were reused\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 2)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)\n\n    def test_colors_discrete_nan(self):\n        self.master.is_continuous_color = lambda: False\n        palette = self.master.get_palette()\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        self.assertEqual(pens[0].color().hue(), palette[0].hue())\n        self.assertEqual(pens[1].color().hue(), palette[1].hue())\n        self.assertEqual(brushes[0].color().hue(), palette[0].hue())\n        self.assertEqual(brushes[1].color().hue(), palette[1].hue())\n        self.assertEqual(pens[4].color().hue(), QColor(128, 128, 128).hue())\n        self.assertEqual(brushes[4].color().hue(), QColor(128, 128, 128).hue())\n\n    def test_colors_continuous(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()  # I don't have a good test ... just don't crash\n\n        d[4] = np.nan\n        graph.update_colors()  # Ditto\n\n    def test_colors_continuous_reused(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        self.xy = (np.arange(100, dtype=float),\n                   np.arange(100, dtype=float))\n\n        d = np.arange(100, dtype=float)\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n\n        data = graph.scatterplot_item.data\n\n        self.assertEqual(len(data[\"pen\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"pen\"]))), 10)\n        self.assertEqual(len(data[\"brush\"]), 100)\n        self.assertLessEqual(len(set(map(id, data[\"brush\"]))), 10)\n\n    def test_colors_continuous_nan(self):\n        self.master.is_continuous_color = lambda: True\n        graph = self.graph\n\n        d = np.arange(10, dtype=float) % 2\n        d[4] = np.nan\n        self.master.get_color_data = lambda: d\n        graph.reset_graph()\n        pens = graph.scatterplot_item.data[\"pen\"]\n        brushes = graph.scatterplot_item.data[\"brush\"]\n        nan_color = QColor(*NAN_GREY)\n        self.assertEqual(pens[4].color().hue(), nan_color.hue())\n        self.assertEqual(brushes[4].color().hue(), nan_color.hue())\n\n    def test_colors_subset(self):\n        def run_tests():\n            self.master.get_subset_mask = lambda: None\n\n            graph.alpha_value = 42\n            graph.reset_graph()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 42)\n            self.assertEqual(brushes[1].color().alpha(), 42)\n            self.assertEqual(brushes[4].color().alpha(), 42)\n\n            graph.alpha_value = 123\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 123)\n            self.assertEqual(brushes[1].color().alpha(), 123)\n            self.assertEqual(brushes[4].color().alpha(), 123)\n\n            self.master.get_subset_mask = lambda: np.arange(10) >= 5\n            graph.update_colors()\n            brushes = graph.scatterplot_item.data[\"brush\"]\n            self.assertEqual(brushes[0].color().alpha(), 0)\n            self.assertEqual(brushes[1].color().alpha(), 0)\n            self.assertEqual(brushes[4].color().alpha(), 0)\n            self.assertEqual(brushes[5].color().alpha(), 255)\n            self.assertEqual(brushes[6].color().alpha(), 255)\n            self.assertEqual(brushes[7].color().alpha(), 255)\n\n        graph = self.graph\n\n        self.master.get_color_data = lambda: None\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n        d = np.arange(10, dtype=float) % 2\n        d[4:6] = np.nan\n        self.master.get_color_data = lambda: d\n\n        self.master.is_continuous_color = lambda: True\n        graph.reset_graph()\n        run_tests()\n\n        self.master.is_continuous_color = lambda: False\n        graph.reset_graph()\n        run_tests()\n\n    def test_colors_none(self):\n        graph = self.graph\n        graph.reset_graph()\n        hue = QColor(128, 128, 128).hue()\n\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)  # test QPen/QBrush reuse\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 1)\n\n        self.master.get_subset_mask = lambda: np.arange(10) < 5\n        graph.update_colors()\n        data = graph.scatterplot_item.data\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"pen\"]))\n        self.assertTrue(all(pen.color().hue() == hue for pen in data[\"brush\"]))\n        self.assertEqual(len(set(map(id, data[\"pen\"]))), 1)\n        self.assertEqual(len(set(map(id, data[\"brush\"]))), 2)  # transparent and colored\n\n    def test_colors_update_legend_and_density(self):\n        graph = self.graph\n        graph.update_legends = Mock()\n        graph.update_density = Mock()\n        graph.reset_graph()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n        graph.update_legends.reset_mock()\n        graph.update_density.reset_mock()\n\n        graph.update_coordinates()\n        graph.update_legends.assert_not_called()\n\n        graph.update_colors()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n\n    def test_selection_colors(self):\n        graph = self.graph\n        graph.reset_graph()\n        data = graph.scatterplot_item_sel.data\n\n        # One group\n        graph.select_by_indices(np.array([0, 1, 2, 3]))\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(4):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(4, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n\n        # Two groups\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_indices(np.array([4, 5, 6]))\n\n        graph.update_selection_colors()\n        pens = data[\"pen\"]\n        for i in range(7):\n            self.assertNotEqual(pens[i].style(), Qt.NoPen)\n        for i in range(7, 10):\n            self.assertEqual(pens[i].style(), Qt.NoPen)\n        self.assertEqual(len({pen.color().hue() for pen in pens[:4]}), 1)\n        self.assertEqual(len({pen.color().hue() for pen in pens[4:7]}), 1)\n        color1 = pens[3].color().hue()\n        color2 = pens[4].color().hue()\n        self.assertNotEqual(color1, color2)\n\n        # Two groups + sampling\n        graph.set_sample_size(7)\n        x = graph.scatterplot_item.getData()[0]\n        pens = graph.scatterplot_item_sel.data[\"pen\"]\n        for xi, pen in zip(x, pens):\n            if xi < 4:\n                self.assertEqual(pen.color().hue(), color1)\n            elif xi < 7:\n                self.assertEqual(pen.color().hue(), color2)\n            else:\n                self.assertEqual(pen.style(), Qt.NoPen)\n\n    def test_density(self):\n        graph = self.graph\n        density = object()\n        with patch(\"Orange.widgets.utils.classdensity.class_density_image\",\n                   return_value=density):\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n\n            graph.plot_widget.addItem = Mock()\n            graph.plot_widget.removeItem = Mock()\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.ones((10, ), dtype=float)\n            self.master.get_color_data = lambda: d\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n\n            d = np.arange(10) % 2\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.class_density = False\n            graph.update_colors()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n            graph.class_density = True\n            graph.update_colors()\n            self.assertIs(graph.density_img, density)\n            self.assertIs(graph.plot_widget.addItem.call_args[0][0], density)\n\n            graph.update_coordinates = lambda: (None, None)\n            graph.reset_graph()\n            self.assertIsNone(graph.density_img)\n            self.assertIs(graph.plot_widget.removeItem.call_args[0][0], density)\n\n    def test_labels(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n\n        # Label only selected\n        selected = [1, 3, 5]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(x) for x in selected])\n        x, y = graph.scatterplot_item.getData()\n        for i, index in enumerate(selected):\n            self.assertEqual(x[index], graph.labels[i].x())\n            self.assertEqual(y[index], graph.labels[i].y())\n\n        # Disable label only selected\n        self.graph.label_only_selected = False\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(i) for i in range(10)])\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        # Label only selected + sampling\n        selected = [1, 3, 4, 5, 6, 7, 9]\n        graph.select_by_indices(selected)\n        self.graph.label_only_selected = True\n        graph.update_labels()\n        graph.set_sample_size(5)\n        for label in graph.labels:\n            ind = int(label.textItem.toPlainText())\n            self.assertIn(ind, selected)\n            self.assertEqual(label.x(), x[ind])\n            self.assertEqual(label.y(), y[ind])\n\n    def test_label_mask_all_visible(self):\n        graph = self.graph\n\n        x, y = np.arange(10) / 10, np.arange(10) / 10\n        sel = np.array(\n            [True, True, False, False, False, True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False, True, True, False, False, False])\n        trues = np.ones(10, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel)\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), np.array(\n            [True, True, True, True, False, True, True, True, False, False]\n        ))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset)\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5, 10) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, False, True])\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        trues = np.ones(5, dtype=bool)\n\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), sel[5:])\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([True, True, True, False, True]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(graph._label_mask(x, y), subset[5:])\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), trues)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_label_mask_with_invisible_and_view(self):\n        graph = self.graph\n\n        x, y = np.arange(5, 10) / 10, np.arange(5) / 10\n        sel = np.array(\n            [True, True, False, False, False,  # these 5 are not in the sample\n             True, True, True, False, False])  # first and last out of the view\n        subset = np.array(\n            [True, False, True, True, False,  # these 5 are not in the sample\n             True, True, False, True, True])  # first and last out of the view\n        graph.sample_indices = np.arange(5, 10, dtype=int)\n        graph.view_box.viewRange = lambda: ((0.6, 1), (0, 0.3))\n        viewed = np.array([False, True, True, True, False])\n\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        # Selection present, subset is None\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, False, False]))\n\n        # Selection and subset present\n        graph.selection = sel\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, True, True, False]))\n\n        # No selection, subset present\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: subset\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        np.testing.assert_equal(\n            graph._label_mask(x, y),\n            np.array([False, True, False, True, False]))\n\n        # No selection, no subset\n        graph.selection = None\n        graph.master.get_subset_mask = lambda: None\n\n        graph.label_only_selected = False\n        np.testing.assert_equal(graph._label_mask(x, y), viewed)\n\n        graph.label_only_selected = True\n        self.assertIsNone(graph._label_mask(x, y))\n\n    def test_labels_observes_mask(self):\n        graph = self.graph\n        get_label_data = graph.master.get_label_data\n        graph.reset_graph()\n\n        self.assertEqual(graph.labels, [])\n\n        get_label_data.reset_mock()\n        graph._label_mask = lambda *_: None\n        graph.update_labels()\n        get_label_data.assert_not_called()\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph._label_mask = \\\n            lambda *_: np.array([False, True, True] + [False] * 7)\n        graph.update_labels()\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [\"1\", \"2\"])\n\n    def test_labels_update_coordinates(self):\n        graph = self.graph\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n\n        graph.reset_graph()\n        graph.set_sample_size(7)\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n        self.master.get_coordinates_data = \\\n            lambda: (np.arange(10, 20), np.arange(50, 60))\n        graph.update_coordinates()\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n\n    def test_shapes(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 3]\n                            for i, symbol in enumerate(symbols)))\n\n        d = np.arange(10, dtype=float) % 2\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertTrue(all(symbol == graph.CurveSymbols[i % 2]\n                            for i, symbol in enumerate(symbols)))\n\n        d = None\n        graph.update_shapes()\n        symbols = scatterplot_item.data[\"symbol\"]\n        self.assertEqual(len(set(symbols)), 1)\n\n    def test_shapes_nan(self):\n        graph = self.graph\n\n        self.master.get_shape_data = lambda: d\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n\n        graph.reset_graph()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2], '?')\n\n        d[:] = np.nan\n        graph.update_shapes()\n        self.assertTrue(\n            all(symbol == '?'\n                for symbol in graph.scatterplot_item.data[\"symbol\"]))\n\n        def impute0(data, _):\n            data[np.isnan(data)] = 0\n\n        self.master.impute_shapes = impute0\n        d = np.arange(10, dtype=float) % 3\n        d[2] = np.nan\n        graph.update_shapes()\n        self.assertEqual(graph.scatterplot_item.data[\"symbol\"][2],\n                         graph.CurveSymbols[0])\n\n    def test_show_grid(self):\n        graph = self.graph\n        show_grid = self.graph.plot_widget.showGrid = Mock()\n        graph.show_grid = False\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=False, y=False))\n\n        graph.show_grid = True\n        graph.update_grid_visibility()\n        self.assertEqual(show_grid.call_args[1], dict(x=True, y=True))\n\n    def test_show_legend(self):\n        graph = self.graph\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        shape_labels = color_labels = None  # Avoid pylint warning\n        self.master.get_shape_labels = lambda: shape_labels\n        self.master.get_color_labels = lambda: color_labels\n        for shape_labels in (None, [\"a\", \"b\"]):\n            for color_labels in (None, [\"c\", \"d\"], None):\n                for visible in (True, False, True):\n                    graph.show_legend = visible\n                    graph.update_legends()\n                    self.assertIs(\n                        shape_legend.call_args[0][0],\n                        visible and bool(shape_labels),\n                        msg=\"error at {}, {}\".format(visible, shape_labels))\n                    self.assertIs(\n                        color_legend.call_args[0][0],\n                        visible and bool(color_labels),\n                        msg=\"error at {}, {}\".format(visible, color_labels))\n\n    def test_show_legend_no_data(self):\n        graph = self.graph\n        self.master.get_shape_labels = lambda: [\"a\", \"b\"]\n        self.master.get_color_labels = lambda: [\"c\", \"d\"]\n        self.master.get_shape_data = lambda: np.arange(10) % 2\n        self.master.get_color_data = lambda: np.arange(10) < 6\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n        self.master.get_coordinates_data = lambda: (None, None)\n        graph.reset_graph()\n        self.assertFalse(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n\n    def test_legend_combine(self):\n        master = self.master\n        graph = self.graph\n\n        master.get_shape_data = lambda: np.arange(10, dtype=float) % 3\n        master.get_color_data = lambda: 2 * np.arange(10, dtype=float) % 3\n\n        graph.reset_graph()\n\n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n\n        master.get_shape_labels = lambda: [\"a\", \"b\"]\n        master.get_color_labels = lambda: [\"c\", \"d\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n\n        master.get_color_labels = lambda: [\"a\", \"b\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.get_color_data = lambda: np.arange(10, dtype=float) % 3\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertFalse(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n        master.is_continuous_color = lambda: True\n        master.get_color_data = lambda: np.arange(10, dtype=float)\n        master.get_color_labels = lambda: None\n        graph.update_colors()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n        self.assertEqual(len(graph.shape_legend.items), 2)\n\n    def test_select_by_click(self):\n        graph = self.graph\n        graph.reset_graph()\n        points = graph.scatterplot_item.points()\n        graph.select_by_click(None, [points[2]])\n        np.testing.assert_almost_equal(graph.get_selection(), [2])\n        with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                   lambda: Qt.ShiftModifier):\n            graph.select_by_click(None, points[3:6])\n        np.testing.assert_almost_equal(\n            list(graph.get_selection()), [2, 3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 1, 2, 2, 2, 0, 0, 0, 0])\n\n    def test_select_by_rectangle(self):\n        graph = self.graph\n        coords = np.array(\n            [(x, y) for y in range(10) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n\n        graph.reset_graph()\n        graph.select_by_rectangle(QRectF(3, 5, 3.9, 2.9))\n        self.assertTrue(\n            all(selected == (3 <= coords[0][i] <= 6 and 5 <= coords[1][i] <= 7)\n                for i, selected in enumerate(graph.selection)))\n\n    def test_select_by_indices(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        def select(modifiers, indices):\n            with patch(\"AnyQt.QtWidgets.QApplication.keyboardModifiers\",\n                       lambda: modifiers):\n                graph.update_selection_colors = Mock()\n                graph.update_labels = Mock()\n                self.master.selection_changed = Mock()\n\n                graph.select_by_indices(np.array(indices))\n                graph.update_selection_colors.assert_called_with()\n                if graph.label_only_selected:\n                    graph.update_labels.assert_called_with()\n                else:\n                    graph.update_labels.assert_not_called()\n                self.master.selection_changed.assert_called_with()\n\n        select(0, [7, 8, 9])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 0, 0, 1, 1, 1])\n\n        select(Qt.ShiftModifier | Qt.ControlModifier, [5, 6])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 0, 1, 1, 1, 1, 1])\n\n        select(Qt.ShiftModifier, [3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 2, 2, 2, 1, 1, 1, 1])\n\n        select(Qt.AltModifier, [1, 3, 7])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 0, 2, 2, 1, 0, 1, 1])\n\n        select(0, [1, 8])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 1, 0, 0, 0, 0, 0, 0, 1, 0])\n\n        graph.label_only_selected = False\n        select(0, [3, 4])\n\n    def test_unselect_all(self):\n        graph = self.graph\n        graph.reset_graph()\n        graph.label_only_selected = True\n\n        graph.select_by_indices([3, 4, 5])\n        np.testing.assert_almost_equal(\n            graph.selection, [0, 0, 0, 1, 1, 1, 0, 0, 0, 0])\n\n        graph.update_selection_colors = Mock()\n        graph.update_labels = Mock()\n        self.master.selection_changed = Mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_called_with()\n        graph.update_labels.assert_called_with()\n        self.master.selection_changed.assert_called_with()\n\n        graph.update_selection_colors.reset_mock()\n        graph.update_labels.reset_mock()\n        self.master.selection_changed.reset_mock()\n\n        graph.unselect_all()\n        self.assertIsNone(graph.selection)\n        graph.update_selection_colors.assert_not_called()\n        graph.update_labels.assert_not_called()\n        self.master.selection_changed.assert_not_called()\n\n    def test_hiding_too_many_labels(self):\n        spy = QSignalSpy(self.graph.too_many_labels)\n        self.graph.MAX_VISIBLE_LABELS = 5\n\n        graph = self.graph\n        coords = np.array(\n            [(x, 0) for x in range(10)], dtype=float).T\n        self.master.get_coordinates_data = lambda: coords\n        graph.reset_graph()\n\n        self.assertFalse(spy and spy[-1][0])\n\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 4, 4))\n        graph.view_box.sigRangeChangedManually.emit(((1, 5), (-1, 3)))\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.view_box.setRange(QRectF(1, -1, 8, 8))\n        graph.view_box.sigRangeChangedManually.emit(((1, 9), (-1, 7)))\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.label_only_selected = True\n        graph.update_labels()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3, 4, 5, 6])\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.selection_select([1, 2, 3])\n        self.assertFalse(spy[-1][0])\n        self.assertTrue(bool(self.graph.labels))\n\n        graph.label_only_selected = False\n        graph.update_labels()\n        self.assertTrue(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n        graph.clear()\n        self.assertFalse(spy[-1][0])\n        self.assertFalse(bool(self.graph.labels))\n\n    def test_no_needless_buildatlas(self):\n        graph = self.graph\n        graph.reset_graph()\n        self.assertIsNone(graph.scatterplot_item.fragmentAtlas.atlas)\n\n\nif __name__ == \"__main__\":\n    import unittest\n    unittest.main()\n"
    ],
    "test_file_names": [
        "test_1.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "Starting Orange installation attempts...\nAttempting installation with Python 3.7...\nrunning build_ext\nrunning build_src\nbuild_src\nbuilding extension \"Orange.classification._simple_tree\" sources\nbuilding extension \"Orange.classification._tree_scorers\" sources\nbuilding extension \"Orange.data._valuecount\" sources\nbuilding extension \"Orange.data._contingency\" sources\nbuilding extension \"Orange.data._io\" sources\nbuilding extension \"Orange.data._variable\" sources\nbuilding extension \"Orange.distance._distance\" sources\nbuilding extension \"Orange.preprocess._discretize\" sources\nbuilding extension \"Orange.preprocess._relieff\" sources\nbuilding extension \"Orange.projection._som\" sources\nbuilding extension \"Orange.widgets.utils._grid_density\" sources\nbuild_src: building npy-pkg config files\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmprxg991jg/tmp\ncreating /tmp/tmprxg991jg/tmp/tmprxg991jg\ncompile options: '-MMD -MF /tmp/tmprxg991jg/file.c.d -c'\ncc: /tmp/tmprxg991jg/file.c\ncustomize UnixCCompiler using build_ext\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmp_ap8ep9d/tmp\ncreating /tmp/tmp_ap8ep9d/tmp/tmp_ap8ep9d\ncompile options: '-MMD -MF /tmp/tmp_ap8ep9d/file.c.d -c'\ncc: /tmp/tmp_ap8ep9d/file.c\ncustomize UnixCCompiler using build_ext\nbuilding 'Orange.classification._simple_tree' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange\ncreating build/temp.linux-x86_64-3.7/Orange/classification\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/classification/_simple_tree.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/classification/_simple_tree.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/classification/_simple_tree.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.classification._tree_scorers' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/classification/_tree_scorers.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/classification/_tree_scorers.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/classification/_tree_scorers.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._valuecount' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/data\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_valuecount.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_valuecount.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_valuecount.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._contingency' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_contingency.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_contingency.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_contingency.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._io' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_io.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_io.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_io.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._variable' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_variable.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_variable.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_variable.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.distance._distance' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/distance\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/distance/_distance.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/distance/_distance.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/distance/_distance.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.preprocess._discretize' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/preprocess\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/preprocess/_discretize.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/preprocess/_discretize.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/preprocess/_discretize.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.preprocess._relieff' extension\ncompiling C++ sources\nC compiler: c++ -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\nc++: Orange/preprocess/_relieff.cpp\nc++ -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/preprocess/_relieff.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/preprocess/_relieff.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.projection._som' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/projection\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/projection/_som.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/projection/_som.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/projection/_som.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.widgets.utils._grid_density' extension\ncompiling C++ sources\nC compiler: c++ -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/widgets\ncreating build/temp.linux-x86_64-3.7/Orange/widgets/utils\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\nc++: Orange/widgets/utils/_grid_density.cpp\nc++ -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/widgets/utils/_grid_density.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/widgets/utils/_grid_density.cpython-37m-x86_64-linux-gnu.so\nrunning develop\nrunning build_scripts\nrunning egg_info\nrunning build_src\nbuild_src\nbuilding extension \"Orange.classification._simple_tree\" sources\nbuilding extension \"Orange.classification._tree_scorers\" sources\nbuilding extension \"Orange.data._valuecount\" sources\nbuilding extension \"Orange.data._contingency\" sources\nbuilding extension \"Orange.data._io\" sources\nbuilding extension \"Orange.data._variable\" sources\nbuilding extension \"Orange.distance._distance\" sources\nbuilding extension \"Orange.preprocess._discretize\" sources\nbuilding extension \"Orange.preprocess._relieff\" sources\nbuilding extension \"Orange.projection._som\" sources\nbuilding extension \"Orange.widgets.utils._grid_density\" sources\nbuild_src: building npy-pkg config files\ncreating Orange3.egg-info\nwriting Orange3.egg-info/PKG-INFO\nwriting dependency_links to Orange3.egg-info/dependency_links.txt\nwriting entry points to Orange3.egg-info/entry_points.txt\nwriting requirements to Orange3.egg-info/requires.txt\nwriting top-level names to Orange3.egg-info/top_level.txt\nwriting manifest file 'Orange3.egg-info/SOURCES.txt'\nreading manifest file 'Orange3.egg-info/SOURCES.txt'\nreading manifest template 'MANIFEST.in'\nwarning: no files found matching 'README*' under directory 'Orange'\nwarning: no files found matching 'LICENSE' under directory 'Orange'\nwarning: no files found matching '*.basket' under directory 'Orange/datasets'\nwarning: no files found matching '*.js' under directory 'Orange/widgets'\nwarning: no files found matching '*.css' under directory 'Orange/widgets'\nwarning: no files found matching '*.html' under directory 'Orange/widgets'\nwarning: no files found matching 'COPYING'\nadding license file 'LICENSE'\nwriting manifest file 'Orange3.egg-info/SOURCES.txt'\nrunning build_ext\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmpsf_flihu/tmp\ncreating /tmp/tmpsf_flihu/tmp/tmpsf_flihu\ncompile options: '-MMD -MF /tmp/tmpsf_flihu/file.c.d -c'\ncc: /tmp/tmpsf_flihu/file.c\ncustomize UnixCCompiler using build_ext\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmpc5oz7wxs/tmp\ncreating /tmp/tmpc5oz7wxs/tmp/tmpc5oz7wxs\ncompile options: '-MMD -MF /tmp/tmpc5oz7wxs/file.c.d -c'\ncc: /tmp/tmpc5oz7wxs/file.c\ncustomize UnixCCompiler using build_ext\nCreating /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/Orange3.egg-link (link to .)\nAdding Orange3 3.24.0.dev0+1a53b71 to easy-install.pth file\nInstalling orange-canvas script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\n\nInstalled /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf\nProcessing dependencies for Orange3==3.24.0.dev0+1a53b71\nSearching for XlsxWriter==3.2.0\nBest match: XlsxWriter 3.2.0\nAdding XlsxWriter 3.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for xlrd==2.0.1\nBest match: xlrd 2.0.1\nAdding xlrd 2.0.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for setuptools==59.8.0\nBest match: setuptools 59.8.0\nAdding setuptools 59.8.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for serverfiles==0.3.1\nBest match: serverfiles 0.3.1\nAdding serverfiles 0.3.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for scipy==1.7.3\nBest match: scipy 1.7.3\nAdding scipy 1.7.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for scikit-learn==1.0.2\nBest match: scikit-learn 1.0.2\nAdding scikit-learn 1.0.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for requests==2.31.0\nBest match: requests 2.31.0\nAdding requests 2.31.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for PyYAML==6.0.1\nBest match: PyYAML 6.0.1\nAdding PyYAML 6.0.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for python-louvain==0.16\nBest match: python-louvain 0.16\nAdding python-louvain 0.16 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for pyqtgraph==0.12.4\nBest match: pyqtgraph 0.12.4\nAdding pyqtgraph 0.12.4 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for pip==24.0\nBest match: pip 24.0\nAdding pip 24.0 to easy-install.pth file\nInstalling pip script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\nInstalling pip3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\nInstalling pip3.10 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for pandas==1.3.5\nBest match: pandas 1.3.5\nAdding pandas 1.3.5 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for orange-widget-base==4.0.1\nBest match: orange-widget-base 4.0.1\nAdding orange-widget-base 4.0.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for orange-canvas-core==0.1.35\nBest match: orange-canvas-core 0.1.35\nAdding orange-canvas-core 0.1.35 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for openTSNE==1.0.1\nBest match: openTSNE 1.0.1\nAdding openTSNE 1.0.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for numpy==1.17.5\nBest match: numpy 1.17.5\nAdding numpy 1.17.5 to easy-install.pth file\nInstalling f2py script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\nInstalling f2py3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\nInstalling f2py3.7 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for networkx==2.6.3\nBest match: networkx 2.6.3\nAdding networkx 2.6.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for matplotlib==3.5.3\nBest match: matplotlib 3.5.3\nAdding matplotlib 3.5.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for keyrings.alt==4.2.0\nBest match: keyrings.alt 4.2.0\nAdding keyrings.alt 4.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for keyring==24.1.1\nBest match: keyring 24.1.1\nAdding keyring 24.1.1 to easy-install.pth file\nInstalling keyring script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for joblib==1.3.2\nBest match: joblib 1.3.2\nAdding joblib 1.3.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for docutils==0.20.1\nBest match: docutils 0.20.1\nAdding docutils 0.20.1 to easy-install.pth file\nInstalling docutils script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for chardet==5.2.0\nBest match: chardet 5.2.0\nAdding chardet 5.2.0 to easy-install.pth file\nInstalling chardetect script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for Bottleneck==1.4.0\nBest match: Bottleneck 1.4.0\nAdding Bottleneck 1.4.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for AnyQt==0.2.0\nBest match: AnyQt 0.2.0\nAdding AnyQt 0.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for threadpoolctl==3.1.0\nBest match: threadpoolctl 3.1.0\nAdding threadpoolctl 3.1.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for charset-normalizer==3.4.1\nBest match: charset-normalizer 3.4.1\nAdding charset-normalizer 3.4.1 to easy-install.pth file\nInstalling normalizer script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for urllib3==2.0.7\nBest match: urllib3 2.0.7\nAdding urllib3 2.0.7 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for certifi==2024.12.14\nBest match: certifi 2024.12.14\nAdding certifi 2024.12.14 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for idna==3.10\nBest match: idna 3.10\nAdding idna 3.10 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for python-dateutil==2.9.0.post0\nBest match: python-dateutil 2.9.0.post0\nAdding python-dateutil 2.9.0.post0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for pytz==2024.2\nBest match: pytz 2024.2\nAdding pytz 2024.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for packaging==24.0\nBest match: packaging 24.0\nAdding packaging 24.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for requests-cache==1.1.1\nBest match: requests-cache 1.1.1\nAdding requests-cache 1.1.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for importlib-metadata==6.7.0\nBest match: importlib-metadata 6.7.0\nAdding importlib-metadata 6.7.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for commonmark==0.9.1\nBest match: commonmark 0.9.1\nAdding commonmark 0.9.1 to easy-install.pth file\nInstalling cmark script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for dictdiffer==0.9.0\nBest match: dictdiffer 0.9.0\nAdding dictdiffer 0.9.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for qasync==0.25.0\nBest match: qasync 0.25.0\nAdding qasync 0.25.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for kiwisolver==1.4.5\nBest match: kiwisolver 1.4.5\nAdding kiwisolver 1.4.5 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for fonttools==4.38.0\nBest match: fonttools 4.38.0\nAdding fonttools 4.38.0 to easy-install.pth file\nInstalling fonttools script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\nInstalling pyftmerge script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\nInstalling pyftsubset script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\nInstalling ttx script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for cycler==0.11.0\nBest match: cycler 0.11.0\nAdding cycler 0.11.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for pyparsing==3.1.4\nBest match: pyparsing 3.1.4\nAdding pyparsing 3.1.4 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for Pillow==9.5.0\nBest match: Pillow 9.5.0\nAdding Pillow 9.5.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for jaraco.classes==3.2.3\nBest match: jaraco.classes 3.2.3\nAdding jaraco.classes 3.2.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for jeepney==0.8.0\nBest match: jeepney 0.8.0\nAdding jeepney 0.8.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for SecretStorage==3.3.3\nBest match: SecretStorage 3.3.3\nAdding SecretStorage 3.3.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for importlib-resources==5.12.0\nBest match: importlib-resources 5.12.0\nAdding importlib-resources 5.12.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for six==1.17.0\nBest match: six 1.17.0\nAdding six 1.17.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for platformdirs==4.0.0\nBest match: platformdirs 4.0.0\nAdding platformdirs 4.0.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for cattrs==23.1.2\nBest match: cattrs 23.1.2\nAdding cattrs 23.1.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for attrs==24.2.0\nBest match: attrs 24.2.0\nAdding attrs 24.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for url-normalize==1.4.3\nBest match: url-normalize 1.4.3\nAdding url-normalize 1.4.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for typing-extensions==4.7.1\nBest match: typing-extensions 4.7.1\nAdding typing-extensions 4.7.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for zipp==3.15.0\nBest match: zipp 3.15.0\nAdding zipp 3.15.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for more-itertools==9.1.0\nBest match: more-itertools 9.1.0\nAdding more-itertools 9.1.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for cryptography==44.0.0\nBest match: cryptography 44.0.0\nAdding cryptography 44.0.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for exceptiongroup==1.2.2\nBest match: exceptiongroup 1.2.2\nAdding exceptiongroup 1.2.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for cffi==1.15.1\nBest match: cffi 1.15.1\nAdding cffi 1.15.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nSearching for pycparser==2.21\nBest match: pycparser 2.21\nAdding pycparser 2.21 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages\nFinished processing dependencies for Orange3==3.24.0.dev0+1a53b71\nVerifying Orange installation...\n✅ Orange installation successful!\nSuccessfully installed orange using Python 3.7\n",
    "setup_res_stderr": "Using CPython 3.7.9\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 18 packages in 66ms\nPrepared 18 packages in 41ms\nInstalled 18 packages in 674ms\n + cython==0.29.37\n + exceptiongroup==1.2.2\n + importlib-metadata==6.7.0\n + iniconfig==2.0.0\n + numpy==1.17.5\n + packaging==24.0\n + pluggy==1.2.0\n + pyqt5==5.15.10\n + pyqt5-qt5==5.15.16\n + pyqt5-sip==12.13.0\n + pyqtwebengine==5.15.6\n + pyqtwebengine-qt5==5.15.16\n + pytest==7.4.4\n + setuptools==59.8.0\n + tomli==2.0.1\n + typing-extensions==4.7.1\n + wheel==0.42.0\n + zipp==3.15.0\nResolved 38 packages in 226ms\nInstalled 33 packages in 483ms\n + bottleneck==1.4.0\n + certifi==2024.12.14\n + cffi==1.15.1\n + chardet==5.2.0\n + charset-normalizer==3.4.1\n + cryptography==44.0.0\n + idna==3.10\n + importlib-resources==5.12.0\n + jaraco-classes==3.2.3\n + jeepney==0.8.0\n + joblib==1.3.2\n + keyring==24.1.1\n + keyrings-alt==4.2.0\n + more-itertools==9.1.0\n + networkx==2.6.3\n + opentsne==1.0.1\n + pandas==1.3.5\n + pip==24.0\n + pycparser==2.21\n + python-dateutil==2.9.0.post0\n + python-louvain==0.16\n + pytz==2024.2\n + pyyaml==6.0.1\n + requests==2.31.0\n + scikit-learn==1.0.2\n + scipy==1.7.3\n + secretstorage==3.3.3\n + serverfiles==0.3.1\n + six==1.17.0\n + threadpoolctl==3.1.0\n + urllib3==2.0.7\n + xlrd==2.0.1\n + xlsxwriter==3.2.0\nResolved 34 packages in 179ms\nInstalled 19 packages in 27ms\n + anyqt==0.2.0\n + attrs==24.2.0\n + cattrs==23.1.2\n + commonmark==0.9.1\n + cycler==0.11.0\n + dictdiffer==0.9.0\n + docutils==0.20.1\n + fonttools==4.38.0\n + kiwisolver==1.4.5\n + matplotlib==3.5.3\n + orange-canvas-core==0.1.35\n + orange-widget-base==4.0.1\n + pillow==9.5.0\n + platformdirs==4.0.0\n + pyparsing==3.1.4\n + pyqtgraph==0.12.4\n + qasync==0.25.0\n + requests-cache==1.1.1\n + url-normalize==1.4.3\nResolved 2 packages in 3ms\nInstalled 2 packages in 6ms\n + psycopg2==2.9.9\n + pymssql==2.3.2\nAudited 1 package in 32ms\nAudited 2 packages in 1ms\nOrange/classification/_simple_tree.c: In function ‘gain_ratio_c’:\nOrange/classification/_simple_tree.c:63:9: warning: implicit declaration of function ‘qsort_r’; did you mean ‘qsort’? [-Wimplicit-function-declaration]\n   63 |         qsort_r(base, nel, size, compar, thunk)\n      |         ^~~~~~~\nOrange/classification/_simple_tree.c:147:9: note: in expansion of macro ‘QSORT_R_FUNC’\n  147 |         QSORT_R_FUNC(examples, size, sizeof(struct Example), (void*) &compar_attr, compar_examples);\n      |         ^~~~~~~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/classification/_tree_scorers.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_2find_threshold_entropy’:\nOrange/classification/_tree_scorers.c:3115:27: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 3115 |   __pyx_t_7 = ((__pyx_v_N <= __pyx_v_min_leaf) != 0);\n      |                           ^~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_6find_threshold_MSE’:\nOrange/classification/_tree_scorers.c:4619:27: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 4619 |   __pyx_t_1 = ((__pyx_v_N <= __pyx_v_min_leaf) != 0);\n      |                           ^~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_8find_binarization_MSE’:\nOrange/classification/_tree_scorers.c:5396:43: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5396 |           for (__pyx_t_22 = 0; __pyx_t_22 < __pyx_t_21; __pyx_t_22+=1) {\n      |                                           ^\nOrange/classification/_tree_scorers.c:5517:39: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5517 |           __pyx_t_27 = ((__pyx_v_left >= __pyx_v_min_leaf) != 0);\n      |                                       ^~\nOrange/classification/_tree_scorers.c:5523:53: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5523 |           __pyx_t_27 = (((__pyx_v_N - __pyx_v_left) >= __pyx_v_min_leaf) != 0);\n      |                                                     ^~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_14compute_predictions_csr’:\nOrange/classification/_tree_scorers.c:7051:41: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 7051 |         for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) {\n      |                                         ^\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_16compute_predictions_csc’:\nOrange/classification/_tree_scorers.c:7741:41: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 7741 |         for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) {\n      |                                         ^\nOrange/classification/_tree_scorers.c:7801:143: warning: comparison of integer expressions of different signedness: ‘__pyx_t_5numpy_int32_t’ {aka ‘int’} and ‘unsigned int’ [-Wsign-compare]\n 7801 |               __pyx_t_17 = (((*((__pyx_t_5numpy_int32_t *) ( /* dim=0 */ (__pyx_v_indices.data + __pyx_t_18 * __pyx_v_indices.strides[0]) ))) != __pyx_v_i) != 0);\n      |                                                                                                                                               ^~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/data/_valuecount.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/data/_contingency.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nOrange/data/_io.c: In function ‘__pyx_pf_6Orange_4data_3_io_sparse_read_float.constprop’:\nOrange/data/_io.c:3881:24: warning: ‘__pyx_v_decs’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3881 |           __pyx_v_decs = (__pyx_v_decs / 10.0);\n      |           ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:4070:24: warning: ‘__pyx_v_value’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4070 |           __pyx_t_10 = PyFloat_FromDouble(__pyx_v_value); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 221, __pyx_L5_error)\n      |                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:480:40: warning: ‘__pyx_v_attr_index’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n  480 |   #define PyInt_FromLong               PyLong_FromLong\n      |                                        ^~~~~~~~~~~~~~~\nOrange/data/_io.c:1301:7: note: ‘__pyx_v_attr_index’ was declared here\n 1301 |   int __pyx_v_attr_index;\n      |       ^~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:2935:25: warning: ‘__pyx_v_atomp’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 2935 |           __pyx_v_atomp = (__pyx_v_atomp + 1);\n      |           ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/distance/_distance.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/preprocess/_discretize.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/preprocess/_relieff.cpp:581:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/projection/_som.c:598:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_5update_hex’:\nOrange/projection/_som.c:3655:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3655 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:3654:7: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3654 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_7get_winners_sparse’:\nOrange/projection/_som.c:4547:223: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4547 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_38, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_39, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_y;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:4114:7: note: ‘__pyx_v_win_y’ was declared here\n 4114 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:4536:223: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4536 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_36, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_37, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_x;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:4113:7: note: ‘__pyx_v_win_x’ was declared here\n 4113 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pf_6Orange_10projection_4_som_8update_sparse.constprop’:\nOrange/projection/_som.c:4746:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4746 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:4745:7: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4745 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_3update’:\nOrange/projection/_som.c:3141:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3141 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_1get_winners’:\nOrange/projection/_som.c:2964:223: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 2964 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_27, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_28, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_y;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:2665:7: note: ‘__pyx_v_win_y’ was declared here\n 2665 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:2953:223: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 2953 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_25, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_26, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_x;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:2664:7: note: ‘__pyx_v_win_x’ was declared here\n 2664 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pf_6Orange_10projection_4_som_10update_sparse_hex.constprop’:\nOrange/projection/_som.c:5515:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 5515 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:5514:7: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 5514 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/setuptools/command/install.py:37: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.\n  setuptools.SetuptoolsDeprecationWarning,\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/setuptools/command/easy_install.py:159: EasyInstallDeprecationWarning: easy_install command is deprecated. Use build and pip and other standards-based tools.\n  EasyInstallDeprecationWarning,\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/setuptools/command/install.py:37: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.\n  setuptools.SetuptoolsDeprecationWarning,\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf/.venv/lib/python3.7/site-packages/setuptools/command/egg_info.py:628: SetuptoolsDeprecationWarning: Custom 'build_py' does not implement 'get_data_files_without_manifest'.\nPlease extend command classes from setuptools instead of distutils.\n  SetuptoolsDeprecationWarning\n",
    "new_commit_res_code": 1,
    "new_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.7.9, pytest-7.4.4, pluggy-1.2.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf\ncollected 49 items\n\nr2e_tests/test_1.py .......F..F.....F.ssF..F...................FFF..F    [100%]\n\n=================================== FAILURES ===================================\n_________ TestOWScatterPlotBase.test_colors_update_legend_and_density __________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_colors_update_legend_and_density>\n\n    def test_colors_update_legend_and_density(self):\n        graph = self.graph\n        graph.update_legends = Mock()\n        graph.update_density = Mock()\n        graph.reset_graph()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n    \n        graph.update_legends.reset_mock()\n        graph.update_density.reset_mock()\n    \n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:654: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x7959fd9eae10>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x7959debfc190>\nx = array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])\ny = array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n_____________________ TestOWScatterPlotBase.test_jittering _____________________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_jittering>\n\n    def test_jittering(self):\n        graph = self.graph\n        graph.jitter_size = 10\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        a10 = np.arange(10)\n        self.assertTrue(np.any(np.nonzero(a10 - x)))\n        self.assertTrue(np.any(np.nonzero(a10 - y)))\n        np.testing.assert_array_less(a10 - x, 1)\n        np.testing.assert_array_less(a10 - y, 1)\n    \n        graph.jitter_size = 0\n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:343: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x795a02c97cd0>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x7959f8460550>\nx = array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])\ny = array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n_____________ TestOWScatterPlotBase.test_labels_update_coordinates _____________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_labels_update_coordinates>\n\n    def test_labels_update_coordinates(self):\n        graph = self.graph\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n    \n        graph.reset_graph()\n        graph.set_sample_size(7)\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n    \n        self.master.get_coordinates_data = \\\n            lambda: (np.arange(10, 20), np.arange(50, 60))\n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:1001: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x7959f852eeb0>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x795a02defd70>\nx = array([12, 18, 14, 19, 11, 16, 17]), y = array([52, 58, 54, 59, 51, 56, 57])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n______________ TestOWScatterPlotBase.test_no_needless_buildatlas _______________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_no_needless_buildatlas>\n\n    def test_no_needless_buildatlas(self):\n        graph = self.graph\n        graph.reset_graph()\n>       self.assertIsNone(graph.scatterplot_item.fragmentAtlas.atlas)\nE       AttributeError: 'SymbolAtlas' object has no attribute 'atlas'\n\nr2e_tests/test_1.py:1294: AttributeError\n_____________________ TestOWScatterPlotBase.test_sampling ______________________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_sampling>\n\n    def test_sampling(self):\n        graph = self.graph\n        master = self.master\n    \n        # Enable sampling before getting the data\n        graph.set_sample_size(3)\n        xy = self.xy = (np.arange(10, dtype=float),\n                        np.arange(0, 30, 3, dtype=float))\n        d = np.arange(10, dtype=float)\n        master.get_size_data = lambda: d\n        master.get_shape_data = lambda: d % 5 if d is not None else None\n        master.get_color_data = lambda: d\n        master.get_label_data = lambda: \\\n            np.array([str(x) for x in d], dtype=object)\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n    \n        # Check proper sampling\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertNotEqual(x[0], x[1])\n        self.assertNotEqual(x[0], x[2])\n        self.assertNotEqual(x[1], x[2])\n        np.testing.assert_almost_equal(3 * x, y)\n    \n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n    \n        # Check that sample is extended when sample size is changed\n        graph.set_sample_size(4)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s = data[\"size\"] - graph.MinShapeSize\n        precise_s = (x - min(x)) / (max(x) - min(x)) * max(s)\n        np.testing.assert_almost_equal(s, precise_s, decimal=0)\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n    \n        # Disable sampling\n        graph.set_sample_size(None)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        np.testing.assert_almost_equal(x, xy[0])\n        np.testing.assert_almost_equal(y, xy[1])\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in d])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in d])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in d])\n    \n        # Enable sampling when data is already present and not sampled\n        graph.set_sample_size(3)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n    \n        # Update data when data is present and sampling is enabled\n        xy[0][:] = np.arange(9, -1, -1, dtype=float)\n        d = xy[0]\n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:259: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x7959dead1370>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x7959deb27eb0>\nx = array([7., 1., 5.]), y = array([ 6., 24., 12.])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n________________ TestOWScatterPlotBase.test_update_coordinates _________________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_update_coordinates>\n\n    def test_update_coordinates(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        graph.reset_graph()\n    \n        scatterplot_item = graph.scatterplot_item\n        scatterplot_item_sel = graph.scatterplot_item_sel\n        data = scatterplot_item.data\n    \n        np.testing.assert_almost_equal(scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(scatterplot_item_sel.getData(), xy)\n        scatterplot_item.setSize([5, 6])\n        scatterplot_item.setSymbol([7, 8])\n        scatterplot_item.setPen([mkPen(9), mkPen(10)])\n        scatterplot_item.setBrush([11, 12])\n        data[\"data\"] = np.array([13, 14])\n    \n        xy[0][0] = 0\n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:92: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x7959d42be230>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x7959d42867d0>\nx = array([0, 2]), y = array([3, 4])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n__________ TestOWScatterPlotBase.test_update_coordinates_and_density ___________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_update_coordinates_and_density>\n\n    def test_update_coordinates_and_density(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 0\n        graph.update_density = Mock()\n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:127: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x7959e3e5eaf0>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x7959e3ed7730>\nx = array([0, 2]), y = array([3, 4])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n___________ TestOWScatterPlotBase.test_update_coordinates_and_labels ___________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_update_coordinates_and_labels>\n\n    def test_update_coordinates_and_labels(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1., 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 1.5\n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:113: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x7959e3edeeb0>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x795a02c50d70>\nx = array([1.5, 2. ]), y = array([3, 4])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n___________ TestOWScatterPlotBase.test_update_coordinates_reset_view ___________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_update_coordinates_reset_view>\n\n    def test_update_coordinates_reset_view(self):\n        graph = self.graph\n        graph.view_box.setRange = self.setRange\n        xy = self.xy = (np.array([2, 1]), np.array([3, 10]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(self.last_setRange, [[1, 2], [3, 10]])\n    \n        xy[0][1] = 0\n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:139: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x795a02cd8870>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x795a02deff50>\nx = array([2, 0]), y = array([ 3, 10])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_continuous\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_continuous_nan\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_continuous_reused\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_discrete\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_discrete_nan\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_none\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_subset\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_density\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_hiding_too_many_labels\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_label_mask_all_visible\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_label_mask_with_invisible\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_label_mask_with_invisible_and_view\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_labels\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_labels_observes_mask\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_legend_combine\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_reset_calls_all_updates_and_update_doesnt\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_reset_graph_no_data\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_sampling_keeps_selection\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_select_by_click\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_select_by_indices\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_select_by_rectangle\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_selection_colors\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_shapes\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_shapes_nan\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_show_grid\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_show_legend\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_show_legend_no_data\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_size_animation\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_size_normalization\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_size_rounding_half_pixel\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_size_with_nans\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_sizes_all_same_or_nan\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_sizes_custom_imputation\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_sizes_point_width_is_linear\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_sizes_selection\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_unselect_all\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_update_coordinates_indices\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_update_coordinates_no_data\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:86: minimum size not tested as .widget was not set\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:92: msg base class not tested as .widget was not set\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_update_legend_and_density\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_jittering - ValueErro...\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_labels_update_coordinates\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_no_needless_buildatlas\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_sampling - ValueError...\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_update_coordinates - ...\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_update_coordinates_and_density\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_update_coordinates_and_labels\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_update_coordinates_reset_view\n=================== 9 failed, 38 passed, 2 skipped in 7.86s ====================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.7.9, pytest-7.4.4, pluggy-1.2.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_1a53b71b2cfdb3037c385474f5a8fd5f07f15bdf\ncollected 49 items\n\nr2e_tests/test_1.py .......F..F.....FFssF..F...................FFF..F    [100%]\n\n=================================== FAILURES ===================================\n_________ TestOWScatterPlotBase.test_colors_update_legend_and_density __________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_colors_update_legend_and_density>\n\n    def test_colors_update_legend_and_density(self):\n        graph = self.graph\n        graph.update_legends = Mock()\n        graph.update_density = Mock()\n        graph.reset_graph()\n        graph.update_legends.assert_called_with()\n        graph.update_density.assert_called_with()\n    \n        graph.update_legends.reset_mock()\n        graph.update_density.reset_mock()\n    \n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:654: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x7b318250e5f0>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x7b3182534b90>\nx = array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])\ny = array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n_____________________ TestOWScatterPlotBase.test_jittering _____________________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_jittering>\n\n    def test_jittering(self):\n        graph = self.graph\n        graph.jitter_size = 10\n        graph.reset_graph()\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        a10 = np.arange(10)\n        self.assertTrue(np.any(np.nonzero(a10 - x)))\n        self.assertTrue(np.any(np.nonzero(a10 - y)))\n        np.testing.assert_array_less(a10 - x, 1)\n        np.testing.assert_array_less(a10 - y, 1)\n    \n        graph.jitter_size = 0\n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:343: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x7b317f15f2d0>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x7b317f168870>\nx = array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])\ny = array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n_____________ TestOWScatterPlotBase.test_labels_update_coordinates _____________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_labels_update_coordinates>\n\n    def test_labels_update_coordinates(self):\n        graph = self.graph\n        self.master.get_label_data = lambda: \\\n            np.array([str(x) for x in range(10)], dtype=object)\n    \n        graph.reset_graph()\n        graph.set_sample_size(7)\n        x, y = graph.scatterplot_item.getData()\n        for xi, yi, label in zip(x, y, graph.labels):\n            self.assertEqual(xi, label.x())\n            self.assertEqual(yi, label.y())\n    \n        self.master.get_coordinates_data = \\\n            lambda: (np.arange(10, 20), np.arange(50, 60))\n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:1001: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x7b317fae9eb0>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x7b317faea5f0>\nx = array([12, 18, 14, 19, 11, 16, 17]), y = array([52, 58, 54, 59, 51, 56, 57])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n__________________ TestOWScatterPlotBase.test_legend_combine ___________________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_legend_combine>\n\n    def test_legend_combine(self):\n        master = self.master\n        graph = self.graph\n    \n        master.get_shape_data = lambda: np.arange(10, dtype=float) % 3\n        master.get_color_data = lambda: 2 * np.arange(10, dtype=float) % 3\n    \n        graph.reset_graph()\n    \n        shape_legend = self.graph.shape_legend.setVisible = Mock()\n        color_legend = self.graph.color_legend.setVisible = Mock()\n    \n        master.get_shape_labels = lambda: [\"a\", \"b\"]\n        master.get_color_labels = lambda: [\"c\", \"d\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n        self.assertTrue(color_legend.call_args[0][0])\n    \n        master.get_color_labels = lambda: [\"a\", \"b\"]\n        graph.update_legends()\n        self.assertTrue(shape_legend.call_args[0][0])\n>       self.assertTrue(color_legend.call_args[0][0])\nE       AssertionError: False is not true\n\nr2e_tests/test_1.py:1126: AssertionError\n______________ TestOWScatterPlotBase.test_no_needless_buildatlas _______________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_no_needless_buildatlas>\n\n    def test_no_needless_buildatlas(self):\n        graph = self.graph\n        graph.reset_graph()\n>       self.assertIsNone(graph.scatterplot_item.fragmentAtlas.atlas)\nE       AttributeError: 'SymbolAtlas' object has no attribute 'atlas'\n\nr2e_tests/test_1.py:1294: AttributeError\n_____________________ TestOWScatterPlotBase.test_sampling ______________________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_sampling>\n\n    def test_sampling(self):\n        graph = self.graph\n        master = self.master\n    \n        # Enable sampling before getting the data\n        graph.set_sample_size(3)\n        xy = self.xy = (np.arange(10, dtype=float),\n                        np.arange(0, 30, 3, dtype=float))\n        d = np.arange(10, dtype=float)\n        master.get_size_data = lambda: d\n        master.get_shape_data = lambda: d % 5 if d is not None else None\n        master.get_color_data = lambda: d\n        master.get_label_data = lambda: \\\n            np.array([str(x) for x in d], dtype=object)\n        graph.reset_graph()\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n    \n        # Check proper sampling\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        self.assertEqual(len(x), 3)\n        self.assertNotEqual(x[0], x[1])\n        self.assertNotEqual(x[0], x[2])\n        self.assertNotEqual(x[1], x[2])\n        np.testing.assert_almost_equal(3 * x, y)\n    \n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n    \n        # Check that sample is extended when sample size is changed\n        graph.set_sample_size(4)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s = data[\"size\"] - graph.MinShapeSize\n        precise_s = (x - min(x)) / (max(x) - min(x)) * max(s)\n        np.testing.assert_almost_equal(s, precise_s, decimal=0)\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n    \n        # Disable sampling\n        graph.set_sample_size(None)\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        np.testing.assert_almost_equal(x, xy[0])\n        np.testing.assert_almost_equal(y, xy[1])\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in d])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in d])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in d])\n    \n        # Enable sampling when data is already present and not sampled\n        graph.set_sample_size(3)\n        self.process_events(until=lambda: not (\n            self.graph.timer is not None and self.graph.timer.isActive()))\n        scatterplot_item = graph.scatterplot_item\n        x, y = scatterplot_item.getData()\n        data = scatterplot_item.data\n        s0, s1, s2 = data[\"size\"] - graph.MinShapeSize\n        np.testing.assert_almost_equal(\n            (s2 - s1) / (s1 - s0),\n            (x[2] - x[1]) / (x[1] - x[0]))\n        self.assertEqual(\n            list(data[\"symbol\"]),\n            [graph.CurveSymbols[int(xi) % 5] for xi in x])\n        self.assertEqual(\n            [pen.color().hue() for pen in data[\"pen\"]],\n            [graph.palette[xi].hue() for xi in x])\n        self.assertEqual(\n            [label.textItem.toPlainText() for label in graph.labels],\n            [str(xi) for xi in x])\n    \n        # Update data when data is present and sampling is enabled\n        xy[0][:] = np.arange(9, -1, -1, dtype=float)\n        d = xy[0]\n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:259: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x7b317c64e370>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x7b317c665cd0>\nx = array([7., 1., 5.]), y = array([ 6., 24., 12.])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n________________ TestOWScatterPlotBase.test_update_coordinates _________________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_update_coordinates>\n\n    def test_update_coordinates(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        graph.reset_graph()\n    \n        scatterplot_item = graph.scatterplot_item\n        scatterplot_item_sel = graph.scatterplot_item_sel\n        data = scatterplot_item.data\n    \n        np.testing.assert_almost_equal(scatterplot_item.getData(), xy)\n        np.testing.assert_almost_equal(scatterplot_item_sel.getData(), xy)\n        scatterplot_item.setSize([5, 6])\n        scatterplot_item.setSymbol([7, 8])\n        scatterplot_item.setPen([mkPen(9), mkPen(10)])\n        scatterplot_item.setBrush([11, 12])\n        data[\"data\"] = np.array([13, 14])\n    \n        xy[0][0] = 0\n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:92: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x7b3182474730>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x7b3182529870>\nx = array([0, 2]), y = array([3, 4])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n__________ TestOWScatterPlotBase.test_update_coordinates_and_density ___________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_update_coordinates_and_density>\n\n    def test_update_coordinates_and_density(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1, 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 0\n        graph.update_density = Mock()\n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:127: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x7b31825344b0>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x7b3182529550>\nx = array([0, 2]), y = array([3, 4])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n___________ TestOWScatterPlotBase.test_update_coordinates_and_labels ___________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_update_coordinates_and_labels>\n\n    def test_update_coordinates_and_labels(self):\n        graph = self.graph\n        xy = self.xy = (np.array([1., 2]), np.array([3, 4]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(graph.labels[0].pos().x(), 1)\n        xy[0][0] = 1.5\n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:113: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x7b3182518730>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x7b317fa94cd0>\nx = array([1.5, 2. ]), y = array([3, 4])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n___________ TestOWScatterPlotBase.test_update_coordinates_reset_view ___________\n\nself = <r2e_tests.test_1.TestOWScatterPlotBase testMethod=test_update_coordinates_reset_view>\n\n    def test_update_coordinates_reset_view(self):\n        graph = self.graph\n        graph.view_box.setRange = self.setRange\n        xy = self.xy = (np.array([2, 1]), np.array([3, 10]))\n        self.master.get_label_data = lambda: np.array([\"a\", \"b\"])\n        graph.reset_graph()\n        self.assertEqual(self.last_setRange, [[1, 2], [3, 10]])\n    \n        xy[0][1] = 0\n>       graph.update_coordinates()\n\nr2e_tests/test_1.py:139: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/widgets/visualize/owscatterplotgraph.py:716: in update_coordinates\n    self._update_plot_coordinates(self.scatterplot_item, x, y)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.visualize.owscatterplotgraph.OWScatterPlotBase object at 0x7b3182533190>\nplot = <Orange.widgets.visualize.owscatterplotgraph.ScatterPlotItem object at 0x7b317fab4730>\nx = array([2, 0]), y = array([ 3, 10])\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n    \n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n>           data[prop] = plot.data[prop]\nE           ValueError: no field of name targetRect\n\nOrange/widgets/visualize/owscatterplotgraph.py:688: ValueError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_continuous\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_continuous_nan\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_continuous_reused\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_discrete\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_discrete_nan\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_none\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_subset\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_density\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_hiding_too_many_labels\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_label_mask_all_visible\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_label_mask_with_invisible\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_label_mask_with_invisible_and_view\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_labels\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_labels_observes_mask\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_reset_calls_all_updates_and_update_doesnt\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_reset_graph_no_data\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_sampling_keeps_selection\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_select_by_click\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_select_by_indices\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_select_by_rectangle\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_selection_colors\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_shapes\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_shapes_nan\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_show_grid\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_show_legend\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_show_legend_no_data\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_size_animation\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_size_normalization\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_size_rounding_half_pixel\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_size_with_nans\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_sizes_all_same_or_nan\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_sizes_custom_imputation\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_sizes_point_width_is_linear\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_sizes_selection\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_unselect_all\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_update_coordinates_indices\nPASSED r2e_tests/test_1.py::TestOWScatterPlotBase::test_update_coordinates_no_data\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:86: minimum size not tested as .widget was not set\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:92: msg base class not tested as .widget was not set\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_colors_update_legend_and_density\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_jittering - ValueErro...\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_labels_update_coordinates\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_legend_combine - Asse...\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_no_needless_buildatlas\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_sampling - ValueError...\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_update_coordinates - ...\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_update_coordinates_and_density\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_update_coordinates_and_labels\nFAILED r2e_tests/test_1.py::TestOWScatterPlotBase::test_update_coordinates_reset_view\n=================== 10 failed, 37 passed, 2 skipped in 6.29s ===================\n",
    "old_commit_res_stderr": ""
}
Orange/widgets/visualize/owscatterplotgraph.py Orange/widgets/visualize/tests/test_owscatterplotbase.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]

**Title:** OWScatterPlotGraph Fails to Display Separate Color Legend When Shape and Color Labels Match

**Description:**
When the shape labels and color labels are identical, the color legend fails to display separately as expected. This issue occurs even when the color and shape data are distinct, leading to a combined legend that hides the color information.

**Example Code:**
```python
master.get_shape_data = lambda: np.arange(10, dtype=float) % 3
master.get_color_data = lambda: 2 * np.arange(10, dtype=float) % 3
master.get_shape_labels = lambda: ["a", "b"]
master.get_color_labels = lambda: ["a", "b"]

graph.update_legends()

# Expected: Both shape_legend and color_legend should be visible
# Actual: color_legend is not visible
```

**Expected Behavior:**
When shape labels and color labels are the same, and the color data differs from the shape data, both the shape legend and the color legend should be displayed separately to accurately represent the distinct attributes.

**Actual Behavior:**
Only the shape legend is displayed, and the color legend remains hidden, making it unclear which colors correspond to which data points.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### Orange/widgets/visualize/owscatterplotgraph.py
import sys
import itertools
import warnings
from xml.sax.saxutils import escape
from math import log10, floor, ceil

import numpy as np
from AnyQt.QtCore import Qt, QRectF, QSize, QTimer, pyqtSignal as Signal, \
    QObject
from AnyQt.QtGui import (
    QStaticText, QColor, QPen, QBrush, QPainterPath, QTransform, QPainter
)
from AnyQt.QtWidgets import (
    QApplication, QToolTip, QGraphicsTextItem, QGraphicsRectItem
)

import pyqtgraph as pg
import pyqtgraph.graphicsItems.ScatterPlotItem
from pyqtgraph.graphicsItems.LegendItem import (
    LegendItem as PgLegendItem, ItemSample
)
from pyqtgraph.graphicsItems.TextItem import TextItem

from Orange.util import OrangeDeprecationWarning
from Orange.widgets import gui
from Orange.widgets.settings import Setting
from Orange.widgets.utils import classdensity
from Orange.widgets.utils.colorpalette import ColorPaletteGenerator
from Orange.widgets.utils.plot import OWPalette
from Orange.widgets.visualize.owscatterplotgraph_obsolete import (
    OWScatterPlotGraph as OWScatterPlotGraphObs
)
from Orange.widgets.visualize.utils.plotutils import (
    HelpEventDelegate as EventDelegate,
    InteractiveViewBox as ViewBox
)


SELECTION_WIDTH = 5
MAX_N_VALID_SIZE_ANIMATE = 1000


class PaletteItemSample(ItemSample):
    """A color strip to insert into legends for discretized continuous values"""

    def __init__(self, palette, scale, label_formatter=None):
        """
        :param palette: palette used for showing continuous values
        :type palette: ContinuousPaletteGenerator
        :param scale: an instance of DiscretizedScale that defines the
                      conversion of values into bins
        :type scale: DiscretizedScale
        """
        super().__init__(None)
        self.palette = palette
        self.scale = scale
        if label_formatter is None:
            label_formatter = "{{:.{}f}}".format(scale.decimals).format
        cuts = [label_formatter(scale.offset + i * scale.width)
                for i in range(scale.bins + 1)]
        self.labels = [QStaticText("{} - {}".format(fr, to))
                       for fr, to in zip(cuts, cuts[1:])]
        for label in self.labels:
            label.prepare()
        self.text_width = max(label.size().width() for label in self.labels)

    def boundingRect(self):
        return QRectF(0, 0, 40 + self.text_width, 20 + self.scale.bins * 15)

    def paint(self, p, *args):
        p.setRenderHint(p.Antialiasing)
        scale = self.scale
        font = p.font()
        font.setPixelSize(11)
        p.setFont(font)
        for i, label in enumerate(self.labels):
            color = QColor(*self.palette.getRGB((i + 0.5) / scale.bins))
            p.setPen(Qt.NoPen)
            p.setBrush(QBrush(color))
            p.drawRect(0, i * 15, 15, 15)
            p.setPen(QPen(Qt.black))
            p.drawStaticText(20, i * 15 + 1, label)


class LegendItem(PgLegendItem):
    def __init__(self, size=None, offset=None, pen=None, brush=None):
        super().__init__(size, offset)

        self.layout.setContentsMargins(5, 5, 5, 5)
        self.layout.setHorizontalSpacing(15)
        self.layout.setColumnAlignment(1, Qt.AlignLeft | Qt.AlignVCenter)

        if pen is None:
            pen = QPen(QColor(196, 197, 193, 200), 1)
            pen.setCosmetic(True)
        self.__pen = pen

        if brush is None:
            brush = QBrush(QColor(232, 232, 232, 100))
        self.__brush = brush

    def restoreAnchor(self, anchors):
        """
        Restore (parent) relative position from stored anchors.

        The restored position is within the parent bounds.
        """
        anchor, parentanchor = anchors
        self.anchor(*bound_anchor_pos(anchor, parentanchor))

    def paint(self, painter, option, widget=None):
        painter.setPen(self.__pen)
        painter.setBrush(self.__brush)
        rect = self.contentsRect()
        painter.drawRoundedRect(rect, 2, 2)

    def addItem(self, item, name):
        super().addItem(item, name)
        # Fix-up the label alignment
        _, label = self.items[-1]
        label.setText(name, justify="left")

    def clear(self):
        """
        Clear all legend items.
        """
        items = list(self.items)
        self.items = []
        for sample, label in items:
            self.layout.removeItem(sample)
            self.layout.removeItem(label)
            sample.hide()
            label.hide()

        self.updateSize()


def bound_anchor_pos(corner, parentpos):
    corner = np.clip(corner, 0, 1)
    parentpos = np.clip(parentpos, 0, 1)

    irx, iry = corner
    prx, pry = parentpos

    if irx > 0.9 and prx < 0.1:
        irx = prx = 0.0
    if iry > 0.9 and pry < 0.1:
        iry = pry = 0.0
    if irx < 0.1 and prx > 0.9:
        irx = prx = 1.0
    if iry < 0.1 and pry > 0.9:
        iry = pry = 1.0
    return (irx, iry), (prx, pry)


class DiscretizedScale:
    """
    Compute suitable bins for continuous value from its minimal and
    maximal value.

    The width of the bin is a power of 10 (including negative powers).
    The minimal value is rounded up and the maximal is rounded down. If this
    gives less than 3 bins, the width is divided by four; if it gives
    less than 6, it is halved.

    .. attribute:: offset
        The start of the first bin.

    .. attribute:: width
        The width of the bins

    .. attribute:: bins
        The number of bins

    .. attribute:: decimals
        The number of decimals used for printing out the boundaries
    """
    def __init__(self, min_v, max_v):
        """
        :param min_v: Minimal value
        :type min_v: float
        :param max_v: Maximal value
        :type max_v: float
        """
        super().__init__()
        dif = max_v - min_v if max_v != min_v else 1
        if np.isnan(dif):
            min_v = 0
            dif = decimals = 1
        else:
            decimals = -floor(log10(dif))
        resolution = 10 ** -decimals
        bins = ceil(dif / resolution)
        if bins < 6:
            decimals += 1
            if bins < 3:
                resolution /= 4
            else:
                resolution /= 2
            bins = ceil(dif / resolution)
        self.offset = resolution * floor(min_v // resolution)
        self.bins = bins
        self.decimals = max(decimals, 0)
        self.width = resolution


class InteractiveViewBox(ViewBox):
    def __init__(self, graph, enable_menu=False):
        super().__init__(graph, enable_menu)
        warnings.warn("InteractiveViewBox class has been deprecated since "
                      "3.17. Use Orange.widgets.visualize.utils.plotutils."
                      "InteractiveViewBox instead.", OrangeDeprecationWarning)


class OWScatterPlotGraph(OWScatterPlotGraphObs):
    def __init__(self, scatter_widget, parent=None, _="None", view_box=InteractiveViewBox):
        super().__init__(scatter_widget, parent=parent, _=_, view_box=view_box)
        warnings.warn("OWScatterPlotGraph class has been deprecated since "
                      "3.17. Use OWScatterPlotBase instead.",
                      OrangeDeprecationWarning)


class ScatterPlotItem(pg.ScatterPlotItem):
    """PyQtGraph's ScatterPlotItem calls updateSpots at any change of sizes/colors/symbols,
    which then rebuilds the stored pixmaps for each symbol. Because Orange calls
    set* function in succession, we postpone updateSpots() to paint()."""

    _update_spots_in_paint = False

    def updateSpots(self, dataSet=None):  # pylint: disable=unused-argument
        self._update_spots_in_paint = True
        self.update()

    def paint(self, painter, option, widget=None):
        if self._update_spots_in_paint:
            self._update_spots_in_paint = False
            super().updateSpots()
        painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
        super().paint(painter, option, widget)


def _define_symbols():
    """
    Add symbol ? to ScatterPlotItemSymbols,
    reflect the triangle to point upwards
    """
    symbols = pyqtgraph.graphicsItems.ScatterPlotItem.Symbols
    path = QPainterPath()
    path.addEllipse(QRectF(-0.35, -0.35, 0.7, 0.7))
    path.moveTo(-0.5, 0.5)
    path.lineTo(0.5, -0.5)
    path.moveTo(-0.5, -0.5)
    path.lineTo(0.5, 0.5)
    symbols["?"] = path

    tr = QTransform()
    tr.rotate(180)
    symbols['t'] = tr.map(symbols['t'])


_define_symbols()


def _make_pen(color, width):
    p = QPen(color, width)
    p.setCosmetic(True)
    return p


class OWScatterPlotBase(gui.OWComponent, QObject):
    """
    Provide a graph component for widgets that show any kind of point plot

    The component plots a set of points with given coordinates, shapes,
    sizes and colors. Its function is similar to that of a *view*, whereas
    the widget represents a *model* and a *controler*.

    The model (widget) needs to provide methods:

    - `get_coordinates_data`, `get_size_data`, `get_color_data`,
      `get_shape_data`, `get_label_data`, which return a 1d array (or two
      arrays, for `get_coordinates_data`) of `dtype` `float64`, except for
      `get_label_data`, which returns formatted labels;
    - `get_shape_labels` returns a list of strings for shape legend
    - `get_color_labels` returns strings for color legend, or a function for
       formatting numbers if the legend is continuous, or None for default
       formatting
    - `get_tooltip`, which gives a tooltip for a single data point
    - (optional) `impute_sizes`, `impute_shapes` get final coordinates and
      shapes, and replace nans;
    - `get_subset_mask` returns a bool array indicating whether a
      data point is in the subset or not (e.g. in the 'Data Subset' signal
      in the Scatter plot and similar widgets);
    - `get_palette` returns a palette appropriate for visualizing the
      current color data;
    - `is_continuous_color` decides the type of the color legend;

    The widget (in a role of controller) must also provide methods
    - `selection_changed`

    If `get_coordinates_data` returns `(None, None)`, the plot is cleared. If
    `get_size_data`, `get_color_data` or `get_shape_data` return `None`,
    all points will have the same size, color or shape, respectively.
    If `get_label_data` returns `None`, there are no labels.

    The view (this compomnent) provides methods `update_coordinates`,
    `update_sizes`, `update_colors`, `update_shapes` and `update_labels`
    that the widget (in a role of a controler) should call when any of
    these properties are changed. If the widget calls, for instance, the
    plot's `update_colors`, the plot will react by calling the widget's
    `get_color_data` as well as the widget's methods needed to construct the
    legend.

    The view also provides a method `reset_graph`, which should be called only
    when
    - the widget gets entirely new data
    - the number of points may have changed, for instance when selecting
    a different attribute for x or y in the scatter plot, where the points
    with missing x or y coordinates are hidden.

    Every `update_something` calls the plot's `get_something`, which
    calls the model's `get_something_data`, then it transforms this data
    into whatever is needed (colors, shapes, scaled sizes) and changes the
    plot. For the simplest example, here is `update_shapes`:

    ```
        def update_shapes(self):
            if self.scatterplot_item:
                shape_data = self.get_shapes()
                self.scatterplot_item.setSymbol(shape_data)
            self.update_legends()

        def get_shapes(self):
            shape_data = self.master.get_shape_data()
            shape_data = self.master.impute_shapes(
                shape_data, len(self.CurveSymbols) - 1)
            return self.CurveSymbols[shape_data]
    ```

    On the widget's side, `get_something_data` is essentially just:

    ```
        def get_size_data(self):
            return self.get_column(self.attr_size)
    ```

    where `get_column` retrieves a column while also filtering out the
    points with missing x and y and so forth. (Here we present the simplest
    two cases, "shapes" for the view and "sizes" for the model. The colors
    for the view are more complicated since they deal with discrete and
    continuous palettes, and the shapes for the view merge infrequent shapes.)

    The plot can also show just a random sample of the data. The sample size is
    set by `set_sample_size`, and the rest is taken care by the plot: the
    widget keeps providing the data for all points, selection indices refer
    to the entire set etc. Internally, sampling happens as early as possible
    (in methods `get_<something>`).
    """
    too_many_labels = Signal(bool)
    begin_resizing = Signal()
    step_resizing = Signal()
    end_resizing = Signal()

    label_only_selected = Setting(False)
    point_width = Setting(10)
    alpha_value = Setting(128)
    show_grid = Setting(False)
    show_legend = Setting(True)
    class_density = Setting(False)
    jitter_size = Setting(0)

    resolution = 256

    CurveSymbols = np.array("o x t + d star ?".split())
    MinShapeSize = 6
    DarkerValue = 120
    UnknownColor = (168, 50, 168)

    COLOR_NOT_SUBSET = (128, 128, 128, 0)
    COLOR_SUBSET = (128, 128, 128, 255)
    COLOR_DEFAULT = (128, 128, 128, 0)

    MAX_VISIBLE_LABELS = 500

    def __init__(self, scatter_widget, parent=None, view_box=ViewBox):
        QObject.__init__(self)
        gui.OWComponent.__init__(self, scatter_widget)

        self.subset_is_shown = False

        self.view_box = view_box(self)
        self.plot_widget = pg.PlotWidget(viewBox=self.view_box, parent=parent,
                                         background="w")
        self.plot_widget.hideAxis("left")
        self.plot_widget.hideAxis("bottom")
        self.plot_widget.getPlotItem().buttonsHidden = True
        self.plot_widget.setAntialiasing(True)
        self.plot_widget.sizeHint = lambda: QSize(500, 500)

        self.density_img = None
        self.scatterplot_item = None
        self.scatterplot_item_sel = None
        self.labels = []

        self.master = scatter_widget
        self._create_drag_tooltip(self.plot_widget.scene())

        self.selection = None  # np.ndarray

        self.n_valid = 0
        self.n_shown = 0
        self.sample_size = None
        self.sample_indices = None

        self.palette = None

        self.shape_legend = self._create_legend(((1, 0), (1, 0)))
        self.color_legend = self._create_legend(((1, 1), (1, 1)))
        self.update_legend_visibility()

        self.scale = None  # DiscretizedScale
        self._too_many_labels = False

        # self.setMouseTracking(True)
        # self.grabGesture(QPinchGesture)
        # self.grabGesture(QPanGesture)

        self.update_grid_visibility()

        self._tooltip_delegate = EventDelegate(self.help_event)
        self.plot_widget.scene().installEventFilter(self._tooltip_delegate)
        self.view_box.sigTransformChanged.connect(self.update_density)
        self.view_box.sigRangeChangedManually.connect(self.update_labels)

        self.timer = None

    def _create_legend(self, anchor):
        legend = LegendItem()
        legend.setParentItem(self.plot_widget.getViewBox())
        legend.restoreAnchor(anchor)
        return legend

    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()

        scene.drag_tooltip = scene.createItemGroup([rect, text])
        scene.drag_tooltip.hide()

    def update_tooltip(self, modifiers=Qt.NoModifier):
        modifiers &= Qt.ShiftModifier + Qt.ControlModifier + Qt.AltModifier
        text = self.tiptexts.get(int(modifiers), self.tiptexts[0])
        self.tip_textitem.setHtml(text + self._get_jittering_tooltip())

    def _get_jittering_tooltip(self):
        warn_jittered = ""
        if self.jitter_size:
            warn_jittered = \
                '<br/><br/>' \
                '<span style="background-color: red; color: white; ' \
                'font-weight: 500;">' \
                '&nbsp;Warning: Selection is applied to unjittered data&nbsp;' \
                '</span>'
        return warn_jittered

    def update_jittering(self):
        self.update_tooltip()
        x, y = self.get_coordinates()
        if x is None or not len(x) or self.scatterplot_item is None:
            return
        self._update_plot_coordinates(self.scatterplot_item, x, y)
        self._update_plot_coordinates(self.scatterplot_item_sel, x, y)
        self.update_labels()

    # TODO: Rename to remove_plot_items
    def clear(self):
        """
        Remove all graphical elements from the plot

        Calls the pyqtgraph's plot widget's clear, sets all handles to `None`,
        removes labels and selections.

        This method should generally not be called by the widget. If the data
        is gone (*e.g.* upon receiving `None` as an input data signal), this
        should be handler by calling `reset_graph`, which will in turn call
        `clear`.

        Derived classes should override this method if they add more graphical
        elements. For instance, the regression line in the scatterplot adds
        `self.reg_line_item = None` (the line in the plot is already removed
        in this method).
        """
        self.plot_widget.clear()

        self.density_img = None
        if self.timer is not None and self.timer.isActive():
            self.timer.stop()
            self.timer = None
        self.scatterplot_item = None
        self.scatterplot_item_sel = None
        self.labels = []
        self._signal_too_many_labels(False)
        self.view_box.init_history()
        self.view_box.tag_history()

    # TODO: I hate `keep_something` and `reset_something` arguments
    # __keep_selection is used exclusively be set_sample size which would
    # otherwise just repeat the code from reset_graph except for resetting
    # the selection. I'm uncomfortable with this; we may prefer to have a
    # method _reset_graph which does everything except resetting the selection,
    # and reset_graph would call it.
    def reset_graph(self, __keep_selection=False):
        """
        Reset the graph to new data (or no data)

        The method must be called when the plot receives new data, in
        particular when the number of points change. If only their properties
        - like coordinates or shapes - change, an update method
        (`update_coordinates`, `update_shapes`...) should be called instead.

        The method must also be called when the data is gone.

        The method calls `clear`, followed by calls of all update methods.

        NB. Argument `__keep_selection` is for internal use only
        """
        self.clear()
        if not __keep_selection:
            self.selection = None
        self.sample_indices = None
        self.update_coordinates()
        self.update_point_props()

    def set_sample_size(self, sample_size):
        """
        Set the sample size

        Args:
            sample_size (int or None): sample size or `None` to show all points
        """
        if self.sample_size != sample_size:
            self.sample_size = sample_size
            self.reset_graph(True)

    def update_point_props(self):
        """
        Update the sizes, colors, shapes and labels

        The method calls the appropriate update methods for individual
        properties.
        """
        self.update_sizes()
        self.update_colors()
        self.update_selection_colors()
        self.update_shapes()
        self.update_labels()

    # Coordinates
    # TODO: It could be nice if this method was run on entire data, not just
    # a sample. For this, however, it would need to either be called from
    # `get_coordinates` before sampling (very ugly) or call
    # `self.master.get_coordinates_data` (beyond ugly) or the widget would
    # have to store the ranges of unsampled data (ugly).
    # Maybe we leave it as it is.
    def _reset_view(self, x_data, y_data):
        """
        Set the range of the view box

        Args:
            x_data (np.ndarray): x coordinates
            y_data (np.ndarray) y coordinates
        """
        min_x, max_x = np.min(x_data), np.max(x_data)
        min_y, max_y = np.min(y_data), np.max(y_data)
        self.view_box.setRange(
            QRectF(min_x, min_y, max_x - min_x or 1, max_y - min_y or 1),
            padding=0.025)

    def _filter_visible(self, data):
        """Return the sample from the data using the stored sample_indices"""
        if data is None or self.sample_indices is None:
            return data
        else:
            return np.asarray(data[self.sample_indices])

    def get_coordinates(self):
        """
        Prepare coordinates of the points in the plot

        The method is called by `update_coordinates`. It gets the coordinates
        from the widget, jitters them and return them.

        The methods also initializes the sample indices if neededd and stores
        the original and sampled number of points.

        Returns:
            (tuple): a pair of numpy arrays containing (sampled) coordinates,
                or `(None, None)`.
        """
        x, y = self.master.get_coordinates_data()
        if x is None:
            self.n_valid = self.n_shown = 0
            return None, None
        self.n_valid = len(x)
        self._create_sample()
        x = self._filter_visible(x)
        y = self._filter_visible(y)
        # Jittering after sampling is OK if widgets do not change the sample
        # semi-permanently, e.g. take a sample for the duration of some
        # animation. If the sample size changes dynamically (like by adding
        # a "sample size" slider), points would move around when the sample
        # size changes. To prevent this, jittering should be done before
        # sampling (i.e. two lines earlier). This would slow it down somewhat.
        x, y = self.jitter_coordinates(x, y)
        return x, y

    def _create_sample(self):
        """
        Create a random sample if the data is larger than the set sample size
        """
        self.n_shown = min(self.n_valid, self.sample_size or self.n_valid)
        if self.sample_size is not None \
                and self.sample_indices is None \
                and self.n_valid != self.n_shown:
            random = np.random.RandomState(seed=0)
            self.sample_indices = random.choice(
                self.n_valid, self.n_shown, replace=False)
            # TODO: Is this really needed?
            np.sort(self.sample_indices)

    def jitter_coordinates(self, x, y):
        """
        Display coordinates to random positions within ellipses with
        radiuses of `self.jittter_size` percents of spans
        """
        if self.jitter_size == 0:
            return x, y
        return self._jitter_data(x, y)

    def _jitter_data(self, x, y, span_x=None, span_y=None):
        if span_x is None:
            span_x = np.max(x) - np.min(x)
        if span_y is None:
            span_y = np.max(y) - np.min(y)
        random = np.random.RandomState(seed=0)
        rs = random.uniform(0, 1, len(x))
        phis = random.uniform(0, 2 * np.pi, len(x))
        magnitude = self.jitter_size / 100
        return (x + magnitude * span_x * rs * np.cos(phis),
                y + magnitude * span_y * rs * np.sin(phis))

    def _update_plot_coordinates(self, plot, x, y):
        """
        Change the coordinates of points while keeping other properites

        Note. Pyqtgraph does not offer a method for this: setting coordinates
        invalidates other data. We therefore retrieve the data to set it
        together with the coordinates. Pyqtgraph also does not offer a
        (documented) method for retrieving the data, yet using
        `plot.data[prop]` looks reasonably safe. The alternative, calling
        update for every property would essentially reset the graph, which
        can be time consuming.
        """
        data = dict(x=x, y=y)
        for prop in ('pen', 'brush', 'size', 'symbol', 'data',
                     'sourceRect', 'targetRect'):
            data[prop] = plot.data[prop]
        plot.setData(**data)

    def update_coordinates(self):
        """
        Trigger the update of coordinates while keeping other features intact.

        The method gets the coordinates by calling `self.get_coordinates`,
        which in turn calls the widget's `get_coordinate_data`. The number of
        coordinate pairs returned by the latter must match the current number
        of points. If this is not the case, the widget should trigger
        the complete update by calling `reset_graph` instead of this method.
        """
        x, y = self.get_coordinates()
        if x is None or not len(x):
            return
        if self.scatterplot_item is None:
            if self.sample_indices is None:
                indices = np.arange(self.n_valid)
            else:
                indices = self.sample_indices
            kwargs = dict(x=x, y=y, data=indices)
            self.scatterplot_item = ScatterPlotItem(**kwargs)
            self.scatterplot_item.sigClicked.connect(self.select_by_click)
            self.scatterplot_item_sel = ScatterPlotItem(**kwargs)
            self.plot_widget.addItem(self.scatterplot_item_sel)
            self.plot_widget.addItem(self.scatterplot_item)
        else:
            self._update_plot_coordinates(self.scatterplot_item, x, y)
            self._update_plot_coordinates(self.scatterplot_item_sel, x, y)
            self.update_labels()

        self.update_density()  # Todo: doesn't work: try MDS with density on
        self._reset_view(x, y)

    # Sizes
    def get_sizes(self):
        """
        Prepare data for sizes of points in the plot

        The method is called by `update_sizes`. It gets the sizes
        from the widget and performs the necessary scaling and sizing.
        The output is rounded to half a pixel for faster drawing.

        Returns:
            (np.ndarray): sizes
        """
        size_column = self.master.get_size_data()
        if size_column is None:
            return np.full((self.n_shown,),
                           self.MinShapeSize + (5 + self.point_width) * 0.5)
        size_column = self._filter_visible(size_column)
        size_column = size_column.copy()
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", category=RuntimeWarning)
            size_column -= np.nanmin(size_column)
            mx = np.nanmax(size_column)
        if mx > 0:
            size_column /= mx
        else:
            size_column[:] = 0.5

        sizes = self.MinShapeSize + (5 + self.point_width) * size_column
        # round sizes to half pixel for smaller pyqtgraph's symbol pixmap atlas
        sizes = (sizes * 2).round() / 2
        return sizes

    def update_sizes(self):
        """
        Trigger an update of point sizes

        The method calls `self.get_sizes`, which in turn calls the widget's
        `get_size_data`. The result are properly scaled and then passed
        back to widget for imputing (`master.impute_sizes`).
        """
        if self.scatterplot_item:
            size_data = self.get_sizes()
            size_imputer = getattr(
                self.master, "impute_sizes", self.default_impute_sizes)
            size_imputer(size_data)

            if self.timer is not None and self.timer.isActive():
                self.timer.stop()
                self.timer = None

            current_size_data = self.scatterplot_item.data["size"].copy()
            diff = size_data - current_size_data
            widget = self

            class Timeout:
                # 0.5 - np.cos(np.arange(0.17, 1, 0.17) * np.pi) / 2
                factors = [0.07, 0.26, 0.52, 0.77, 0.95, 1]

                def __init__(self):
                    self._counter = 0

                def __call__(self):
                    factor = self.factors[self._counter]
                    self._counter += 1
                    size = current_size_data + diff * factor
                    if len(self.factors) == self._counter:
                        widget.timer.stop()
                        widget.timer = None
                        size = size_data
                    widget.scatterplot_item.setSize(size)
                    widget.scatterplot_item_sel.setSize(size + SELECTION_WIDTH)
                    if widget.timer is None:
                        widget.end_resizing.emit()
                    else:
                        widget.step_resizing.emit()

            if self.n_valid <= MAX_N_VALID_SIZE_ANIMATE and \
                    np.all(current_size_data > 0) and np.any(diff != 0):
                # If encountered any strange behaviour when updating sizes,
                # implement it with threads
                self.begin_resizing.emit()
                self.timer = QTimer(self.scatterplot_item, interval=50)
                self.timer.timeout.connect(Timeout())
                self.timer.start()
            else:
                self.begin_resizing.emit()
                self.scatterplot_item.setSize(size_data)
                self.scatterplot_item_sel.setSize(size_data + SELECTION_WIDTH)
                self.end_resizing.emit()

    update_point_size = update_sizes  # backward compatibility (needed?!)
    update_size = update_sizes

    @classmethod
    def default_impute_sizes(cls, size_data):
        """
        Fallback imputation for sizes.

        Set the size to two pixels smaller than the minimal size

        Returns:
            (bool): True if there was any missing data
        """
        nans = np.isnan(size_data)
        if np.any(nans):
            size_data[nans] = cls.MinShapeSize - 2
            return True
        else:
            return False

    # Colors
    def get_colors(self):
        """
        Prepare data for colors of the points in the plot

        The method is called by `update_colors`. It gets the colors and the
        indices of the data subset from the widget (`get_color_data`,
        `get_subset_mask`), and constructs lists of pens and brushes for
        each data point.

        The method uses different palettes for discrete and continuous data,
        as determined by calling the widget's method `is_continuous_color`.

        If also marks the points that are in the subset as defined by, for
        instance the 'Data Subset' signal in the Scatter plot and similar
        widgets. (Do not confuse this with *selected points*, which are
        marked by circles around the points, which are colored by groups
        and thus independent of this method.)

        Returns:
            (tuple): a list of pens and list of brushes
        """
        self.palette = self.master.get_palette()
        c_data = self.master.get_color_data()
        c_data = self._filter_visible(c_data)
        subset = self.master.get_subset_mask()
        subset = self._filter_visible(subset)
        self.subset_is_shown = subset is not None
        if c_data is None:  # same color
            return self._get_same_colors(subset)
        elif self.master.is_continuous_color():
            return self._get_continuous_colors(c_data, subset)
        else:
            return self._get_discrete_colors(c_data, subset)

    def _get_same_colors(self, subset):
        """
        Return the same pen for all points while the brush color depends
        upon whether the point is in the subset or not

        Args:
            subset (np.ndarray): a bool array indicating whether a data point
                is in the subset or not (e.g. in the 'Data Subset' signal
                in the Scatter plot and similar widgets);

        Returns:
            (tuple): a list of pens and list of brushes
        """
        color = self.plot_widget.palette().color(OWPalette.Data)
        pen = [_make_pen(color, 1.5)] * self.n_shown  # use a single QPen instance
        if subset is not None:
            brush = np.where(
                subset,
                *(QBrush(QColor(*col))
                  for col in (self.COLOR_SUBSET, self.COLOR_NOT_SUBSET)))
        else:
            color = QColor(*self.COLOR_DEFAULT)
            color.setAlpha(self.alpha_value)
            brush = [QBrush(color)] * self.n_shown  # use a single QBrush instance
        return pen, brush

    def _get_continuous_colors(self, c_data, subset):
        """
        Return the pens and colors whose color represent an index into
        a continuous palette. The same color is used for pen and brush,
        except the former is darker. If the data has a subset, the brush
        is transparent for points that are not in the subset.
        """
        if np.isnan(c_data).all():
            self.scale = None
        else:
            self.scale = DiscretizedScale(np.nanmin(c_data), np.nanmax(c_data))
            c_data -= self.scale.offset
            c_data /= self.scale.width
            c_data = np.floor(c_data) + 0.5
            c_data /= self.scale.bins
            c_data = np.clip(c_data, 0, 1)
        pen = self.palette.getRGB(c_data)
        brush = np.hstack(
            [pen, np.full((len(pen), 1), self.alpha_value, dtype=int)])
        pen *= 100
        pen //= self.DarkerValue

        # Reuse pens and brushes with the same colors because PyQtGraph then builds
        # smaller pixmap atlas, which makes the drawing faster

        def reuse(cache, fn, *args):
            if args not in cache:
                cache[args] = fn(args)
            return cache[args]

        def create_pen(col):
            return _make_pen(QColor(*col), 1.5)

        def create_brush(col):
            return QBrush(QColor(*col))

        cached_pens = {}
        pen = [reuse(cached_pens, create_pen, *col) for col in pen.tolist()]

        if subset is not None:
            brush[:, 3] = 0
            brush[subset, 3] = 255

        cached_brushes = {}
        brush = np.array([reuse(cached_brushes, create_brush, *col) for col in brush.tolist()])

        return pen, brush

    def _get_discrete_colors(self, c_data, subset):
        """
        Return the pens and colors whose color represent an index into
        a discrete palette. The same color is used for pen and brush,
        except the former is darker. If the data has a subset, the brush
        is transparent for points that are not in the subset.
        """
        n_colors = self.palette.number_of_colors
        c_data = c_data.copy()
        c_data[np.isnan(c_data)] = n_colors
        c_data = c_data.astype(int)
        colors = np.r_[self.palette.getRGB(np.arange(n_colors)),
                       [[128, 128, 128]]]
        pens = np.array(
            [_make_pen(QColor(*col).darker(self.DarkerValue), 1.5)
             for col in colors])
        pen = pens[c_data]
        alpha = self.alpha_value if subset is None else 255
        brushes = np.array([
            [QBrush(QColor(0, 0, 0, 0)),
             QBrush(QColor(col[0], col[1], col[2], alpha))]
            for col in colors])
        brush = brushes[c_data]

        if subset is not None:
            brush = np.where(subset, brush[:, 1], brush[:, 0])
        else:
            brush = brush[:, 1]
        return pen, brush

    def update_colors(self):
        """
        Trigger an update of point sizes

        The method calls `self.get_colors`, which in turn calls the widget's
        `get_color_data` to get the indices in the pallette. `get_colors`
        returns a list of pens and brushes to which this method uses to
        update the colors. Finally, the method triggers the update of the
        legend and the density plot.
        """
        if self.scatterplot_item is not None:
            pen_data, brush_data = self.get_colors()
            self.scatterplot_item.setPen(pen_data, update=False, mask=None)
            self.scatterplot_item.setBrush(brush_data, mask=None)
        self.update_legends()
        self.update_density()

    update_alpha_value = update_colors

    def update_density(self):
        """
        Remove the existing density plot (if there is one) and replace it
        with a new one (if enabled).

        The method gets the colors from the pens of the currently plotted
        points.
        """
        if self.density_img:
            self.plot_widget.removeItem(self.density_img)
            self.density_img = None
        if self.class_density and self.scatterplot_item is not None:
            rgb_data = [
                pen.color().getRgb()[:3] if pen is not None else (255, 255, 255)
                for pen in self.scatterplot_item.data['pen']]
            if len(set(rgb_data)) <= 1:
                return
            [min_x, max_x], [min_y, max_y] = self.view_box.viewRange()
            x_data, y_data = self.scatterplot_item.getData()
            self.density_img = classdensity.class_density_image(
                min_x, max_x, min_y, max_y, self.resolution,
                x_data, y_data, rgb_data)
            self.plot_widget.addItem(self.density_img)

    def update_selection_colors(self):
        """
        Trigger an update of selection markers

        This update method is usually not called by the widget but by the
        plot, since it is the plot that handles the selections.

        Like other update methods, it calls the corresponding get method
        (`get_colors_sel`) which returns a list of pens and brushes.
        """
        if self.scatterplot_item_sel is None:
            return
        pen, brush = self.get_colors_sel()
        self.scatterplot_item_sel.setPen(pen, update=False, mask=None)
        self.scatterplot_item_sel.setBrush(brush, mask=None)

    def get_colors_sel(self):
        """
        Return pens and brushes for selection markers.

        A pen can is set to `Qt.NoPen` if a point is not selected.

        All brushes are completely transparent whites.

        Returns:
            (tuple): a list of pens and a list of brushes
        """
        nopen = QPen(Qt.NoPen)
        if self.selection is None:
            pen = [nopen] * self.n_shown
        else:
            sels = np.max(self.selection)
            if sels == 1:
                pen = np.where(
                    self._filter_visible(self.selection),
                    _make_pen(QColor(255, 190, 0, 255), SELECTION_WIDTH + 1),
                    nopen)
            else:
                palette = ColorPaletteGenerator(number_of_colors=sels + 1)
                pen = np.choose(
                    self._filter_visible(self.selection),
                    [nopen] + [_make_pen(palette[i], SELECTION_WIDTH + 1)
                               for i in range(sels)])
        return pen, [QBrush(QColor(255, 255, 255, 0))] * self.n_shown

    # Labels
    def get_labels(self):
        """
        Prepare data for labels for points

        The method returns the results of the widget's `get_label_data`

        Returns:
            (labels): a sequence of labels
        """
        return self._filter_visible(self.master.get_label_data())

    def update_labels(self):
        """
        Trigger an update of labels

        The method calls `get_labels` which in turn calls the widget's
        `get_label_data`. The obtained labels are shown if the corresponding
        points are selected or if `label_only_selected` is `false`.
        """
        for label in self.labels:
            self.plot_widget.removeItem(label)
        self.labels = []

        mask = None
        if self.scatterplot_item is not None:
            x, y = self.scatterplot_item.getData()
            mask = self._label_mask(x, y)

        if mask is not None:
            labels = self.get_labels()
            if labels is None:
                mask = None

        self._signal_too_many_labels(
            mask is not None and mask.sum() > self.MAX_VISIBLE_LABELS)
        if self._too_many_labels or mask is None or not np.any(mask):
            return

        black = pg.mkColor(0, 0, 0)
        labels = labels[mask]
        x = x[mask]
        y = y[mask]
        for label, xp, yp in zip(labels, x, y):
            ti = TextItem(label, black)
            ti.setPos(xp, yp)
            self.plot_widget.addItem(ti)
            self.labels.append(ti)

    def _signal_too_many_labels(self, too_many):
        if self._too_many_labels != too_many:
            self._too_many_labels = too_many
            self.too_many_labels.emit(too_many)

    def _label_mask(self, x, y):
        (x0, x1), (y0, y1) = self.view_box.viewRange()
        mask = np.logical_and(
            np.logical_and(x >= x0, x <= x1),
            np.logical_and(y >= y0, y <= y1))
        if self.label_only_selected:
            sub_mask = self._filter_visible(self.master.get_subset_mask())
            if self.selection is None:
                if sub_mask is None:
                    return None
                else:
                    sel_mask = sub_mask
            else:
                sel_mask = self._filter_visible(self.selection) != 0
                if sub_mask is not None:
                    sel_mask = np.logical_or(sel_mask, sub_mask)
            mask = np.logical_and(mask, sel_mask)
        return mask

    # Shapes
    def get_shapes(self):
        """
        Prepare data for shapes of points in the plot

        The method is called by `update_shapes`. It gets the data from
        the widget's `get_shape_data`, and then calls its `impute_shapes`
        to impute the missing shape (usually with some default shape).

        Returns:
            (np.ndarray): an array of symbols (e.g. o, x, + ...)
        """
        shape_data = self.master.get_shape_data()
        shape_data = self._filter_visible(shape_data)
        # Data has to be copied so the imputation can change it in-place
        # TODO: Try avoiding this when we move imputation to the widget
        if shape_data is not None:
            shape_data = np.copy(shape_data)
        shape_imputer = getattr(
            self.master, "impute_shapes", self.default_impute_shapes)
        shape_imputer(shape_data, len(self.CurveSymbols) - 1)
        if isinstance(shape_data, np.ndarray):
            shape_data = shape_data.astype(int)
        else:
            shape_data = np.zeros(self.n_shown, dtype=int)
        return self.CurveSymbols[shape_data]

    @staticmethod
    def default_impute_shapes(shape_data, default_symbol):
        """
        Fallback imputation for shapes.

        Use the default symbol, usually the last symbol in the list.

        Returns:
            (bool): True if there was any missing data
        """
        if shape_data is None:
            return False
        nans = np.isnan(shape_data)
        if np.any(nans):
            shape_data[nans] = default_symbol
            return True
        else:
            return False

    def update_shapes(self):
        """
        Trigger an update of point symbols

        The method calls `get_shapes` to obtain an array with a symbol
        for each point and uses it to update the symbols.

        Finally, the method updates the legend.
        """
        if self.scatterplot_item:
            shape_data = self.get_shapes()
            self.scatterplot_item.setSymbol(shape_data)
        self.update_legends()

    def update_grid_visibility(self):
        """Show or hide the grid"""
        self.plot_widget.showGrid(x=self.show_grid, y=self.show_grid)

    def update_legend_visibility(self):
        """
        Show or hide legends based on whether they are enabled and non-empty
        """
        self.shape_legend.setVisible(
            self.show_legend and bool(self.shape_legend.items))
        self.color_legend.setVisible(
            self.show_legend and bool(self.color_legend.items))

    def update_legends(self):
        """Update content of legends and their visibility"""
        cont_color = self.master.is_continuous_color()
        shape_labels = self.master.get_shape_labels()
        color_labels = self.master.get_color_labels()
        if shape_labels == color_labels and shape_labels is not None:
            self._update_combined_legend(shape_labels)
        else:
            self._update_shape_legend(shape_labels)
            if cont_color:
                self._update_continuous_color_legend(color_labels)
            else:
                self._update_color_legend(color_labels)
        self.update_legend_visibility()

    def _update_shape_legend(self, labels):
        self.shape_legend.clear()
        if labels is None or self.scatterplot_item is None:
            return
        color = QColor(0, 0, 0)
        color.setAlpha(self.alpha_value)
        for label, symbol in zip(labels, self.CurveSymbols):
            self.shape_legend.addItem(
                ScatterPlotItem(pen=color, brush=color, size=10, symbol=symbol),
                escape(label))

    def _update_continuous_color_legend(self, label_formatter):
        self.color_legend.clear()
        if self.scale is None or self.scatterplot_item is None:
            return
        label = PaletteItemSample(self.palette, self.scale, label_formatter)
        self.color_legend.addItem(label, "")
        self.color_legend.setGeometry(label.boundingRect())

    def _update_color_legend(self, labels):
        self.color_legend.clear()
        if labels is None:
            return
        self._update_colored_legend(self.color_legend, labels, 'o')

    def _update_combined_legend(self, labels):
        # update_colored_legend will already clear the shape legend
        # so we remove colors here
        use_legend = \
            self.shape_legend if self.shape_legend.items else self.color_legend
        self.color_legend.clear()
        self.shape_legend.clear()
        self._update_colored_legend(use_legend, labels, self.CurveSymbols)

    def _update_colored_legend(self, legend, labels, symbols):
        if self.scatterplot_item is None or not self.palette:
            return
        if isinstance(symbols, str):
            symbols = itertools.repeat(symbols, times=len(labels))
        for i, (label, symbol) in enumerate(zip(labels, symbols)):
            color = QColor(*self.palette.getRGB(i))
            pen = _make_pen(color.darker(self.DarkerValue), 1.5)
            color.setAlpha(255 if self.subset_is_shown else self.alpha_value)
            brush = QBrush(color)
            legend.addItem(
                ScatterPlotItem(pen=pen, brush=brush, size=10, symbol=symbol),
                escape(label))

    def zoom_button_clicked(self):
        self.plot_widget.getViewBox().setMouseMode(
            self.plot_widget.getViewBox().RectMode)

    def pan_button_clicked(self):
        self.plot_widget.getViewBox().setMouseMode(
            self.plot_widget.getViewBox().PanMode)

    def select_button_clicked(self):
        self.plot_widget.getViewBox().setMouseMode(
            self.plot_widget.getViewBox().RectMode)

    def reset_button_clicked(self):
        self.plot_widget.getViewBox().autoRange()
        self.update_labels()

    def select_by_click(self, _, points):
        if self.scatterplot_item is not None:
            self.select(points)

    def select_by_rectangle(self, rect):
        if self.scatterplot_item is not None:
            x0, x1 = sorted((rect.topLeft().x(), rect.bottomRight().x()))
            y0, y1 = sorted((rect.topLeft().y(), rect.bottomRight().y()))
            x, y = self.master.get_coordinates_data()
            indices = np.flatnonzero(
                (x0 <= x) & (x <= x1) & (y0 <= y) & (y <= y1))
            self.select_by_indices(indices.astype(int))

    def unselect_all(self):
        if self.selection is not None:
            self.selection = None
            self.update_selection_colors()
            if self.label_only_selected:
                self.update_labels()
            self.master.selection_changed()

    def select(self, points):
        # noinspection PyArgumentList
        if self.scatterplot_item is None:
            return
        indices = [p.data() for p in points]
        self.select_by_indices(indices)

    def select_by_indices(self, indices):
        if self.selection is None:
            self.selection = np.zeros(self.n_valid, dtype=np.uint8)
        keys = QApplication.keyboardModifiers()
        if keys & Qt.AltModifier:
            self.selection_remove(indices)
        elif keys & Qt.ShiftModifier and keys & Qt.ControlModifier:
            self.selection_append(indices)
        elif keys & Qt.ShiftModifier:
            self.selection_new_group(indices)
        else:
            self.selection_select(indices)

    def selection_select(self, indices):
        self.selection = np.zeros(self.n_valid, dtype=np.uint8)
        self.selection[indices] = 1
        self._update_after_selection()

    def selection_append(self, indices):
        self.selection[indices] = np.max(self.selection)
        self._update_after_selection()

    def selection_new_group(self, indices):
        self.selection[indices] = np.max(self.selection) + 1
        self._update_after_selection()

    def selection_remove(self, indices):
        self.selection[indices] = 0
        self._update_after_selection()

    def _update_after_selection(self):
        self._compress_indices()
        self.update_selection_colors()
        if self.label_only_selected:
            self.update_labels()
        self.master.selection_changed()

    def _compress_indices(self):
        indices = sorted(set(self.selection) | {0})
        if len(indices) == max(indices) + 1:
            return
        mapping = np.zeros((max(indices) + 1,), dtype=int)
        for i, ind in enumerate(indices):
            mapping[ind] = i
        self.selection = mapping[self.selection]

    def get_selection(self):
        if self.selection is None:
            return np.array([], dtype=np.uint8)
        else:
            return np.flatnonzero(self.selection)

    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


class HelpEventDelegate(EventDelegate):
    def __init__(self, delegate, parent=None):
        super().__init__(delegate, parent)
        warnings.warn("HelpEventDelegate class has been deprecated since 3.17."
                      " Use Orange.widgets.visualize.utils.plotutils."
                      "HelpEventDelegate instead.", OrangeDeprecationWarning)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]

**Title:** OWScatterPlotGraph Fails to Display Separate Color Legend When Shape and Color Labels Match

**Description:**
When the shape labels and color labels are identical, the color legend fails to display separately as expected. This issue occurs even when the color and shape data are distinct, leading to a combined legend that hides the color information.

**Example Code:**
```python
master.get_shape_data = lambda: np.arange(10, dtype=float) % 3
master.get_color_data = lambda: 2 * np.arange(10, dtype=float) % 3
master.get_shape_labels = lambda: ["a", "b"]
master.get_color_labels = lambda: ["a", "b"]

graph.update_legends()

# Expected: Both shape_legend and color_legend should be visible
# Actual: color_legend is not visible
```

**Expected Behavior:**
When shape labels and color labels are the same, and the color data differs from the shape data, both the shape legend and the color legend should be displayed separately to accurately represent the distinct attributes.

**Actual Behavior:**
Only the shape legend is displayed, and the color legend remains hidden, making it unclear which colors correspond to which data points.

[/ISSUE]
{
    "TestOWScatterPlotBase.test_colors_continuous": "PASSED",
    "TestOWScatterPlotBase.test_colors_continuous_nan": "PASSED",
    "TestOWScatterPlotBase.test_colors_continuous_reused": "PASSED",
    "TestOWScatterPlotBase.test_colors_discrete": "PASSED",
    "TestOWScatterPlotBase.test_colors_discrete_nan": "PASSED",
    "TestOWScatterPlotBase.test_colors_none": "PASSED",
    "TestOWScatterPlotBase.test_colors_subset": "PASSED",
    "TestOWScatterPlotBase.test_density": "PASSED",
    "TestOWScatterPlotBase.test_hiding_too_many_labels": "PASSED",
    "TestOWScatterPlotBase.test_label_mask_all_visible": "PASSED",
    "TestOWScatterPlotBase.test_label_mask_with_invisible": "PASSED",
    "TestOWScatterPlotBase.test_label_mask_with_invisible_and_view": "PASSED",
    "TestOWScatterPlotBase.test_labels": "PASSED",
    "TestOWScatterPlotBase.test_labels_observes_mask": "PASSED",
    "TestOWScatterPlotBase.test_legend_combine": "PASSED",
    "TestOWScatterPlotBase.test_reset_calls_all_updates_and_update_doesnt": "PASSED",
    "TestOWScatterPlotBase.test_reset_graph_no_data": "PASSED",
    "TestOWScatterPlotBase.test_sampling_keeps_selection": "PASSED",
    "TestOWScatterPlotBase.test_select_by_click": "PASSED",
    "TestOWScatterPlotBase.test_select_by_indices": "PASSED",
    "TestOWScatterPlotBase.test_select_by_rectangle": "PASSED",
    "TestOWScatterPlotBase.test_selection_colors": "PASSED",
    "TestOWScatterPlotBase.test_shapes": "PASSED",
    "TestOWScatterPlotBase.test_shapes_nan": "PASSED",
    "TestOWScatterPlotBase.test_show_grid": "PASSED",
    "TestOWScatterPlotBase.test_show_legend": "PASSED",
    "TestOWScatterPlotBase.test_show_legend_no_data": "PASSED",
    "TestOWScatterPlotBase.test_size_animation": "PASSED",
    "TestOWScatterPlotBase.test_size_normalization": "PASSED",
    "TestOWScatterPlotBase.test_size_rounding_half_pixel": "PASSED",
    "TestOWScatterPlotBase.test_size_with_nans": "PASSED",
    "TestOWScatterPlotBase.test_sizes_all_same_or_nan": "PASSED",
    "TestOWScatterPlotBase.test_sizes_custom_imputation": "PASSED",
    "TestOWScatterPlotBase.test_sizes_point_width_is_linear": "PASSED",
    "TestOWScatterPlotBase.test_sizes_selection": "PASSED",
    "TestOWScatterPlotBase.test_unselect_all": "PASSED",
    "TestOWScatterPlotBase.test_update_coordinates_indices": "PASSED",
    "TestOWScatterPlotBase.test_update_coordinates_no_data": "PASSED",
    "TestOWScatterPlotBase.test_colors_update_legend_and_density": "FAILED",
    "TestOWScatterPlotBase.test_jittering": "FAILED",
    "TestOWScatterPlotBase.test_labels_update_coordinates": "FAILED",
    "TestOWScatterPlotBase.test_no_needless_buildatlas": "FAILED",
    "TestOWScatterPlotBase.test_sampling": "FAILED",
    "TestOWScatterPlotBase.test_update_coordinates": "FAILED",
    "TestOWScatterPlotBase.test_update_coordinates_and_density": "FAILED",
    "TestOWScatterPlotBase.test_update_coordinates_and_labels": "FAILED",
    "TestOWScatterPlotBase.test_update_coordinates_reset_view": "FAILED"
}
diff --git a/Orange/widgets/visualize/owscatterplotgraph.py b/Orange/widgets/visualize/owscatterplotgraph.py
index 505f792b3..355922765 100644
--- a/Orange/widgets/visualize/owscatterplotgraph.py
+++ b/Orange/widgets/visualize/owscatterplotgraph.py
@@ -1208,7 +1208,15 @@ class OWScatterPlotBase(gui.OWComponent, QObject):
         cont_color = self.master.is_continuous_color()
         shape_labels = self.master.get_shape_labels()
         color_labels = self.master.get_color_labels()
-        if shape_labels == color_labels and shape_labels is not None:
+        if not cont_color and shape_labels is not None \
+                and shape_labels == color_labels:
+            colors = self.master.get_color_data()
+            shapes = self.master.get_shape_data()
+            mask = np.isfinite(colors) * np.isfinite(shapes)
+            combined = (colors == shapes)[mask].all()
+        else:
+            combined = False
+        if combined:
             self._update_combined_legend(shape_labels)
         else:
             self._update_shape_legend(shape_labels)

{"Orange/widgets/visualize/owscatterplotgraph.py": "import sys\nimport itertools\nimport warnings\nfrom xml.sax.saxutils import escape\nfrom math import log10, floor, ceil\n\nimport numpy as np\nfrom AnyQt.QtCore import Qt, QRectF, QSize, QTimer, pyqtSignal as Signal, \\\n    QObject\nfrom AnyQt.QtGui import (\n    QStaticText, QColor, QPen, QBrush, QPainterPath, QTransform, QPainter\n)\nfrom AnyQt.QtWidgets import (\n    QApplication, QToolTip, QGraphicsTextItem, QGraphicsRectItem\n)\n\nimport pyqtgraph as pg\nimport pyqtgraph.graphicsItems.ScatterPlotItem\nfrom pyqtgraph.graphicsItems.LegendItem import (\n    LegendItem as PgLegendItem, ItemSample\n)\nfrom pyqtgraph.graphicsItems.TextItem import TextItem\n\nfrom Orange.util import OrangeDeprecationWarning\nfrom Orange.widgets import gui\nfrom Orange.widgets.settings import Setting\nfrom Orange.widgets.utils import classdensity\nfrom Orange.widgets.utils.colorpalette import ColorPaletteGenerator\nfrom Orange.widgets.utils.plot import OWPalette\nfrom Orange.widgets.visualize.owscatterplotgraph_obsolete import (\n    OWScatterPlotGraph as OWScatterPlotGraphObs\n)\nfrom Orange.widgets.visualize.utils.plotutils import (\n    HelpEventDelegate as EventDelegate,\n    InteractiveViewBox as ViewBox\n)\n\n\nSELECTION_WIDTH = 5\nMAX_N_VALID_SIZE_ANIMATE = 1000\n\n\nclass PaletteItemSample(ItemSample):\n    \"\"\"A color strip to insert into legends for discretized continuous values\"\"\"\n\n    def __init__(self, palette, scale, label_formatter=None):\n        \"\"\"\n        :param palette: palette used for showing continuous values\n        :type palette: ContinuousPaletteGenerator\n        :param scale: an instance of DiscretizedScale that defines the\n                      conversion of values into bins\n        :type scale: DiscretizedScale\n        \"\"\"\n        super().__init__(None)\n        self.palette = palette\n        self.scale = scale\n        if label_formatter is None:\n            label_formatter = \"{{:.{}f}}\".format(scale.decimals).format\n        cuts = [label_formatter(scale.offset + i * scale.width)\n                for i in range(scale.bins + 1)]\n        self.labels = [QStaticText(\"{} - {}\".format(fr, to))\n                       for fr, to in zip(cuts, cuts[1:])]\n        for label in self.labels:\n            label.prepare()\n        self.text_width = max(label.size().width() for label in self.labels)\n\n    def boundingRect(self):\n        return QRectF(0, 0, 40 + self.text_width, 20 + self.scale.bins * 15)\n\n    def paint(self, p, *args):\n        p.setRenderHint(p.Antialiasing)\n        scale = self.scale\n        font = p.font()\n        font.setPixelSize(11)\n        p.setFont(font)\n        for i, label in enumerate(self.labels):\n            color = QColor(*self.palette.getRGB((i + 0.5) / scale.bins))\n            p.setPen(Qt.NoPen)\n            p.setBrush(QBrush(color))\n            p.drawRect(0, i * 15, 15, 15)\n            p.setPen(QPen(Qt.black))\n            p.drawStaticText(20, i * 15 + 1, label)\n\n\nclass LegendItem(PgLegendItem):\n    def __init__(self, size=None, offset=None, pen=None, brush=None):\n        super().__init__(size, offset)\n\n        self.layout.setContentsMargins(5, 5, 5, 5)\n        self.layout.setHorizontalSpacing(15)\n        self.layout.setColumnAlignment(1, Qt.AlignLeft | Qt.AlignVCenter)\n\n        if pen is None:\n            pen = QPen(QColor(196, 197, 193, 200), 1)\n            pen.setCosmetic(True)\n        self.__pen = pen\n\n        if brush is None:\n            brush = QBrush(QColor(232, 232, 232, 100))\n        self.__brush = brush\n\n    def restoreAnchor(self, anchors):\n        \"\"\"\n        Restore (parent) relative position from stored anchors.\n\n        The restored position is within the parent bounds.\n        \"\"\"\n        anchor, parentanchor = anchors\n        self.anchor(*bound_anchor_pos(anchor, parentanchor))\n\n    def paint(self, painter, option, widget=None):\n        painter.setPen(self.__pen)\n        painter.setBrush(self.__brush)\n        rect = self.contentsRect()\n        painter.drawRoundedRect(rect, 2, 2)\n\n    def addItem(self, item, name):\n        super().addItem(item, name)\n        # Fix-up the label alignment\n        _, label = self.items[-1]\n        label.setText(name, justify=\"left\")\n\n    def clear(self):\n        \"\"\"\n        Clear all legend items.\n        \"\"\"\n        items = list(self.items)\n        self.items = []\n        for sample, label in items:\n            self.layout.removeItem(sample)\n            self.layout.removeItem(label)\n            sample.hide()\n            label.hide()\n\n        self.updateSize()\n\n\ndef bound_anchor_pos(corner, parentpos):\n    corner = np.clip(corner, 0, 1)\n    parentpos = np.clip(parentpos, 0, 1)\n\n    irx, iry = corner\n    prx, pry = parentpos\n\n    if irx > 0.9 and prx < 0.1:\n        irx = prx = 0.0\n    if iry > 0.9 and pry < 0.1:\n        iry = pry = 0.0\n    if irx < 0.1 and prx > 0.9:\n        irx = prx = 1.0\n    if iry < 0.1 and pry > 0.9:\n        iry = pry = 1.0\n    return (irx, iry), (prx, pry)\n\n\nclass DiscretizedScale:\n    \"\"\"\n    Compute suitable bins for continuous value from its minimal and\n    maximal value.\n\n    The width of the bin is a power of 10 (including negative powers).\n    The minimal value is rounded up and the maximal is rounded down. If this\n    gives less than 3 bins, the width is divided by four; if it gives\n    less than 6, it is halved.\n\n    .. attribute:: offset\n        The start of the first bin.\n\n    .. attribute:: width\n        The width of the bins\n\n    .. attribute:: bins\n        The number of bins\n\n    .. attribute:: decimals\n        The number of decimals used for printing out the boundaries\n    \"\"\"\n    def __init__(self, min_v, max_v):\n        \"\"\"\n        :param min_v: Minimal value\n        :type min_v: float\n        :param max_v: Maximal value\n        :type max_v: float\n        \"\"\"\n        super().__init__()\n        dif = max_v - min_v if max_v != min_v else 1\n        if np.isnan(dif):\n            min_v = 0\n            dif = decimals = 1\n        else:\n            decimals = -floor(log10(dif))\n        resolution = 10 ** -decimals\n        bins = ceil(dif / resolution)\n        if bins < 6:\n            decimals += 1\n            if bins < 3:\n                resolution /= 4\n            else:\n                resolution /= 2\n            bins = ceil(dif / resolution)\n        self.offset = resolution * floor(min_v // resolution)\n        self.bins = bins\n        self.decimals = max(decimals, 0)\n        self.width = resolution\n\n\nclass InteractiveViewBox(ViewBox):\n    def __init__(self, graph, enable_menu=False):\n        super().__init__(graph, enable_menu)\n        warnings.warn(\"InteractiveViewBox class has been deprecated since \"\n                      \"3.17. Use Orange.widgets.visualize.utils.plotutils.\"\n                      \"InteractiveViewBox instead.\", OrangeDeprecationWarning)\n\n\nclass OWScatterPlotGraph(OWScatterPlotGraphObs):\n    def __init__(self, scatter_widget, parent=None, _=\"None\", view_box=InteractiveViewBox):\n        super().__init__(scatter_widget, parent=parent, _=_, view_box=view_box)\n        warnings.warn(\"OWScatterPlotGraph class has been deprecated since \"\n                      \"3.17. Use OWScatterPlotBase instead.\",\n                      OrangeDeprecationWarning)\n\n\nclass ScatterPlotItem(pg.ScatterPlotItem):\n    \"\"\"PyQtGraph's ScatterPlotItem calls updateSpots at any change of sizes/colors/symbols,\n    which then rebuilds the stored pixmaps for each symbol. Because Orange calls\n    set* function in succession, we postpone updateSpots() to paint().\"\"\"\n\n    _update_spots_in_paint = False\n\n    def updateSpots(self, dataSet=None):  # pylint: disable=unused-argument\n        self._update_spots_in_paint = True\n        self.update()\n\n    def paint(self, painter, option, widget=None):\n        if self._update_spots_in_paint:\n            self._update_spots_in_paint = False\n            super().updateSpots()\n        painter.setRenderHint(QPainter.SmoothPixmapTransform, True)\n        super().paint(painter, option, widget)\n\n\ndef _define_symbols():\n    \"\"\"\n    Add symbol ? to ScatterPlotItemSymbols,\n    reflect the triangle to point upwards\n    \"\"\"\n    symbols = pyqtgraph.graphicsItems.ScatterPlotItem.Symbols\n    path = QPainterPath()\n    path.addEllipse(QRectF(-0.35, -0.35, 0.7, 0.7))\n    path.moveTo(-0.5, 0.5)\n    path.lineTo(0.5, -0.5)\n    path.moveTo(-0.5, -0.5)\n    path.lineTo(0.5, 0.5)\n    symbols[\"?\"] = path\n\n    tr = QTransform()\n    tr.rotate(180)\n    symbols['t'] = tr.map(symbols['t'])\n\n\n_define_symbols()\n\n\ndef _make_pen(color, width):\n    p = QPen(color, width)\n    p.setCosmetic(True)\n    return p\n\n\nclass OWScatterPlotBase(gui.OWComponent, QObject):\n    \"\"\"\n    Provide a graph component for widgets that show any kind of point plot\n\n    The component plots a set of points with given coordinates, shapes,\n    sizes and colors. Its function is similar to that of a *view*, whereas\n    the widget represents a *model* and a *controler*.\n\n    The model (widget) needs to provide methods:\n\n    - `get_coordinates_data`, `get_size_data`, `get_color_data`,\n      `get_shape_data`, `get_label_data`, which return a 1d array (or two\n      arrays, for `get_coordinates_data`) of `dtype` `float64`, except for\n      `get_label_data`, which returns formatted labels;\n    - `get_shape_labels` returns a list of strings for shape legend\n    - `get_color_labels` returns strings for color legend, or a function for\n       formatting numbers if the legend is continuous, or None for default\n       formatting\n    - `get_tooltip`, which gives a tooltip for a single data point\n    - (optional) `impute_sizes`, `impute_shapes` get final coordinates and\n      shapes, and replace nans;\n    - `get_subset_mask` returns a bool array indicating whether a\n      data point is in the subset or not (e.g. in the 'Data Subset' signal\n      in the Scatter plot and similar widgets);\n    - `get_palette` returns a palette appropriate for visualizing the\n      current color data;\n    - `is_continuous_color` decides the type of the color legend;\n\n    The widget (in a role of controller) must also provide methods\n    - `selection_changed`\n\n    If `get_coordinates_data` returns `(None, None)`, the plot is cleared. If\n    `get_size_data`, `get_color_data` or `get_shape_data` return `None`,\n    all points will have the same size, color or shape, respectively.\n    If `get_label_data` returns `None`, there are no labels.\n\n    The view (this compomnent) provides methods `update_coordinates`,\n    `update_sizes`, `update_colors`, `update_shapes` and `update_labels`\n    that the widget (in a role of a controler) should call when any of\n    these properties are changed. If the widget calls, for instance, the\n    plot's `update_colors`, the plot will react by calling the widget's\n    `get_color_data` as well as the widget's methods needed to construct the\n    legend.\n\n    The view also provides a method `reset_graph`, which should be called only\n    when\n    - the widget gets entirely new data\n    - the number of points may have changed, for instance when selecting\n    a different attribute for x or y in the scatter plot, where the points\n    with missing x or y coordinates are hidden.\n\n    Every `update_something` calls the plot's `get_something`, which\n    calls the model's `get_something_data`, then it transforms this data\n    into whatever is needed (colors, shapes, scaled sizes) and changes the\n    plot. For the simplest example, here is `update_shapes`:\n\n    ```\n        def update_shapes(self):\n            if self.scatterplot_item:\n                shape_data = self.get_shapes()\n                self.scatterplot_item.setSymbol(shape_data)\n            self.update_legends()\n\n        def get_shapes(self):\n            shape_data = self.master.get_shape_data()\n            shape_data = self.master.impute_shapes(\n                shape_data, len(self.CurveSymbols) - 1)\n            return self.CurveSymbols[shape_data]\n    ```\n\n    On the widget's side, `get_something_data` is essentially just:\n\n    ```\n        def get_size_data(self):\n            return self.get_column(self.attr_size)\n    ```\n\n    where `get_column` retrieves a column while also filtering out the\n    points with missing x and y and so forth. (Here we present the simplest\n    two cases, \"shapes\" for the view and \"sizes\" for the model. The colors\n    for the view are more complicated since they deal with discrete and\n    continuous palettes, and the shapes for the view merge infrequent shapes.)\n\n    The plot can also show just a random sample of the data. The sample size is\n    set by `set_sample_size`, and the rest is taken care by the plot: the\n    widget keeps providing the data for all points, selection indices refer\n    to the entire set etc. Internally, sampling happens as early as possible\n    (in methods `get_<something>`).\n    \"\"\"\n    too_many_labels = Signal(bool)\n    begin_resizing = Signal()\n    step_resizing = Signal()\n    end_resizing = Signal()\n\n    label_only_selected = Setting(False)\n    point_width = Setting(10)\n    alpha_value = Setting(128)\n    show_grid = Setting(False)\n    show_legend = Setting(True)\n    class_density = Setting(False)\n    jitter_size = Setting(0)\n\n    resolution = 256\n\n    CurveSymbols = np.array(\"o x t + d star ?\".split())\n    MinShapeSize = 6\n    DarkerValue = 120\n    UnknownColor = (168, 50, 168)\n\n    COLOR_NOT_SUBSET = (128, 128, 128, 0)\n    COLOR_SUBSET = (128, 128, 128, 255)\n    COLOR_DEFAULT = (128, 128, 128, 0)\n\n    MAX_VISIBLE_LABELS = 500\n\n    def __init__(self, scatter_widget, parent=None, view_box=ViewBox):\n        QObject.__init__(self)\n        gui.OWComponent.__init__(self, scatter_widget)\n\n        self.subset_is_shown = False\n\n        self.view_box = view_box(self)\n        self.plot_widget = pg.PlotWidget(viewBox=self.view_box, parent=parent,\n                                         background=\"w\")\n        self.plot_widget.hideAxis(\"left\")\n        self.plot_widget.hideAxis(\"bottom\")\n        self.plot_widget.getPlotItem().buttonsHidden = True\n        self.plot_widget.setAntialiasing(True)\n        self.plot_widget.sizeHint = lambda: QSize(500, 500)\n\n        self.density_img = None\n        self.scatterplot_item = None\n        self.scatterplot_item_sel = None\n        self.labels = []\n\n        self.master = scatter_widget\n        self._create_drag_tooltip(self.plot_widget.scene())\n\n        self.selection = None  # np.ndarray\n\n        self.n_valid = 0\n        self.n_shown = 0\n        self.sample_size = None\n        self.sample_indices = None\n\n        self.palette = None\n\n        self.shape_legend = self._create_legend(((1, 0), (1, 0)))\n        self.color_legend = self._create_legend(((1, 1), (1, 1)))\n        self.update_legend_visibility()\n\n        self.scale = None  # DiscretizedScale\n        self._too_many_labels = False\n\n        # self.setMouseTracking(True)\n        # self.grabGesture(QPinchGesture)\n        # self.grabGesture(QPanGesture)\n\n        self.update_grid_visibility()\n\n        self._tooltip_delegate = EventDelegate(self.help_event)\n        self.plot_widget.scene().installEventFilter(self._tooltip_delegate)\n        self.view_box.sigTransformChanged.connect(self.update_density)\n        self.view_box.sigRangeChangedManually.connect(self.update_labels)\n\n        self.timer = None\n\n    def _create_legend(self, anchor):\n        legend = LegendItem()\n        legend.setParentItem(self.plot_widget.getViewBox())\n        legend.restoreAnchor(anchor)\n        return legend\n\n    def _create_drag_tooltip(self, scene):\n        tip_parts = [\n            (Qt.ShiftModifier, \"Shift: Add group\"),\n            (Qt.ShiftModifier + Qt.ControlModifier,\n             \"Shift-{}: Append to group\".\n             format(\"Cmd\" if sys.platform == \"darwin\" else \"Ctrl\")),\n            (Qt.AltModifier, \"Alt: Remove\")\n        ]\n        all_parts = \", \".join(part for _, part in tip_parts)\n        self.tiptexts = {\n            int(modifier): all_parts.replace(part, \"<b>{}</b>\".format(part))\n            for modifier, part in tip_parts\n        }\n        self.tiptexts[0] = all_parts\n\n        self.tip_textitem = text = QGraphicsTextItem()\n        # Set to the longest text\n        text.setHtml(self.tiptexts[Qt.ShiftModifier + Qt.ControlModifier])\n        text.setPos(4, 2)\n        r = text.boundingRect()\n        rect = QGraphicsRectItem(0, 0, r.width() + 8, r.height() + 4)\n        rect.setBrush(QColor(224, 224, 224, 212))\n        rect.setPen(QPen(Qt.NoPen))\n        self.update_tooltip()\n\n        scene.drag_tooltip = scene.createItemGroup([rect, text])\n        scene.drag_tooltip.hide()\n\n    def update_tooltip(self, modifiers=Qt.NoModifier):\n        modifiers &= Qt.ShiftModifier + Qt.ControlModifier + Qt.AltModifier\n        text = self.tiptexts.get(int(modifiers), self.tiptexts[0])\n        self.tip_textitem.setHtml(text + self._get_jittering_tooltip())\n\n    def _get_jittering_tooltip(self):\n        warn_jittered = \"\"\n        if self.jitter_size:\n            warn_jittered = \\\n                '<br/><br/>' \\\n                '<span style=\"background-color: red; color: white; ' \\\n                'font-weight: 500;\">' \\\n                '&nbsp;Warning: Selection is applied to unjittered data&nbsp;' \\\n                '</span>'\n        return warn_jittered\n\n    def update_jittering(self):\n        self.update_tooltip()\n        x, y = self.get_coordinates()\n        if x is None or not len(x) or self.scatterplot_item is None:\n            return\n        self._update_plot_coordinates(self.scatterplot_item, x, y)\n        self._update_plot_coordinates(self.scatterplot_item_sel, x, y)\n        self.update_labels()\n\n    # TODO: Rename to remove_plot_items\n    def clear(self):\n        \"\"\"\n        Remove all graphical elements from the plot\n\n        Calls the pyqtgraph's plot widget's clear, sets all handles to `None`,\n        removes labels and selections.\n\n        This method should generally not be called by the widget. If the data\n        is gone (*e.g.* upon receiving `None` as an input data signal), this\n        should be handler by calling `reset_graph`, which will in turn call\n        `clear`.\n\n        Derived classes should override this method if they add more graphical\n        elements. For instance, the regression line in the scatterplot adds\n        `self.reg_line_item = None` (the line in the plot is already removed\n        in this method).\n        \"\"\"\n        self.plot_widget.clear()\n\n        self.density_img = None\n        if self.timer is not None and self.timer.isActive():\n            self.timer.stop()\n            self.timer = None\n        self.scatterplot_item = None\n        self.scatterplot_item_sel = None\n        self.labels = []\n        self._signal_too_many_labels(False)\n        self.view_box.init_history()\n        self.view_box.tag_history()\n\n    # TODO: I hate `keep_something` and `reset_something` arguments\n    # __keep_selection is used exclusively be set_sample size which would\n    # otherwise just repeat the code from reset_graph except for resetting\n    # the selection. I'm uncomfortable with this; we may prefer to have a\n    # method _reset_graph which does everything except resetting the selection,\n    # and reset_graph would call it.\n    def reset_graph(self, __keep_selection=False):\n        \"\"\"\n        Reset the graph to new data (or no data)\n\n        The method must be called when the plot receives new data, in\n        particular when the number of points change. If only their properties\n        - like coordinates or shapes - change, an update method\n        (`update_coordinates`, `update_shapes`...) should be called instead.\n\n        The method must also be called when the data is gone.\n\n        The method calls `clear`, followed by calls of all update methods.\n\n        NB. Argument `__keep_selection` is for internal use only\n        \"\"\"\n        self.clear()\n        if not __keep_selection:\n            self.selection = None\n        self.sample_indices = None\n        self.update_coordinates()\n        self.update_point_props()\n\n    def set_sample_size(self, sample_size):\n        \"\"\"\n        Set the sample size\n\n        Args:\n            sample_size (int or None): sample size or `None` to show all points\n        \"\"\"\n        if self.sample_size != sample_size:\n            self.sample_size = sample_size\n            self.reset_graph(True)\n\n    def update_point_props(self):\n        \"\"\"\n        Update the sizes, colors, shapes and labels\n\n        The method calls the appropriate update methods for individual\n        properties.\n        \"\"\"\n        self.update_sizes()\n        self.update_colors()\n        self.update_selection_colors()\n        self.update_shapes()\n        self.update_labels()\n\n    # Coordinates\n    # TODO: It could be nice if this method was run on entire data, not just\n    # a sample. For this, however, it would need to either be called from\n    # `get_coordinates` before sampling (very ugly) or call\n    # `self.master.get_coordinates_data` (beyond ugly) or the widget would\n    # have to store the ranges of unsampled data (ugly).\n    # Maybe we leave it as it is.\n    def _reset_view(self, x_data, y_data):\n        \"\"\"\n        Set the range of the view box\n\n        Args:\n            x_data (np.ndarray): x coordinates\n            y_data (np.ndarray) y coordinates\n        \"\"\"\n        min_x, max_x = np.min(x_data), np.max(x_data)\n        min_y, max_y = np.min(y_data), np.max(y_data)\n        self.view_box.setRange(\n            QRectF(min_x, min_y, max_x - min_x or 1, max_y - min_y or 1),\n            padding=0.025)\n\n    def _filter_visible(self, data):\n        \"\"\"Return the sample from the data using the stored sample_indices\"\"\"\n        if data is None or self.sample_indices is None:\n            return data\n        else:\n            return np.asarray(data[self.sample_indices])\n\n    def get_coordinates(self):\n        \"\"\"\n        Prepare coordinates of the points in the plot\n\n        The method is called by `update_coordinates`. It gets the coordinates\n        from the widget, jitters them and return them.\n\n        The methods also initializes the sample indices if neededd and stores\n        the original and sampled number of points.\n\n        Returns:\n            (tuple): a pair of numpy arrays containing (sampled) coordinates,\n                or `(None, None)`.\n        \"\"\"\n        x, y = self.master.get_coordinates_data()\n        if x is None:\n            self.n_valid = self.n_shown = 0\n            return None, None\n        self.n_valid = len(x)\n        self._create_sample()\n        x = self._filter_visible(x)\n        y = self._filter_visible(y)\n        # Jittering after sampling is OK if widgets do not change the sample\n        # semi-permanently, e.g. take a sample for the duration of some\n        # animation. If the sample size changes dynamically (like by adding\n        # a \"sample size\" slider), points would move around when the sample\n        # size changes. To prevent this, jittering should be done before\n        # sampling (i.e. two lines earlier). This would slow it down somewhat.\n        x, y = self.jitter_coordinates(x, y)\n        return x, y\n\n    def _create_sample(self):\n        \"\"\"\n        Create a random sample if the data is larger than the set sample size\n        \"\"\"\n        self.n_shown = min(self.n_valid, self.sample_size or self.n_valid)\n        if self.sample_size is not None \\\n                and self.sample_indices is None \\\n                and self.n_valid != self.n_shown:\n            random = np.random.RandomState(seed=0)\n            self.sample_indices = random.choice(\n                self.n_valid, self.n_shown, replace=False)\n            # TODO: Is this really needed?\n            np.sort(self.sample_indices)\n\n    def jitter_coordinates(self, x, y):\n        \"\"\"\n        Display coordinates to random positions within ellipses with\n        radiuses of `self.jittter_size` percents of spans\n        \"\"\"\n        if self.jitter_size == 0:\n            return x, y\n        return self._jitter_data(x, y)\n\n    def _jitter_data(self, x, y, span_x=None, span_y=None):\n        if span_x is None:\n            span_x = np.max(x) - np.min(x)\n        if span_y is None:\n            span_y = np.max(y) - np.min(y)\n        random = np.random.RandomState(seed=0)\n        rs = random.uniform(0, 1, len(x))\n        phis = random.uniform(0, 2 * np.pi, len(x))\n        magnitude = self.jitter_size / 100\n        return (x + magnitude * span_x * rs * np.cos(phis),\n                y + magnitude * span_y * rs * np.sin(phis))\n\n    def _update_plot_coordinates(self, plot, x, y):\n        \"\"\"\n        Change the coordinates of points while keeping other properites\n\n        Note. Pyqtgraph does not offer a method for this: setting coordinates\n        invalidates other data. We therefore retrieve the data to set it\n        together with the coordinates. Pyqtgraph also does not offer a\n        (documented) method for retrieving the data, yet using\n        `plot.data[prop]` looks reasonably safe. The alternative, calling\n        update for every property would essentially reset the graph, which\n        can be time consuming.\n        \"\"\"\n        data = dict(x=x, y=y)\n        for prop in ('pen', 'brush', 'size', 'symbol', 'data',\n                     'sourceRect', 'targetRect'):\n            data[prop] = plot.data[prop]\n        plot.setData(**data)\n\n    def update_coordinates(self):\n        \"\"\"\n        Trigger the update of coordinates while keeping other features intact.\n\n        The method gets the coordinates by calling `self.get_coordinates`,\n        which in turn calls the widget's `get_coordinate_data`. The number of\n        coordinate pairs returned by the latter must match the current number\n        of points. If this is not the case, the widget should trigger\n        the complete update by calling `reset_graph` instead of this method.\n        \"\"\"\n        x, y = self.get_coordinates()\n        if x is None or not len(x):\n            return\n        if self.scatterplot_item is None:\n            if self.sample_indices is None:\n                indices = np.arange(self.n_valid)\n            else:\n                indices = self.sample_indices\n            kwargs = dict(x=x, y=y, data=indices)\n            self.scatterplot_item = ScatterPlotItem(**kwargs)\n            self.scatterplot_item.sigClicked.connect(self.select_by_click)\n            self.scatterplot_item_sel = ScatterPlotItem(**kwargs)\n            self.plot_widget.addItem(self.scatterplot_item_sel)\n            self.plot_widget.addItem(self.scatterplot_item)\n        else:\n            self._update_plot_coordinates(self.scatterplot_item, x, y)\n            self._update_plot_coordinates(self.scatterplot_item_sel, x, y)\n            self.update_labels()\n\n        self.update_density()  # Todo: doesn't work: try MDS with density on\n        self._reset_view(x, y)\n\n    # Sizes\n    def get_sizes(self):\n        \"\"\"\n        Prepare data for sizes of points in the plot\n\n        The method is called by `update_sizes`. It gets the sizes\n        from the widget and performs the necessary scaling and sizing.\n        The output is rounded to half a pixel for faster drawing.\n\n        Returns:\n            (np.ndarray): sizes\n        \"\"\"\n        size_column = self.master.get_size_data()\n        if size_column is None:\n            return np.full((self.n_shown,),\n                           self.MinShapeSize + (5 + self.point_width) * 0.5)\n        size_column = self._filter_visible(size_column)\n        size_column = size_column.copy()\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n            size_column -= np.nanmin(size_column)\n            mx = np.nanmax(size_column)\n        if mx > 0:\n            size_column /= mx\n        else:\n            size_column[:] = 0.5\n\n        sizes = self.MinShapeSize + (5 + self.point_width) * size_column\n        # round sizes to half pixel for smaller pyqtgraph's symbol pixmap atlas\n        sizes = (sizes * 2).round() / 2\n        return sizes\n\n    def update_sizes(self):\n        \"\"\"\n        Trigger an update of point sizes\n\n        The method calls `self.get_sizes`, which in turn calls the widget's\n        `get_size_data`. The result are properly scaled and then passed\n        back to widget for imputing (`master.impute_sizes`).\n        \"\"\"\n        if self.scatterplot_item:\n            size_data = self.get_sizes()\n            size_imputer = getattr(\n                self.master, \"impute_sizes\", self.default_impute_sizes)\n            size_imputer(size_data)\n\n            if self.timer is not None and self.timer.isActive():\n                self.timer.stop()\n                self.timer = None\n\n            current_size_data = self.scatterplot_item.data[\"size\"].copy()\n            diff = size_data - current_size_data\n            widget = self\n\n            class Timeout:\n                # 0.5 - np.cos(np.arange(0.17, 1, 0.17) * np.pi) / 2\n                factors = [0.07, 0.26, 0.52, 0.77, 0.95, 1]\n\n                def __init__(self):\n                    self._counter = 0\n\n                def __call__(self):\n                    factor = self.factors[self._counter]\n                    self._counter += 1\n                    size = current_size_data + diff * factor\n                    if len(self.factors) == self._counter:\n                        widget.timer.stop()\n                        widget.timer = None\n                        size = size_data\n                    widget.scatterplot_item.setSize(size)\n                    widget.scatterplot_item_sel.setSize(size + SELECTION_WIDTH)\n                    if widget.timer is None:\n                        widget.end_resizing.emit()\n                    else:\n                        widget.step_resizing.emit()\n\n            if self.n_valid <= MAX_N_VALID_SIZE_ANIMATE and \\\n                    np.all(current_size_data > 0) and np.any(diff != 0):\n                # If encountered any strange behaviour when updating sizes,\n                # implement it with threads\n                self.begin_resizing.emit()\n                self.timer = QTimer(self.scatterplot_item, interval=50)\n                self.timer.timeout.connect(Timeout())\n                self.timer.start()\n            else:\n                self.begin_resizing.emit()\n                self.scatterplot_item.setSize(size_data)\n                self.scatterplot_item_sel.setSize(size_data + SELECTION_WIDTH)\n                self.end_resizing.emit()\n\n    update_point_size = update_sizes  # backward compatibility (needed?!)\n    update_size = update_sizes\n\n    @classmethod\n    def default_impute_sizes(cls, size_data):\n        \"\"\"\n        Fallback imputation for sizes.\n\n        Set the size to two pixels smaller than the minimal size\n\n        Returns:\n            (bool): True if there was any missing data\n        \"\"\"\n        nans = np.isnan(size_data)\n        if np.any(nans):\n            size_data[nans] = cls.MinShapeSize - 2\n            return True\n        else:\n            return False\n\n    # Colors\n    def get_colors(self):\n        \"\"\"\n        Prepare data for colors of the points in the plot\n\n        The method is called by `update_colors`. It gets the colors and the\n        indices of the data subset from the widget (`get_color_data`,\n        `get_subset_mask`), and constructs lists of pens and brushes for\n        each data point.\n\n        The method uses different palettes for discrete and continuous data,\n        as determined by calling the widget's method `is_continuous_color`.\n\n        If also marks the points that are in the subset as defined by, for\n        instance the 'Data Subset' signal in the Scatter plot and similar\n        widgets. (Do not confuse this with *selected points*, which are\n        marked by circles around the points, which are colored by groups\n        and thus independent of this method.)\n\n        Returns:\n            (tuple): a list of pens and list of brushes\n        \"\"\"\n        self.palette = self.master.get_palette()\n        c_data = self.master.get_color_data()\n        c_data = self._filter_visible(c_data)\n        subset = self.master.get_subset_mask()\n        subset = self._filter_visible(subset)\n        self.subset_is_shown = subset is not None\n        if c_data is None:  # same color\n            return self._get_same_colors(subset)\n        elif self.master.is_continuous_color():\n            return self._get_continuous_colors(c_data, subset)\n        else:\n            return self._get_discrete_colors(c_data, subset)\n\n    def _get_same_colors(self, subset):\n        \"\"\"\n        Return the same pen for all points while the brush color depends\n        upon whether the point is in the subset or not\n\n        Args:\n            subset (np.ndarray): a bool array indicating whether a data point\n                is in the subset or not (e.g. in the 'Data Subset' signal\n                in the Scatter plot and similar widgets);\n\n        Returns:\n            (tuple): a list of pens and list of brushes\n        \"\"\"\n        color = self.plot_widget.palette().color(OWPalette.Data)\n        pen = [_make_pen(color, 1.5)] * self.n_shown  # use a single QPen instance\n        if subset is not None:\n            brush = np.where(\n                subset,\n                *(QBrush(QColor(*col))\n                  for col in (self.COLOR_SUBSET, self.COLOR_NOT_SUBSET)))\n        else:\n            color = QColor(*self.COLOR_DEFAULT)\n            color.setAlpha(self.alpha_value)\n            brush = [QBrush(color)] * self.n_shown  # use a single QBrush instance\n        return pen, brush\n\n    def _get_continuous_colors(self, c_data, subset):\n        \"\"\"\n        Return the pens and colors whose color represent an index into\n        a continuous palette. The same color is used for pen and brush,\n        except the former is darker. If the data has a subset, the brush\n        is transparent for points that are not in the subset.\n        \"\"\"\n        if np.isnan(c_data).all():\n            self.scale = None\n        else:\n            self.scale = DiscretizedScale(np.nanmin(c_data), np.nanmax(c_data))\n            c_data -= self.scale.offset\n            c_data /= self.scale.width\n            c_data = np.floor(c_data) + 0.5\n            c_data /= self.scale.bins\n            c_data = np.clip(c_data, 0, 1)\n        pen = self.palette.getRGB(c_data)\n        brush = np.hstack(\n            [pen, np.full((len(pen), 1), self.alpha_value, dtype=int)])\n        pen *= 100\n        pen //= self.DarkerValue\n\n        # Reuse pens and brushes with the same colors because PyQtGraph then builds\n        # smaller pixmap atlas, which makes the drawing faster\n\n        def reuse(cache, fn, *args):\n            if args not in cache:\n                cache[args] = fn(args)\n            return cache[args]\n\n        def create_pen(col):\n            return _make_pen(QColor(*col), 1.5)\n\n        def create_brush(col):\n            return QBrush(QColor(*col))\n\n        cached_pens = {}\n        pen = [reuse(cached_pens, create_pen, *col) for col in pen.tolist()]\n\n        if subset is not None:\n            brush[:, 3] = 0\n            brush[subset, 3] = 255\n\n        cached_brushes = {}\n        brush = np.array([reuse(cached_brushes, create_brush, *col) for col in brush.tolist()])\n\n        return pen, brush\n\n    def _get_discrete_colors(self, c_data, subset):\n        \"\"\"\n        Return the pens and colors whose color represent an index into\n        a discrete palette. The same color is used for pen and brush,\n        except the former is darker. If the data has a subset, the brush\n        is transparent for points that are not in the subset.\n        \"\"\"\n        n_colors = self.palette.number_of_colors\n        c_data = c_data.copy()\n        c_data[np.isnan(c_data)] = n_colors\n        c_data = c_data.astype(int)\n        colors = np.r_[self.palette.getRGB(np.arange(n_colors)),\n                       [[128, 128, 128]]]\n        pens = np.array(\n            [_make_pen(QColor(*col).darker(self.DarkerValue), 1.5)\n             for col in colors])\n        pen = pens[c_data]\n        alpha = self.alpha_value if subset is None else 255\n        brushes = np.array([\n            [QBrush(QColor(0, 0, 0, 0)),\n             QBrush(QColor(col[0], col[1], col[2], alpha))]\n            for col in colors])\n        brush = brushes[c_data]\n\n        if subset is not None:\n            brush = np.where(subset, brush[:, 1], brush[:, 0])\n        else:\n            brush = brush[:, 1]\n        return pen, brush\n\n    def update_colors(self):\n        \"\"\"\n        Trigger an update of point sizes\n\n        The method calls `self.get_colors`, which in turn calls the widget's\n        `get_color_data` to get the indices in the pallette. `get_colors`\n        returns a list of pens and brushes to which this method uses to\n        update the colors. Finally, the method triggers the update of the\n        legend and the density plot.\n        \"\"\"\n        if self.scatterplot_item is not None:\n            pen_data, brush_data = self.get_colors()\n            self.scatterplot_item.setPen(pen_data, update=False, mask=None)\n            self.scatterplot_item.setBrush(brush_data, mask=None)\n        self.update_legends()\n        self.update_density()\n\n    update_alpha_value = update_colors\n\n    def update_density(self):\n        \"\"\"\n        Remove the existing density plot (if there is one) and replace it\n        with a new one (if enabled).\n\n        The method gets the colors from the pens of the currently plotted\n        points.\n        \"\"\"\n        if self.density_img:\n            self.plot_widget.removeItem(self.density_img)\n            self.density_img = None\n        if self.class_density and self.scatterplot_item is not None:\n            rgb_data = [\n                pen.color().getRgb()[:3] if pen is not None else (255, 255, 255)\n                for pen in self.scatterplot_item.data['pen']]\n            if len(set(rgb_data)) <= 1:\n                return\n            [min_x, max_x], [min_y, max_y] = self.view_box.viewRange()\n            x_data, y_data = self.scatterplot_item.getData()\n            self.density_img = classdensity.class_density_image(\n                min_x, max_x, min_y, max_y, self.resolution,\n                x_data, y_data, rgb_data)\n            self.plot_widget.addItem(self.density_img)\n\n    def update_selection_colors(self):\n        \"\"\"\n        Trigger an update of selection markers\n\n        This update method is usually not called by the widget but by the\n        plot, since it is the plot that handles the selections.\n\n        Like other update methods, it calls the corresponding get method\n        (`get_colors_sel`) which returns a list of pens and brushes.\n        \"\"\"\n        if self.scatterplot_item_sel is None:\n            return\n        pen, brush = self.get_colors_sel()\n        self.scatterplot_item_sel.setPen(pen, update=False, mask=None)\n        self.scatterplot_item_sel.setBrush(brush, mask=None)\n\n    def get_colors_sel(self):\n        \"\"\"\n        Return pens and brushes for selection markers.\n\n        A pen can is set to `Qt.NoPen` if a point is not selected.\n\n        All brushes are completely transparent whites.\n\n        Returns:\n            (tuple): a list of pens and a list of brushes\n        \"\"\"\n        nopen = QPen(Qt.NoPen)\n        if self.selection is None:\n            pen = [nopen] * self.n_shown\n        else:\n            sels = np.max(self.selection)\n            if sels == 1:\n                pen = np.where(\n                    self._filter_visible(self.selection),\n                    _make_pen(QColor(255, 190, 0, 255), SELECTION_WIDTH + 1),\n                    nopen)\n            else:\n                palette = ColorPaletteGenerator(number_of_colors=sels + 1)\n                pen = np.choose(\n                    self._filter_visible(self.selection),\n                    [nopen] + [_make_pen(palette[i], SELECTION_WIDTH + 1)\n                               for i in range(sels)])\n        return pen, [QBrush(QColor(255, 255, 255, 0))] * self.n_shown\n\n    # Labels\n    def get_labels(self):\n        \"\"\"\n        Prepare data for labels for points\n\n        The method returns the results of the widget's `get_label_data`\n\n        Returns:\n            (labels): a sequence of labels\n        \"\"\"\n        return self._filter_visible(self.master.get_label_data())\n\n    def update_labels(self):\n        \"\"\"\n        Trigger an update of labels\n\n        The method calls `get_labels` which in turn calls the widget's\n        `get_label_data`. The obtained labels are shown if the corresponding\n        points are selected or if `label_only_selected` is `false`.\n        \"\"\"\n        for label in self.labels:\n            self.plot_widget.removeItem(label)\n        self.labels = []\n\n        mask = None\n        if self.scatterplot_item is not None:\n            x, y = self.scatterplot_item.getData()\n            mask = self._label_mask(x, y)\n\n        if mask is not None:\n            labels = self.get_labels()\n            if labels is None:\n                mask = None\n\n        self._signal_too_many_labels(\n            mask is not None and mask.sum() > self.MAX_VISIBLE_LABELS)\n        if self._too_many_labels or mask is None or not np.any(mask):\n            return\n\n        black = pg.mkColor(0, 0, 0)\n        labels = labels[mask]\n        x = x[mask]\n        y = y[mask]\n        for label, xp, yp in zip(labels, x, y):\n            ti = TextItem(label, black)\n            ti.setPos(xp, yp)\n            self.plot_widget.addItem(ti)\n            self.labels.append(ti)\n\n    def _signal_too_many_labels(self, too_many):\n        if self._too_many_labels != too_many:\n            self._too_many_labels = too_many\n            self.too_many_labels.emit(too_many)\n\n    def _label_mask(self, x, y):\n        (x0, x1), (y0, y1) = self.view_box.viewRange()\n        mask = np.logical_and(\n            np.logical_and(x >= x0, x <= x1),\n            np.logical_and(y >= y0, y <= y1))\n        if self.label_only_selected:\n            sub_mask = self._filter_visible(self.master.get_subset_mask())\n            if self.selection is None:\n                if sub_mask is None:\n                    return None\n                else:\n                    sel_mask = sub_mask\n            else:\n                sel_mask = self._filter_visible(self.selection) != 0\n                if sub_mask is not None:\n                    sel_mask = np.logical_or(sel_mask, sub_mask)\n            mask = np.logical_and(mask, sel_mask)\n        return mask\n\n    # Shapes\n    def get_shapes(self):\n        \"\"\"\n        Prepare data for shapes of points in the plot\n\n        The method is called by `update_shapes`. It gets the data from\n        the widget's `get_shape_data`, and then calls its `impute_shapes`\n        to impute the missing shape (usually with some default shape).\n\n        Returns:\n            (np.ndarray): an array of symbols (e.g. o, x, + ...)\n        \"\"\"\n        shape_data = self.master.get_shape_data()\n        shape_data = self._filter_visible(shape_data)\n        # Data has to be copied so the imputation can change it in-place\n        # TODO: Try avoiding this when we move imputation to the widget\n        if shape_data is not None:\n            shape_data = np.copy(shape_data)\n        shape_imputer = getattr(\n            self.master, \"impute_shapes\", self.default_impute_shapes)\n        shape_imputer(shape_data, len(self.CurveSymbols) - 1)\n        if isinstance(shape_data, np.ndarray):\n            shape_data = shape_data.astype(int)\n        else:\n            shape_data = np.zeros(self.n_shown, dtype=int)\n        return self.CurveSymbols[shape_data]\n\n    @staticmethod\n    def default_impute_shapes(shape_data, default_symbol):\n        \"\"\"\n        Fallback imputation for shapes.\n\n        Use the default symbol, usually the last symbol in the list.\n\n        Returns:\n            (bool): True if there was any missing data\n        \"\"\"\n        if shape_data is None:\n            return False\n        nans = np.isnan(shape_data)\n        if np.any(nans):\n            shape_data[nans] = default_symbol\n            return True\n        else:\n            return False\n\n    def update_shapes(self):\n        \"\"\"\n        Trigger an update of point symbols\n\n        The method calls `get_shapes` to obtain an array with a symbol\n        for each point and uses it to update the symbols.\n\n        Finally, the method updates the legend.\n        \"\"\"\n        if self.scatterplot_item:\n            shape_data = self.get_shapes()\n            self.scatterplot_item.setSymbol(shape_data)\n        self.update_legends()\n\n    def update_grid_visibility(self):\n        \"\"\"Show or hide the grid\"\"\"\n        self.plot_widget.showGrid(x=self.show_grid, y=self.show_grid)\n\n    def update_legend_visibility(self):\n        \"\"\"\n        Show or hide legends based on whether they are enabled and non-empty\n        \"\"\"\n        self.shape_legend.setVisible(\n            self.show_legend and bool(self.shape_legend.items))\n        self.color_legend.setVisible(\n            self.show_legend and bool(self.color_legend.items))\n\n    def update_legends(self):\n        \"\"\"Update content of legends and their visibility\"\"\"\n        cont_color = self.master.is_continuous_color()\n        shape_labels = self.master.get_shape_labels()\n        color_labels = self.master.get_color_labels()\n        if shape_labels == color_labels and shape_labels is not None:\n            self._update_combined_legend(shape_labels)\n        else:\n            self._update_shape_legend(shape_labels)\n            if cont_color:\n                self._update_continuous_color_legend(color_labels)\n            else:\n                self._update_color_legend(color_labels)\n        self.update_legend_visibility()\n\n    def _update_shape_legend(self, labels):\n        self.shape_legend.clear()\n        if labels is None or self.scatterplot_item is None:\n            return\n        color = QColor(0, 0, 0)\n        color.setAlpha(self.alpha_value)\n        for label, symbol in zip(labels, self.CurveSymbols):\n            self.shape_legend.addItem(\n                ScatterPlotItem(pen=color, brush=color, size=10, symbol=symbol),\n                escape(label))\n\n    def _update_continuous_color_legend(self, label_formatter):\n        self.color_legend.clear()\n        if self.scale is None or self.scatterplot_item is None:\n            return\n        label = PaletteItemSample(self.palette, self.scale, label_formatter)\n        self.color_legend.addItem(label, \"\")\n        self.color_legend.setGeometry(label.boundingRect())\n\n    def _update_color_legend(self, labels):\n        self.color_legend.clear()\n        if labels is None:\n            return\n        self._update_colored_legend(self.color_legend, labels, 'o')\n\n    def _update_combined_legend(self, labels):\n        # update_colored_legend will already clear the shape legend\n        # so we remove colors here\n        use_legend = \\\n            self.shape_legend if self.shape_legend.items else self.color_legend\n        self.color_legend.clear()\n        self.shape_legend.clear()\n        self._update_colored_legend(use_legend, labels, self.CurveSymbols)\n\n    def _update_colored_legend(self, legend, labels, symbols):\n        if self.scatterplot_item is None or not self.palette:\n            return\n        if isinstance(symbols, str):\n            symbols = itertools.repeat(symbols, times=len(labels))\n        for i, (label, symbol) in enumerate(zip(labels, symbols)):\n            color = QColor(*self.palette.getRGB(i))\n            pen = _make_pen(color.darker(self.DarkerValue), 1.5)\n            color.setAlpha(255 if self.subset_is_shown else self.alpha_value)\n            brush = QBrush(color)\n            legend.addItem(\n                ScatterPlotItem(pen=pen, brush=brush, size=10, symbol=symbol),\n                escape(label))\n\n    def zoom_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().RectMode)\n\n    def pan_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().PanMode)\n\n    def select_button_clicked(self):\n        self.plot_widget.getViewBox().setMouseMode(\n            self.plot_widget.getViewBox().RectMode)\n\n    def reset_button_clicked(self):\n        self.plot_widget.getViewBox().autoRange()\n        self.update_labels()\n\n    def select_by_click(self, _, points):\n        if self.scatterplot_item is not None:\n            self.select(points)\n\n    def select_by_rectangle(self, rect):\n        if self.scatterplot_item is not None:\n            x0, x1 = sorted((rect.topLeft().x(), rect.bottomRight().x()))\n            y0, y1 = sorted((rect.topLeft().y(), rect.bottomRight().y()))\n            x, y = self.master.get_coordinates_data()\n            indices = np.flatnonzero(\n                (x0 <= x) & (x <= x1) & (y0 <= y) & (y <= y1))\n            self.select_by_indices(indices.astype(int))\n\n    def unselect_all(self):\n        if self.selection is not None:\n            self.selection = None\n            self.update_selection_colors()\n            if self.label_only_selected:\n                self.update_labels()\n            self.master.selection_changed()\n\n    def select(self, points):\n        # noinspection PyArgumentList\n        if self.scatterplot_item is None:\n            return\n        indices = [p.data() for p in points]\n        self.select_by_indices(indices)\n\n    def select_by_indices(self, indices):\n        if self.selection is None:\n            self.selection = np.zeros(self.n_valid, dtype=np.uint8)\n        keys = QApplication.keyboardModifiers()\n        if keys & Qt.AltModifier:\n            self.selection_remove(indices)\n        elif keys & Qt.ShiftModifier and keys & Qt.ControlModifier:\n            self.selection_append(indices)\n        elif keys & Qt.ShiftModifier:\n            self.selection_new_group(indices)\n        else:\n            self.selection_select(indices)\n\n    def selection_select(self, indices):\n        self.selection = np.zeros(self.n_valid, dtype=np.uint8)\n        self.selection[indices] = 1\n        self._update_after_selection()\n\n    def selection_append(self, indices):\n        self.selection[indices] = np.max(self.selection)\n        self._update_after_selection()\n\n    def selection_new_group(self, indices):\n        self.selection[indices] = np.max(self.selection) + 1\n        self._update_after_selection()\n\n    def selection_remove(self, indices):\n        self.selection[indices] = 0\n        self._update_after_selection()\n\n    def _update_after_selection(self):\n        self._compress_indices()\n        self.update_selection_colors()\n        if self.label_only_selected:\n            self.update_labels()\n        self.master.selection_changed()\n\n    def _compress_indices(self):\n        indices = sorted(set(self.selection) | {0})\n        if len(indices) == max(indices) + 1:\n            return\n        mapping = np.zeros((max(indices) + 1,), dtype=int)\n        for i, ind in enumerate(indices):\n            mapping[ind] = i\n        self.selection = mapping[self.selection]\n\n    def get_selection(self):\n        if self.selection is None:\n            return np.array([], dtype=np.uint8)\n        else:\n            return np.flatnonzero(self.selection)\n\n    def help_event(self, event):\n        \"\"\"\n        Create a `QToolTip` for the point hovered by the mouse\n        \"\"\"\n        if self.scatterplot_item is None:\n            return False\n        act_pos = self.scatterplot_item.mapFromScene(event.scenePos())\n        point_data = [p.data() for p in self.scatterplot_item.pointsAt(act_pos)]\n        text = self.master.get_tooltip(point_data)\n        if text:\n            QToolTip.showText(event.screenPos(), text, widget=self.plot_widget)\n            return True\n        else:\n            return False\n\n\nclass HelpEventDelegate(EventDelegate):\n    def __init__(self, delegate, parent=None):\n        super().__init__(delegate, parent)\n        warnings.warn(\"HelpEventDelegate class has been deprecated since 3.17.\"\n                      \" Use Orange.widgets.visualize.utils.plotutils.\"\n                      \"HelpEventDelegate instead.\", OrangeDeprecationWarning)\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]

**Title:** OWScatterPlotGraph Fails to Display Separate Color Legend When Shape and Color Labels Match

**Description:**
When the shape labels and color labels are identical, the color legend fails to display separately as expected. This issue occurs even when the color and shape data are distinct, leading to a combined legend that hides the color information.

**Example Code:**
```python
master.get_shape_data = lambda: np.arange(10, dtype=float) % 3
master.get_color_data = lambda: 2 * np.arange(10, dtype=float) % 3
master.get_shape_labels = lambda: ["a", "b"]
master.get_color_labels = lambda: ["a", "b"]

graph.update_legends()

# Expected: Both shape_legend and color_legend should be visible
# Actual: color_legend is not visible
```

**Expected Behavior:**
When shape labels and color labels are the same, and the color data differs from the shape data, both the shape legend and the color legend should be displayed separately to accurately represent the distinct attributes.

**Actual Behavior:**
Only the shape legend is displayed, and the color legend remains hidden, making it unclear which colors correspond to which data points.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### Orange/widgets/visualize/owscatterplotgraph.py
import sys
import itertools
import warnings
from xml.sax.saxutils import escape
from math import log10, floor, ceil

import numpy as np
from AnyQt.QtCore import Qt, QRectF, QSize, QTimer, pyqtSignal as Signal, \
    QObject
from AnyQt.QtGui import (
    QStaticText, QColor, QPen, QBrush, QPainterPath, QTransform, QPainter
)
from AnyQt.QtWidgets import (
    QApplication, QToolTip, QGraphicsTextItem, QGraphicsRectItem
)

import pyqtgraph as pg
import pyqtgraph.graphicsItems.ScatterPlotItem
from pyqtgraph.graphicsItems.LegendItem import (
    LegendItem as PgLegendItem, ItemSample
)
from pyqtgraph.graphicsItems.TextItem import TextItem

from Orange.util import OrangeDeprecationWarning
from Orange.widgets import gui
from Orange.widgets.settings import Setting
from Orange.widgets.utils import classdensity
from Orange.widgets.utils.colorpalette import ColorPaletteGenerator
from Orange.widgets.utils.plot import OWPalette
from Orange.widgets.visualize.owscatterplotgraph_obsolete import (
    OWScatterPlotGraph as OWScatterPlotGraphObs
)
from Orange.widgets.visualize.utils.plotutils import (
    HelpEventDelegate as EventDelegate,
    InteractiveViewBox as ViewBox
)


SELECTION_WIDTH = 5
MAX_N_VALID_SIZE_ANIMATE = 1000


class PaletteItemSample(ItemSample):
    """A color strip to insert into legends for discretized continuous values"""

    def __init__(self, palette, scale, label_formatter=None):
        """
        :param palette: palette used for showing continuous values
        :type palette: ContinuousPaletteGenerator
        :param scale: an instance of DiscretizedScale that defines the
                      conversion of values into bins
        :type scale: DiscretizedScale
        """
        super().__init__(None)
        self.palette = palette
        self.scale = scale
        if label_formatter is None:
            label_formatter = "{{:.{}f}}".format(scale.decimals).format
        cuts = [label_formatter(scale.offset + i * scale.width)
                for i in range(scale.bins + 1)]
        self.labels = [QStaticText("{} - {}".format(fr, to))
                       for fr, to in zip(cuts, cuts[1:])]
        for label in self.labels:
            label.prepare()
        self.text_width = max(label.size().width() for label in self.labels)

    def boundingRect(self):
        return QRectF(0, 0, 40 + self.text_width, 20 + self.scale.bins * 15)

    def paint(self, p, *args):
        p.setRenderHint(p.Antialiasing)
        scale = self.scale
        font = p.font()
        font.setPixelSize(11)
        p.setFont(font)
        for i, label in enumerate(self.labels):
            color = QColor(*self.palette.getRGB((i + 0.5) / scale.bins))
            p.setPen(Qt.NoPen)
            p.setBrush(QBrush(color))
            p.drawRect(0, i * 15, 15, 15)
            p.setPen(QPen(Qt.black))
            p.drawStaticText(20, i * 15 + 1, label)


class LegendItem(PgLegendItem):
    def __init__(self, size=None, offset=None, pen=None, brush=None):
        super().__init__(size, offset)

        self.layout.setContentsMargins(5, 5, 5, 5)
        self.layout.setHorizontalSpacing(15)
        self.layout.setColumnAlignment(1, Qt.AlignLeft | Qt.AlignVCenter)

        if pen is None:
            pen = QPen(QColor(196, 197, 193, 200), 1)
            pen.setCosmetic(True)
        self.__pen = pen

        if brush is None:
            brush = QBrush(QColor(232, 232, 232, 100))
        self.__brush = brush

    def restoreAnchor(self, anchors):
        """
        Restore (parent) relative position from stored anchors.

        The restored position is within the parent bounds.
        """
        anchor, parentanchor = anchors
        self.anchor(*bound_anchor_pos(anchor, parentanchor))

    def paint(self, painter, option, widget=None):
        painter.setPen(self.__pen)
        painter.setBrush(self.__brush)
        rect = self.contentsRect()
        painter.drawRoundedRect(rect, 2, 2)

    def addItem(self, item, name):
        super().addItem(item, name)
        # Fix-up the label alignment
        _, label = self.items[-1]
        label.setText(name, justify="left")

    def clear(self):
        """
        Clear all legend items.
        """
        items = list(self.items)
        self.items = []
        for sample, label in items:
            self.layout.removeItem(sample)
            self.layout.removeItem(label)
            sample.hide()
            label.hide()

        self.updateSize()


def bound_anchor_pos(corner, parentpos):
    corner = np.clip(corner, 0, 1)
    parentpos = np.clip(parentpos, 0, 1)

    irx, iry = corner
    prx, pry = parentpos

    if irx > 0.9 and prx < 0.1:
        irx = prx = 0.0
    if iry > 0.9 and pry < 0.1:
        iry = pry = 0.0
    if irx < 0.1 and prx > 0.9:
        irx = prx = 1.0
    if iry < 0.1 and pry > 0.9:
        iry = pry = 1.0
    return (irx, iry), (prx, pry)


class DiscretizedScale:
    """
    Compute suitable bins for continuous value from its minimal and
    maximal value.

    The width of the bin is a power of 10 (including negative powers).
    The minimal value is rounded up and the maximal is rounded down. If this
    gives less than 3 bins, the width is divided by four; if it gives
    less than 6, it is halved.

    .. attribute:: offset
        The start of the first bin.

    .. attribute:: width
        The width of the bins

    .. attribute:: bins
        The number of bins

    .. attribute:: decimals
        The number of decimals used for printing out the boundaries
    """
    def __init__(self, min_v, max_v):
        """
        :param min_v: Minimal value
        :type min_v: float
        :param max_v: Maximal value
        :type max_v: float
        """
        super().__init__()
        dif = max_v - min_v if max_v != min_v else 1
        if np.isnan(dif):
            min_v = 0
            dif = decimals = 1
        else:
            decimals = -floor(log10(dif))
        resolution = 10 ** -decimals
        bins = ceil(dif / resolution)
        if bins < 6:
            decimals += 1
            if bins < 3:
                resolution /= 4
            else:
                resolution /= 2
            bins = ceil(dif / resolution)
        self.offset = resolution * floor(min_v // resolution)
        self.bins = bins
        self.decimals = max(decimals, 0)
        self.width = resolution


class InteractiveViewBox(ViewBox):
    def __init__(self, graph, enable_menu=False):
        super().__init__(graph, enable_menu)
        warnings.warn("InteractiveViewBox class has been deprecated since "
                      "3.17. Use Orange.widgets.visualize.utils.plotutils."
                      "InteractiveViewBox instead.", OrangeDeprecationWarning)


class OWScatterPlotGraph(OWScatterPlotGraphObs):
    def __init__(self, scatter_widget, parent=None, _="None", view_box=InteractiveViewBox):
        super().__init__(scatter_widget, parent=parent, _=_, view_box=view_box)
        warnings.warn("OWScatterPlotGraph class has been deprecated since "
                      "3.17. Use OWScatterPlotBase instead.",
                      OrangeDeprecationWarning)


class ScatterPlotItem(pg.ScatterPlotItem):
    """PyQtGraph's ScatterPlotItem calls updateSpots at any change of sizes/colors/symbols,
    which then rebuilds the stored pixmaps for each symbol. Because Orange calls
    set* function in succession, we postpone updateSpots() to paint()."""

    _update_spots_in_paint = False

    def updateSpots(self, dataSet=None):  # pylint: disable=unused-argument
        self._update_spots_in_paint = True
        self.update()

    def paint(self, painter, option, widget=None):
        if self._update_spots_in_paint:
            self._update_spots_in_paint = False
            super().updateSpots()
        painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
        super().paint(painter, option, widget)


def _define_symbols():
    """
    Add symbol ? to ScatterPlotItemSymbols,
    reflect the triangle to point upwards
    """
    symbols = pyqtgraph.graphicsItems.ScatterPlotItem.Symbols
    path = QPainterPath()
    path.addEllipse(QRectF(-0.35, -0.35, 0.7, 0.7))
    path.moveTo(-0.5, 0.5)
    path.lineTo(0.5, -0.5)
    path.moveTo(-0.5, -0.5)
    path.lineTo(0.5, 0.5)
    symbols["?"] = path

    tr = QTransform()
    tr.rotate(180)
    symbols['t'] = tr.map(symbols['t'])


_define_symbols()


def _make_pen(color, width):
    p = QPen(color, width)
    p.setCosmetic(True)
    return p


class OWScatterPlotBase(gui.OWComponent, QObject):
    """
    Provide a graph component for widgets that show any kind of point plot

    The component plots a set of points with given coordinates, shapes,
    sizes and colors. Its function is similar to that of a *view*, whereas
    the widget represents a *model* and a *controler*.

    The model (widget) needs to provide methods:

    - `get_coordinates_data`, `get_size_data`, `get_color_data`,
      `get_shape_data`, `get_label_data`, which return a 1d array (or two
      arrays, for `get_coordinates_data`) of `dtype` `float64`, except for
      `get_label_data`, which returns formatted labels;
    - `get_shape_labels` returns a list of strings for shape legend
    - `get_color_labels` returns strings for color legend, or a function for
       formatting numbers if the legend is continuous, or None for default
       formatting
    - `get_tooltip`, which gives a tooltip for a single data point
    - (optional) `impute_sizes`, `impute_shapes` get final coordinates and
      shapes, and replace nans;
    - `get_subset_mask` returns a bool array indicating whether a
      data point is in the subset or not (e.g. in the 'Data Subset' signal
      in the Scatter plot and similar widgets);
    - `get_palette` returns a palette appropriate for visualizing the
      current color data;
    - `is_continuous_color` decides the type of the color legend;

    The widget (in a role of controller) must also provide methods
    - `selection_changed`

    If `get_coordinates_data` returns `(None, None)`, the plot is cleared. If
    `get_size_data`, `get_color_data` or `get_shape_data` return `None`,
    all points will have the same size, color or shape, respectively.
    If `get_label_data` returns `None`, there are no labels.

    The view (this compomnent) provides methods `update_coordinates`,
    `update_sizes`, `update_colors`, `update_shapes` and `update_labels`
    that the widget (in a role of a controler) should call when any of
    these properties are changed. If the widget calls, for instance, the
    plot's `update_colors`, the plot will react by calling the widget's
    `get_color_data` as well as the widget's methods needed to construct the
    legend.

    The view also provides a method `reset_graph`, which should be called only
    when
    - the widget gets entirely new data
    - the number of points may have changed, for instance when selecting
    a different attribute for x or y in the scatter plot, where the points
    with missing x or y coordinates are hidden.

    Every `update_something` calls the plot's `get_something`, which
    calls the model's `get_something_data`, then it transforms this data
    into whatever is needed (colors, shapes, scaled sizes) and changes the
    plot. For the simplest example, here is `update_shapes`:

    ```
        def update_shapes(self):
            if self.scatterplot_item:
                shape_data = self.get_shapes()
                self.scatterplot_item.setSymbol(shape_data)
            self.update_legends()

        def get_shapes(self):
            shape_data = self.master.get_shape_data()
            shape_data = self.master.impute_shapes(
                shape_data, len(self.CurveSymbols) - 1)
            return self.CurveSymbols[shape_data]
    ```

    On the widget's side, `get_something_data` is essentially just:

    ```
        def get_size_data(self):
            return self.get_column(self.attr_size)
    ```

    where `get_column` retrieves a column while also filtering out the
    points with missing x and y and so forth. (Here we present the simplest
    two cases, "shapes" for the view and "sizes" for the model. The colors
    for the view are more complicated since they deal with discrete and
    continuous palettes, and the shapes for the view merge infrequent shapes.)

    The plot can also show just a random sample of the data. The sample size is
    set by `set_sample_size`, and the rest is taken care by the plot: the
    widget keeps providing the data for all points, selection indices refer
    to the entire set etc. Internally, sampling happens as early as possible
    (in methods `get_<something>`).
    """
    too_many_labels = Signal(bool)
    begin_resizing = Signal()
    step_resizing = Signal()
    end_resizing = Signal()

    label_only_selected = Setting(False)
    point_width = Setting(10)
    alpha_value = Setting(128)
    show_grid = Setting(False)
    show_legend = Setting(True)
    class_density = Setting(False)
    jitter_size = Setting(0)

    resolution = 256

    CurveSymbols = np.array("o x t + d star ?".split())
    MinShapeSize = 6
    DarkerValue = 120
    UnknownColor = (168, 50, 168)

    COLOR_NOT_SUBSET = (128, 128, 128, 0)
    COLOR_SUBSET = (128, 128, 128, 255)
    COLOR_DEFAULT = (128, 128, 128, 0)

    MAX_VISIBLE_LABELS = 500

    def __init__(self, scatter_widget, parent=None, view_box=ViewBox):
        QObject.__init__(self)
        gui.OWComponent.__init__(self, scatter_widget)

        self.subset_is_shown = False

        self.view_box = view_box(self)
        self.plot_widget = pg.PlotWidget(viewBox=self.view_box, parent=parent,
                                         background="w")
        self.plot_widget.hideAxis("left")
        self.plot_widget.hideAxis("bottom")
        self.plot_widget.getPlotItem().buttonsHidden = True
        self.plot_widget.setAntialiasing(True)
        self.plot_widget.sizeHint = lambda: QSize(500, 500)

        self.density_img = None
        self.scatterplot_item = None
        self.scatterplot_item_sel = None
        self.labels = []

        self.master = scatter_widget
        self._create_drag_tooltip(self.plot_widget.scene())

        self.selection = None  # np.ndarray

        self.n_valid = 0
        self.n_shown = 0
        self.sample_size = None
        self.sample_indices = None

        self.palette = None

        self.shape_legend = self._create_legend(((1, 0), (1, 0)))
        self.color_legend = self._create_legend(((1, 1), (1, 1)))
        self.update_legend_visibility()

        self.scale = None  # DiscretizedScale
        self._too_many_labels = False

        # self.setMouseTracking(True)
        # self.grabGesture(QPinchGesture)
        # self.grabGesture(QPanGesture)

        self.update_grid_visibility()

        self._tooltip_delegate = EventDelegate(self.help_event)
        self.plot_widget.scene().installEventFilter(self._tooltip_delegate)
        self.view_box.sigTransformChanged.connect(self.update_density)
        self.view_box.sigRangeChangedManually.connect(self.update_labels)

        self.timer = None

    def _create_legend(self, anchor):
        legend = LegendItem()
        legend.setParentItem(self.plot_widget.getViewBox())
        legend.restoreAnchor(anchor)
        return legend

    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()

        scene.drag_tooltip = scene.createItemGroup([rect, text])
        scene.drag_tooltip.hide()

    def update_tooltip(self, modifiers=Qt.NoModifier):
        modifiers &= Qt.ShiftModifier + Qt.ControlModifier + Qt.AltModifier
        text = self.tiptexts.get(int(modifiers), self.tiptexts[0])
        self.tip_textitem.setHtml(text + self._get_jittering_tooltip())

    def _get_jittering_tooltip(self):
        warn_jittered = ""
        if self.jitter_size:
            warn_jittered = \
                '<br/><br/>' \
                '<span style="background-color: red; color: white; ' \
                'font-weight: 500;">' \
                '&nbsp;Warning: Selection is applied to unjittered data&nbsp;' \
                '</span>'
        return warn_jittered

    def update_jittering(self):
        self.update_tooltip()
        x, y = self.get_coordinates()
        if x is None or not len(x) or self.scatterplot_item is None:
            return
        self._update_plot_coordinates(self.scatterplot_item, x, y)
        self._update_plot_coordinates(self.scatterplot_item_sel, x, y)
        self.update_labels()

    # TODO: Rename to remove_plot_items
    def clear(self):
        """
        Remove all graphical elements from the plot

        Calls the pyqtgraph's plot widget's clear, sets all handles to `None`,
        removes labels and selections.

        This method should generally not be called by the widget. If the data
        is gone (*e.g.* upon receiving `None` as an input data signal), this
        should be handler by calling `reset_graph`, which will in turn call
        `clear`.

        Derived classes should override this method if they add more graphical
        elements. For instance, the regression line in the scatterplot adds
        `self.reg_line_item = None` (the line in the plot is already removed
        in this method).
        """
        self.plot_widget.clear()

        self.density_img = None
        if self.timer is not None and self.timer.isActive():
            self.timer.stop()
            self.timer = None
        self.scatterplot_item = None
        self.scatterplot_item_sel = None
        self.labels = []
        self._signal_too_many_labels(False)
        self.view_box.init_history()
        self.view_box.tag_history()

    # TODO: I hate `keep_something` and `reset_something` arguments
    # __keep_selection is used exclusively be set_sample size which would
    # otherwise just repeat the code from reset_graph except for resetting
    # the selection. I'm uncomfortable with this; we may prefer to have a
    # method _reset_graph which does everything except resetting the selection,
    # and reset_graph would call it.
    def reset_graph(self, __keep_selection=False):
        """
        Reset the graph to new data (or no data)

        The method must be called when the plot receives new data, in
        particular when the number of points change. If only their properties
        - like coordinates or shapes - change, an update method
        (`update_coordinates`, `update_shapes`...) should be called instead.

        The method must also be called when the data is gone.

        The method calls `clear`, followed by calls of all update methods.

        NB. Argument `__keep_selection` is for internal use only
        """
        self.clear()
        if not __keep_selection:
            self.selection = None
        self.sample_indices = None
        self.update_coordinates()
        self.update_point_props()

    def set_sample_size(self, sample_size):
        """
        Set the sample size

        Args:
            sample_size (int or None): sample size or `None` to show all points
        """
        if self.sample_size != sample_size:
            self.sample_size = sample_size
            self.reset_graph(True)

    def update_point_props(self):
        """
        Update the sizes, colors, shapes and labels

        The method calls the appropriate update methods for individual
        properties.
        """
        self.update_sizes()
        self.update_colors()
        self.update_selection_colors()
        self.update_shapes()
        self.update_labels()

    # Coordinates
    # TODO: It could be nice if this method was run on entire data, not just
    # a sample. For this, however, it would need to either be called from
    # `get_coordinates` before sampling (very ugly) or call
    # `self.master.get_coordinates_data` (beyond ugly) or the widget would
    # have to store the ranges of unsampled data (ugly).
    # Maybe we leave it as it is.
    def _reset_view(self, x_data, y_data):
        """
        Set the range of the view box

        Args:
            x_data (np.ndarray): x coordinates
            y_data (np.ndarray) y coordinates
        """
        min_x, max_x = np.min(x_data), np.max(x_data)
        min_y, max_y = np.min(y_data), np.max(y_data)
        self.view_box.setRange(
            QRectF(min_x, min_y, max_x - min_x or 1, max_y - min_y or 1),
            padding=0.025)

    def _filter_visible(self, data):
        """Return the sample from the data using the stored sample_indices"""
        if data is None or self.sample_indices is None:
            return data
        else:
            return np.asarray(data[self.sample_indices])

    def get_coordinates(self):
        """
        Prepare coordinates of the points in the plot

        The method is called by `update_coordinates`. It gets the coordinates
        from the widget, jitters them and return them.

        The methods also initializes the sample indices if neededd and stores
        the original and sampled number of points.

        Returns:
            (tuple): a pair of numpy arrays containing (sampled) coordinates,
                or `(None, None)`.
        """
        x, y = self.master.get_coordinates_data()
        if x is None:
            self.n_valid = self.n_shown = 0
            return None, None
        self.n_valid = len(x)
        self._create_sample()
        x = self._filter_visible(x)
        y = self._filter_visible(y)
        # Jittering after sampling is OK if widgets do not change the sample
        # semi-permanently, e.g. take a sample for the duration of some
        # animation. If the sample size changes dynamically (like by adding
        # a "sample size" slider), points would move around when the sample
        # size changes. To prevent this, jittering should be done before
        # sampling (i.e. two lines earlier). This would slow it down somewhat.
        x, y = self.jitter_coordinates(x, y)
        return x, y

    def _create_sample(self):
        """
        Create a random sample if the data is larger than the set sample size
        """
        self.n_shown = min(self.n_valid, self.sample_size or self.n_valid)
        if self.sample_size is not None \
                and self.sample_indices is None \
                and self.n_valid != self.n_shown:
            random = np.random.RandomState(seed=0)
            self.sample_indices = random.choice(
                self.n_valid, self.n_shown, replace=False)
            # TODO: Is this really needed?
            np.sort(self.sample_indices)

    def jitter_coordinates(self, x, y):
        """
        Display coordinates to random positions within ellipses with
        radiuses of `self.jittter_size` percents of spans
        """
        if self.jitter_size == 0:
            return x, y
        return self._jitter_data(x, y)

    def _jitter_data(self, x, y, span_x=None, span_y=None):
        if span_x is None:
            span_x = np.max(x) - np.min(x)
        if span_y is None:
            span_y = np.max(y) - np.min(y)
        random = np.random.RandomState(seed=0)
        rs = random.uniform(0, 1, len(x))
        phis = random.uniform(0, 2 * np.pi, len(x))
        magnitude = self.jitter_size / 100
        return (x + magnitude * span_x * rs * np.cos(phis),
                y + magnitude * span_y * rs * np.sin(phis))

    def _update_plot_coordinates(self, plot, x, y):
        """
        Change the coordinates of points while keeping other properites

        Note. Pyqtgraph does not offer a method for this: setting coordinates
        invalidates other data. We therefore retrieve the data to set it
        together with the coordinates. Pyqtgraph also does not offer a
        (documented) method for retrieving the data, yet using
        `plot.data[prop]` looks reasonably safe. The alternative, calling
        update for every property would essentially reset the graph, which
        can be time consuming.
        """
        data = dict(x=x, y=y)
        for prop in ('pen', 'brush', 'size', 'symbol', 'data',
                     'sourceRect', 'targetRect'):
            data[prop] = plot.data[prop]
        plot.setData(**data)

    def update_coordinates(self):
        """
        Trigger the update of coordinates while keeping other features intact.

        The method gets the coordinates by calling `self.get_coordinates`,
        which in turn calls the widget's `get_coordinate_data`. The number of
        coordinate pairs returned by the latter must match the current number
        of points. If this is not the case, the widget should trigger
        the complete update by calling `reset_graph` instead of this method.
        """
        x, y = self.get_coordinates()
        if x is None or not len(x):
            return
        if self.scatterplot_item is None:
            if self.sample_indices is None:
                indices = np.arange(self.n_valid)
            else:
                indices = self.sample_indices
            kwargs = dict(x=x, y=y, data=indices)
            self.scatterplot_item = ScatterPlotItem(**kwargs)
            self.scatterplot_item.sigClicked.connect(self.select_by_click)
            self.scatterplot_item_sel = ScatterPlotItem(**kwargs)
            self.plot_widget.addItem(self.scatterplot_item_sel)
            self.plot_widget.addItem(self.scatterplot_item)
        else:
            self._update_plot_coordinates(self.scatterplot_item, x, y)
            self._update_plot_coordinates(self.scatterplot_item_sel, x, y)
            self.update_labels()

        self.update_density()  # Todo: doesn't work: try MDS with density on
        self._reset_view(x, y)

    # Sizes
    def get_sizes(self):
        """
        Prepare data for sizes of points in the plot

        The method is called by `update_sizes`. It gets the sizes
        from the widget and performs the necessary scaling and sizing.
        The output is rounded to half a pixel for faster drawing.

        Returns:
            (np.ndarray): sizes
        """
        size_column = self.master.get_size_data()
        if size_column is None:
            return np.full((self.n_shown,),
                           self.MinShapeSize + (5 + self.point_width) * 0.5)
        size_column = self._filter_visible(size_column)
        size_column = size_column.copy()
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", category=RuntimeWarning)
            size_column -= np.nanmin(size_column)
            mx = np.nanmax(size_column)
        if mx > 0:
            size_column /= mx
        else:
            size_column[:] = 0.5

        sizes = self.MinShapeSize + (5 + self.point_width) * size_column
        # round sizes to half pixel for smaller pyqtgraph's symbol pixmap atlas
        sizes = (sizes * 2).round() / 2
        return sizes

    def update_sizes(self):
        """
        Trigger an update of point sizes

        The method calls `self.get_sizes`, which in turn calls the widget's
        `get_size_data`. The result are properly scaled and then passed
        back to widget for imputing (`master.impute_sizes`).
        """
        if self.scatterplot_item:
            size_data = self.get_sizes()
            size_imputer = getattr(
                self.master, "impute_sizes", self.default_impute_sizes)
            size_imputer(size_data)

            if self.timer is not None and self.timer.isActive():
                self.timer.stop()
                self.timer = None

            current_size_data = self.scatterplot_item.data["size"].copy()
            diff = size_data - current_size_data
            widget = self

            class Timeout:
                # 0.5 - np.cos(np.arange(0.17, 1, 0.17) * np.pi) / 2
                factors = [0.07, 0.26, 0.52, 0.77, 0.95, 1]

                def __init__(self):
                    self._counter = 0

                def __call__(self):
                    factor = self.factors[self._counter]
                    self._counter += 1
                    size = current_size_data + diff * factor
                    if len(self.factors) == self._counter:
                        widget.timer.stop()
                        widget.timer = None
                        size = size_data
                    widget.scatterplot_item.setSize(size)
                    widget.scatterplot_item_sel.setSize(size + SELECTION_WIDTH)
                    if widget.timer is None:
                        widget.end_resizing.emit()
                    else:
                        widget.step_resizing.emit()

            if self.n_valid <= MAX_N_VALID_SIZE_ANIMATE and \
                    np.all(current_size_data > 0) and np.any(diff != 0):
                # If encountered any strange behaviour when updating sizes,
                # implement it with threads
                self.begin_resizing.emit()
                self.timer = QTimer(self.scatterplot_item, interval=50)
                self.timer.timeout.connect(Timeout())
                self.timer.start()
            else:
                self.begin_resizing.emit()
                self.scatterplot_item.setSize(size_data)
                self.scatterplot_item_sel.setSize(size_data + SELECTION_WIDTH)
                self.end_resizing.emit()

    update_point_size = update_sizes  # backward compatibility (needed?!)
    update_size = update_sizes

    @classmethod
    def default_impute_sizes(cls, size_data):
        """
        Fallback imputation for sizes.

        Set the size to two pixels smaller than the minimal size

        Returns:
            (bool): True if there was any missing data
        """
        nans = np.isnan(size_data)
        if np.any(nans):
            size_data[nans] = cls.MinShapeSize - 2
            return True
        else:
            return False

    # Colors
    def get_colors(self):
        """
        Prepare data for colors of the points in the plot

        The method is called by `update_colors`. It gets the colors and the
        indices of the data subset from the widget (`get_color_data`,
        `get_subset_mask`), and constructs lists of pens and brushes for
        each data point.

        The method uses different palettes for discrete and continuous data,
        as determined by calling the widget's method `is_continuous_color`.

        If also marks the points that are in the subset as defined by, for
        instance the 'Data Subset' signal in the Scatter plot and similar
        widgets. (Do not confuse this with *selected points*, which are
        marked by circles around the points, which are colored by groups
        and thus independent of this method.)

        Returns:
            (tuple): a list of pens and list of brushes
        """
        self.palette = self.master.get_palette()
        c_data = self.master.get_color_data()
        c_data = self._filter_visible(c_data)
        subset = self.master.get_subset_mask()
        subset = self._filter_visible(subset)
        self.subset_is_shown = subset is not None
        if c_data is None:  # same color
            return self._get_same_colors(subset)
        elif self.master.is_continuous_color():
            return self._get_continuous_colors(c_data, subset)
        else:
            return self._get_discrete_colors(c_data, subset)

    def _get_same_colors(self, subset):
        """
        Return the same pen for all points while the brush color depends
        upon whether the point is in the subset or not

        Args:
            subset (np.ndarray): a bool array indicating whether a data point
                is in the subset or not (e.g. in the 'Data Subset' signal
                in the Scatter plot and similar widgets);

        Returns:
            (tuple): a list of pens and list of brushes
        """
        color = self.plot_widget.palette().color(OWPalette.Data)
        pen = [_make_pen(color, 1.5)] * self.n_shown  # use a single QPen instance
        if subset is not None:
            brush = np.where(
                subset,
                *(QBrush(QColor(*col))
                  for col in (self.COLOR_SUBSET, self.COLOR_NOT_SUBSET)))
        else:
            color = QColor(*self.COLOR_DEFAULT)
            color.setAlpha(self.alpha_value)
            brush = [QBrush(color)] * self.n_shown  # use a single QBrush instance
        return pen, brush

    def _get_continuous_colors(self, c_data, subset):
        """
        Return the pens and colors whose color represent an index into
        a continuous palette. The same color is used for pen and brush,
        except the former is darker. If the data has a subset, the brush
        is transparent for points that are not in the subset.
        """
        if np.isnan(c_data).all():
            self.scale = None
        else:
            self.scale = DiscretizedScale(np.nanmin(c_data), np.nanmax(c_data))
            c_data -= self.scale.offset
            c_data /= self.scale.width
            c_data = np.floor(c_data) + 0.5
            c_data /= self.scale.bins
            c_data = np.clip(c_data, 0, 1)
        pen = self.palette.getRGB(c_data)
        brush = np.hstack(
            [pen, np.full((len(pen), 1), self.alpha_value, dtype=int)])
        pen *= 100
        pen //= self.DarkerValue

        # Reuse pens and brushes with the same colors because PyQtGraph then builds
        # smaller pixmap atlas, which makes the drawing faster

        def reuse(cache, fn, *args):
            if args not in cache:
                cache[args] = fn(args)
            return cache[args]

        def create_pen(col):
            return _make_pen(QColor(*col), 1.5)

        def create_brush(col):
            return QBrush(QColor(*col))

        cached_pens = {}
        pen = [reuse(cached_pens, create_pen, *col) for col in pen.tolist()]

        if subset is not None:
            brush[:, 3] = 0
            brush[subset, 3] = 255

        cached_brushes = {}
        brush = np.array([reuse(cached_brushes, create_brush, *col) for col in brush.tolist()])

        return pen, brush

    def _get_discrete_colors(self, c_data, subset):
        """
        Return the pens and colors whose color represent an index into
        a discrete palette. The same color is used for pen and brush,
        except the former is darker. If the data has a subset, the brush
        is transparent for points that are not in the subset.
        """
        n_colors = self.palette.number_of_colors
        c_data = c_data.copy()
        c_data[np.isnan(c_data)] = n_colors
        c_data = c_data.astype(int)
        colors = np.r_[self.palette.getRGB(np.arange(n_colors)),
                       [[128, 128, 128]]]
        pens = np.array(
            [_make_pen(QColor(*col).darker(self.DarkerValue), 1.5)
             for col in colors])
        pen = pens[c_data]
        alpha = self.alpha_value if subset is None else 255
        brushes = np.array([
            [QBrush(QColor(0, 0, 0, 0)),
             QBrush(QColor(col[0], col[1], col[2], alpha))]
            for col in colors])
        brush = brushes[c_data]

        if subset is not None:
            brush = np.where(subset, brush[:, 1], brush[:, 0])
        else:
            brush = brush[:, 1]
        return pen, brush

    def update_colors(self):
        """
        Trigger an update of point sizes

        The method calls `self.get_colors`, which in turn calls the widget's
        `get_color_data` to get the indices in the pallette. `get_colors`
        returns a list of pens and brushes to which this method uses to
        update the colors. Finally, the method triggers the update of the
        legend and the density plot.
        """
        if self.scatterplot_item is not None:
            pen_data, brush_data = self.get_colors()
            self.scatterplot_item.setPen(pen_data, update=False, mask=None)
            self.scatterplot_item.setBrush(brush_data, mask=None)
        self.update_legends()
        self.update_density()

    update_alpha_value = update_colors

    def update_density(self):
        """
        Remove the existing density plot (if there is one) and replace it
        with a new one (if enabled).

        The method gets the colors from the pens of the currently plotted
        points.
        """
        if self.density_img:
            self.plot_widget.removeItem(self.density_img)
            self.density_img = None
        if self.class_density and self.scatterplot_item is not None:
            rgb_data = [
                pen.color().getRgb()[:3] if pen is not None else (255, 255, 255)
                for pen in self.scatterplot_item.data['pen']]
            if len(set(rgb_data)) <= 1:
                return
            [min_x, max_x], [min_y, max_y] = self.view_box.viewRange()
            x_data, y_data = self.scatterplot_item.getData()
            self.density_img = classdensity.class_density_image(
                min_x, max_x, min_y, max_y, self.resolution,
                x_data, y_data, rgb_data)
            self.plot_widget.addItem(self.density_img)

    def update_selection_colors(self):
        """
        Trigger an update of selection markers

        This update method is usually not called by the widget but by the
        plot, since it is the plot that handles the selections.

        Like other update methods, it calls the corresponding get method
        (`get_colors_sel`) which returns a list of pens and brushes.
        """
        if self.scatterplot_item_sel is None:
            return
        pen, brush = self.get_colors_sel()
        self.scatterplot_item_sel.setPen(pen, update=False, mask=None)
        self.scatterplot_item_sel.setBrush(brush, mask=None)

    def get_colors_sel(self):
        """
        Return pens and brushes for selection markers.

        A pen can is set to `Qt.NoPen` if a point is not selected.

        All brushes are completely transparent whites.

        Returns:
            (tuple): a list of pens and a list of brushes
        """
        nopen = QPen(Qt.NoPen)
        if self.selection is None:
            pen = [nopen] * self.n_shown
        else:
            sels = np.max(self.selection)
            if sels == 1:
                pen = np.where(
                    self._filter_visible(self.selection),
                    _make_pen(QColor(255, 190, 0, 255), SELECTION_WIDTH + 1),
                    nopen)
            else:
                palette = ColorPaletteGenerator(number_of_colors=sels + 1)
                pen = np.choose(
                    self._filter_visible(self.selection),
                    [nopen] + [_make_pen(palette[i], SELECTION_WIDTH + 1)
                               for i in range(sels)])
        return pen, [QBrush(QColor(255, 255, 255, 0))] * self.n_shown

    # Labels
    def get_labels(self):
        """
        Prepare data for labels for points

        The method returns the results of the widget's `get_label_data`

        Returns:
            (labels): a sequence of labels
        """
        return self._filter_visible(self.master.get_label_data())

    def update_labels(self):
        """
        Trigger an update of labels

        The method calls `get_labels` which in turn calls the widget's
        `get_label_data`. The obtained labels are shown if the corresponding
        points are selected or if `label_only_selected` is `false`.
        """
        for label in self.labels:
            self.plot_widget.removeItem(label)
        self.labels = []

        mask = None
        if self.scatterplot_item is not None:
            x, y = self.scatterplot_item.getData()
            mask = self._label_mask(x, y)

        if mask is not None:
            labels = self.get_labels()
            if labels is None:
                mask = None

        self._signal_too_many_labels(
            mask is not None and mask.sum() > self.MAX_VISIBLE_LABELS)
        if self._too_many_labels or mask is None or not np.any(mask):
            return

        black = pg.mkColor(0, 0, 0)
        labels = labels[mask]
        x = x[mask]
        y = y[mask]
        for label, xp, yp in zip(labels, x, y):
            ti = TextItem(label, black)
            ti.setPos(xp, yp)
            self.plot_widget.addItem(ti)
            self.labels.append(ti)

    def _signal_too_many_labels(self, too_many):
        if self._too_many_labels != too_many:
            self._too_many_labels = too_many
            self.too_many_labels.emit(too_many)

    def _label_mask(self, x, y):
        (x0, x1), (y0, y1) = self.view_box.viewRange()
        mask = np.logical_and(
            np.logical_and(x >= x0, x <= x1),
            np.logical_and(y >= y0, y <= y1))
        if self.label_only_selected:
            sub_mask = self._filter_visible(self.master.get_subset_mask())
            if self.selection is None:
                if sub_mask is None:
                    return None
                else:
                    sel_mask = sub_mask
            else:
                sel_mask = self._filter_visible(self.selection) != 0
                if sub_mask is not None:
                    sel_mask = np.logical_or(sel_mask, sub_mask)
            mask = np.logical_and(mask, sel_mask)
        return mask

    # Shapes
    def get_shapes(self):
        """
        Prepare data for shapes of points in the plot

        The method is called by `update_shapes`. It gets the data from
        the widget's `get_shape_data`, and then calls its `impute_shapes`
        to impute the missing shape (usually with some default shape).

        Returns:
            (np.ndarray): an array of symbols (e.g. o, x, + ...)
        """
        shape_data = self.master.get_shape_data()
        shape_data = self._filter_visible(shape_data)
        # Data has to be copied so the imputation can change it in-place
        # TODO: Try avoiding this when we move imputation to the widget
        if shape_data is not None:
            shape_data = np.copy(shape_data)
        shape_imputer = getattr(
            self.master, "impute_shapes", self.default_impute_shapes)
        shape_imputer(shape_data, len(self.CurveSymbols) - 1)
        if isinstance(shape_data, np.ndarray):
            shape_data = shape_data.astype(int)
        else:
            shape_data = np.zeros(self.n_shown, dtype=int)
        return self.CurveSymbols[shape_data]

    @staticmethod
    def default_impute_shapes(shape_data, default_symbol):
        """
        Fallback imputation for shapes.

        Use the default symbol, usually the last symbol in the list.

        Returns:
            (bool): True if there was any missing data
        """
        if shape_data is None:
            return False
        nans = np.isnan(shape_data)
        if np.any(nans):
            shape_data[nans] = default_symbol
            return True
        else:
            return False

    def update_shapes(self):
        """
        Trigger an update of point symbols

        The method calls `get_shapes` to obtain an array with a symbol
        for each point and uses it to update the symbols.

        Finally, the method updates the legend.
        """
        if self.scatterplot_item:
            shape_data = self.get_shapes()
            self.scatterplot_item.setSymbol(shape_data)
        self.update_legends()

    def update_grid_visibility(self):
        """Show or hide the grid"""
        self.plot_widget.showGrid(x=self.show_grid, y=self.show_grid)

    def update_legend_visibility(self):
        """
        Show or hide legends based on whether they are enabled and non-empty
        """
        self.shape_legend.setVisible(
            self.show_legend and bool(self.shape_legend.items))
        self.color_legend.setVisible(
            self.show_legend and bool(self.color_legend.items))

    def update_legends(self):
        """Update content of legends and their visibility"""
        cont_color = self.master.is_continuous_color()
        shape_labels = self.master.get_shape_labels()
        color_labels = self.master.get_color_labels()
        if shape_labels == color_labels and shape_labels is not None:
            self._update_combined_legend(shape_labels)
        else:
            self._update_shape_legend(shape_labels)
            if cont_color:
                self._update_continuous_color_legend(color_labels)
            else:
                self._update_color_legend(color_labels)
        self.update_legend_visibility()

    def _update_shape_legend(self, labels):
        self.shape_legend.clear()
        if labels is None or self.scatterplot_item is None:
            return
        color = QColor(0, 0, 0)
        color.setAlpha(self.alpha_value)
        for label, symbol in zip(labels, self.CurveSymbols):
            self.shape_legend.addItem(
                ScatterPlotItem(pen=color, brush=color, size=10, symbol=symbol),
                escape(label))

    def _update_continuous_color_legend(self, label_formatter):
        self.color_legend.clear()
        if self.scale is None or self.scatterplot_item is None:
            return
        label = PaletteItemSample(self.palette, self.scale, label_formatter)
        self.color_legend.addItem(label, "")
        self.color_legend.setGeometry(label.boundingRect())

    def _update_color_legend(self, labels):
        self.color_legend.clear()
        if labels is None:
            return
        self._update_colored_legend(self.color_legend, labels, 'o')

    def _update_combined_legend(self, labels):
        # update_colored_legend will already clear the shape legend
        # so we remove colors here
        use_legend = \
            self.shape_legend if self.shape_legend.items else self.color_legend
        self.color_legend.clear()
        self.shape_legend.clear()
        self._update_colored_legend(use_legend, labels, self.CurveSymbols)

    def _update_colored_legend(self, legend, labels, symbols):
        if self.scatterplot_item is None or not self.palette:
            return
        if isinstance(symbols, str):
            symbols = itertools.repeat(symbols, times=len(labels))
        for i, (label, symbol) in enumerate(zip(labels, symbols)):
            color = QColor(*self.palette.getRGB(i))
            pen = _make_pen(color.darker(self.DarkerValue), 1.5)
            color.setAlpha(255 if self.subset_is_shown else self.alpha_value)
            brush = QBrush(color)
            legend.addItem(
                ScatterPlotItem(pen=pen, brush=brush, size=10, symbol=symbol),
                escape(label))

    def zoom_button_clicked(self):
        self.plot_widget.getViewBox().setMouseMode(
            self.plot_widget.getViewBox().RectMode)

    def pan_button_clicked(self):
        self.plot_widget.getViewBox().setMouseMode(
            self.plot_widget.getViewBox().PanMode)

    def select_button_clicked(self):
        self.plot_widget.getViewBox().setMouseMode(
            self.plot_widget.getViewBox().RectMode)

    def reset_button_clicked(self):
        self.plot_widget.getViewBox().autoRange()
        self.update_labels()

    def select_by_click(self, _, points):
        if self.scatterplot_item is not None:
            self.select(points)

    def select_by_rectangle(self, rect):
        if self.scatterplot_item is not None:
            x0, x1 = sorted((rect.topLeft().x(), rect.bottomRight().x()))
            y0, y1 = sorted((rect.topLeft().y(), rect.bottomRight().y()))
            x, y = self.master.get_coordinates_data()
            indices = np.flatnonzero(
                (x0 <= x) & (x <= x1) & (y0 <= y) & (y <= y1))
            self.select_by_indices(indices.astype(int))

    def unselect_all(self):
        if self.selection is not None:
            self.selection = None
            self.update_selection_colors()
            if self.label_only_selected:
                self.update_labels()
            self.master.selection_changed()

    def select(self, points):
        # noinspection PyArgumentList
        if self.scatterplot_item is None:
            return
        indices = [p.data() for p in points]
        self.select_by_indices(indices)

    def select_by_indices(self, indices):
        if self.selection is None:
            self.selection = np.zeros(self.n_valid, dtype=np.uint8)
        keys = QApplication.keyboardModifiers()
        if keys & Qt.AltModifier:
            self.selection_remove(indices)
        elif keys & Qt.ShiftModifier and keys & Qt.ControlModifier:
            self.selection_append(indices)
        elif keys & Qt.ShiftModifier:
            self.selection_new_group(indices)
        else:
            self.selection_select(indices)

    def selection_select(self, indices):
        self.selection = np.zeros(self.n_valid, dtype=np.uint8)
        self.selection[indices] = 1
        self._update_after_selection()

    def selection_append(self, indices):
        self.selection[indices] = np.max(self.selection)
        self._update_after_selection()

    def selection_new_group(self, indices):
        self.selection[indices] = np.max(self.selection) + 1
        self._update_after_selection()

    def selection_remove(self, indices):
        self.selection[indices] = 0
        self._update_after_selection()

    def _update_after_selection(self):
        self._compress_indices()
        self.update_selection_colors()
        if self.label_only_selected:
            self.update_labels()
        self.master.selection_changed()

    def _compress_indices(self):
        indices = sorted(set(self.selection) | {0})
        if len(indices) == max(indices) + 1:
            return
        mapping = np.zeros((max(indices) + 1,), dtype=int)
        for i, ind in enumerate(indices):
            mapping[ind] = i
        self.selection = mapping[self.selection]

    def get_selection(self):
        if self.selection is None:
            return np.array([], dtype=np.uint8)
        else:
            return np.flatnonzero(self.selection)

    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


class HelpEventDelegate(EventDelegate):
    def __init__(self, delegate, parent=None):
        super().__init__(delegate, parent)
        warnings.warn("HelpEventDelegate class has been deprecated since 3.17."
                      " Use Orange.widgets.visualize.utils.plotutils."
                      "HelpEventDelegate instead.", OrangeDeprecationWarning)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user