{
    "file_diffs": [
        {
            "old_file_content": "from collections import namedtuple\nfrom functools import partial\nfrom operator import itemgetter\n\nimport numpy\nfrom AnyQt.QtWidgets import (\n    QTableView, QListWidget, QSplitter, QStyledItemDelegate,\n    QToolTip, QStyle, QApplication, QSizePolicy)\nfrom AnyQt.QtGui import QPainter, QStandardItem, QPen, QColor\nfrom AnyQt.QtCore import (\n    Qt, QSize, QRect, QRectF, QPoint, QLocale,\n    QModelIndex, QAbstractTableModel, QSortFilterProxyModel, pyqtSignal, QTimer)\n\nimport Orange\nfrom Orange.evaluation import Results\nfrom Orange.base import Model\nfrom Orange.data import ContinuousVariable, DiscreteVariable, Value, Domain\nfrom Orange.data.table import DomainTransformationError\nfrom Orange.widgets import gui, settings\nfrom Orange.widgets.evaluate.utils import (\n    ScoreTable, usable_scorers, learner_name, scorer_caller)\nfrom Orange.widgets.utils.colorpalette import ColorPaletteGenerator\nfrom Orange.widgets.utils.widgetpreview import WidgetPreview\nfrom Orange.widgets.widget import OWWidget, Msg, Input, Output\nfrom Orange.widgets.utils.itemmodels import TableModel\nfrom Orange.widgets.utils.sql import check_sql_input\n\n\n# Input slot for the Predictors channel\nPredictorSlot = namedtuple(\n    \"PredictorSlot\",\n    [\"predictor\",  # The `Model` instance\n     \"name\",       # Predictor name\n     \"results\"]    # Computed prediction results or None.\n)\n\n\nclass OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        n_predictors = len(self.predictors)\n        if not self.data and not n_predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        n_valid = len(self._non_errored_predictors())\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = f\"{len(self.data)} instances\" if self.data else \"No data\"\n        details += f\"\\n{n_predictors} models\" if n_predictors else \"No models\"\n        if n_valid != n_predictors:\n            details += f\" ({n_predictors - n_valid} failed)\"\n        self.info.set_input_summary(summary, details)\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_model = self.predictionsview.model()\n\n            # use ItemDelegate to style prediction values\n            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [style(predictions_model.data(predictions_model.index(i, j)))\n                       for j in range(predictions_model.columnCount())] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self.infolabel.text().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)\n\n\nclass PredictionsItemDelegate(QStyledItemDelegate):\n    \"\"\"\n    A Item Delegate for custom formatting of predictions/probabilities\n    \"\"\"\n    def __init__(\n            self, class_values, colors, shown_probabilities=(),\n            target_format=None, parent=None,\n    ):\n        super().__init__(parent)\n        self.class_values = class_values  # will be None for continuous\n        self.colors = [QColor(*c) for c in colors]\n        self.target_format = target_format  # target format for cont. vars\n        self.shown_probabilities = self.fmt = self.tooltip = None  # set below\n        self.setFormat(shown_probabilities)\n\n    def setFormat(self, shown_probabilities=()):\n        self.shown_probabilities = shown_probabilities\n        if self.class_values is None:\n            # is continuous class\n            self.fmt = f\"{{value:{self.target_format[1:]}}}\"\n        else:\n            self.fmt = \" \\N{RIGHTWARDS ARROW} \".join(\n                [\" : \".join(f\"{{dist[{i}]:.2f}}\" if i is not None else \"-\"\n                            for i in shown_probabilities)]\n                * bool(shown_probabilities)\n                + [\"{value!s}\"])\n        self.tooltip = \"\"\n        if shown_probabilities:\n            val = ', '.join(\n                self.class_values[i] if i is not None else \"-\"\n                for i in shown_probabilities if i is not None\n            )\n            self.tooltip = f\"p({val})\"\n\n    def displayText(self, value, _locale):\n        try:\n            value, dist = value\n        except ValueError:\n            return \"\"\n        else:\n            return self.fmt.format(value=value, dist=dist)\n\n    def helpEvent(self, event, view, option, index):\n        if self.tooltip is not None:\n            # ... but can be an empty string, so the current tooltip is removed\n            QToolTip.showText(event.globalPos(), self.tooltip, view)\n            return True\n        else:\n            return super().helpEvent(event, view, option, index)\n\n    def initStyleOption(self, option, index):\n        super().initStyleOption(option, index)\n        if self.class_values is None:\n            option.displayAlignment = \\\n                (option.displayAlignment & Qt.AlignVertical_Mask) | \\\n                Qt.AlignRight\n\n    def sizeHint(self, option, index):\n        # reimplemented\n        sh = super().sizeHint(option, index)\n        if option.widget is not None:\n            style = option.widget.style()\n        else:\n            style = QApplication.style()\n        margin = style.pixelMetric(\n            QStyle.PM_FocusFrameHMargin, option, option.widget) + 1\n        metrics = option.fontMetrics\n        height = sh.height() + metrics.leading() + 2 * margin\n        return QSize(sh.width(), height)\n\n    @staticmethod\n    def distribution(index):\n        value = index.data(Qt.DisplayRole)\n        if isinstance(value, tuple) and len(value) == 2:\n            _, dist = value\n            return dist\n        else:\n            return None\n\n    def paint(self, painter, option, index):\n        dist = self.distribution(index)\n        if dist is None or self.colors is None:\n            super().paint(painter, option, index)\n            return\n\n        if option.widget is not None:\n            style = option.widget.style()\n        else:\n            style = QApplication.style()\n\n        self.initStyleOption(option, index)\n\n        text = option.text\n        metrics = option.fontMetrics\n\n        margin = style.pixelMetric(\n            QStyle.PM_FocusFrameHMargin, option, option.widget) + 1\n        bottommargin = min(margin, 1)\n        rect = option.rect.adjusted(margin, margin, -margin, -bottommargin)\n\n        textrect = style.subElementRect(\n            QStyle.SE_ItemViewItemText, option, option.widget)\n        # Are the margins included in the subElementRect?? -> No!\n        textrect = textrect.adjusted(margin, margin, -margin, -bottommargin)\n\n        text = option.fontMetrics.elidedText(\n            text, option.textElideMode, textrect.width())\n\n        spacing = max(metrics.leading(), 1)\n\n        distheight = rect.height() - metrics.height() - spacing\n        distheight = numpy.clip(distheight, 2, metrics.height())\n\n        painter.save()\n        painter.setClipRect(option.rect)\n        painter.setFont(option.font)\n        painter.setRenderHint(QPainter.Antialiasing)\n\n        style.drawPrimitive(\n            QStyle.PE_PanelItemViewRow, option, painter, option.widget)\n        style.drawPrimitive(\n            QStyle.PE_PanelItemViewItem, option, painter, option.widget)\n\n        if option.state & QStyle.State_Selected:\n            color = option.palette.highlightedText().color()\n        else:\n            color = option.palette.text().color()\n        painter.setPen(QPen(color))\n\n        textrect = textrect.adjusted(0, 0, 0, -distheight - spacing)\n        distrect = QRect(\n            textrect.bottomLeft() + QPoint(0, spacing),\n            QSize(rect.width(), distheight))\n        painter.setPen(QPen(Qt.lightGray, 0.3))\n        self.drawDistBar(painter, distrect, dist)\n        painter.restore()\n        if text:\n            style.drawItemText(\n                painter, textrect, option.displayAlignment, option.palette,\n                option.state & QStyle.State_Enabled, text)\n\n    def drawDistBar(self, painter, rect, distribution):\n        painter.save()\n        painter.translate(rect.topLeft())\n        for i in self.shown_probabilities:\n            if i is None:\n                continue\n            dvalue = distribution[i]\n            if not dvalue > 0:  # This also skips nans\n                continue\n            painter.setBrush(self.colors[i])\n            width = rect.width() * dvalue\n            painter.drawRoundedRect(QRectF(0, 0, width, rect.height()), 1, 2)\n            painter.translate(width, 0.0)\n        painter.restore()\n\n\nclass SortProxyModel(QSortFilterProxyModel):\n    \"\"\"\n    QSortFilter model used in both TableView and PredictionsView\n    \"\"\"\n    list_sorted = pyqtSignal()\n\n    def __init__(self, parent=None):\n        super().__init__(parent)\n        self.__sortInd = None\n\n    def setSortIndices(self, indices):\n        if indices is not None:\n            indices = numpy.array(indices, dtype=numpy.int)\n            if indices.shape != (self.rowCount(),):\n                raise ValueError(\"indices.shape != (self.rowCount(),)\")\n            indices.flags.writeable = False\n\n        self.__sortInd = indices\n\n        if self.__sortInd is not None:\n            self.custom_sort(0)  # need valid order to call lessThan\n\n    def lessThan(self, left, right):\n        if self.__sortInd is None:\n            return super().lessThan(left, right)\n\n        assert not (left.parent().isValid() or right.parent().isValid()), \\\n            \"Not a table model\"\n\n        rleft, rright = left.row(), right.row()\n        try:\n            ileft, iright = self.__sortInd[rleft], self.__sortInd[rright]\n        except IndexError:\n            return False\n        else:\n            return ileft < iright\n\n    def isSorted(self):\n        return self.__sortInd is not None\n\n    def sort(self, n, order=Qt.AscendingOrder):\n        \"\"\"\n        This sort is called only on click, in other cases we manually call\n        custom_sort\n        \"\"\"\n        # reset sort - otherwise when same parameters set by lessThan function\n        # clicking on header would not trigger resort\n        self.__sortInd = None\n        self.custom_sort(n, order=order)\n        self.list_sorted.emit()\n\n    def custom_sort(self, n, order=Qt.AscendingOrder):\n        \"\"\"\n        When sorting is dmanded because of sort change in the other view\n        this sorting is called. It will not reset __sortInd to None.\n        \"\"\"\n        if self.sortColumn() == n and self.sortOrder() == order:\n            self.invalidate()\n        else:\n            super().sort(n, order)  # need some valid sort column\n\n\nclass PredictionsSortProxyModel(SortProxyModel):\n    def __init__(self, parent=None):\n        super().__init__(parent)\n        self.__probInd = None\n\n    def setProbInd(self, indices):\n        self.__probInd = indices\n        self.invalidate()\n        self.list_sorted.emit()\n\n    def lessThan(self, left, right):\n        if self.isSorted():\n            return super().lessThan(left, right)\n\n        role = self.sortRole()\n        left_data = self.sourceModel().data(left, role)\n        right_data = self.sourceModel().data(right, role)\n\n        return self._key(left_data) < self._key(right_data)\n\n    def _key(self, prediction):\n        value, probs = prediction\n        if probs is not None:\n            if self.__probInd is not None:\n                probs = probs[self.__probInd]\n            probs = tuple(probs)\n\n        return probs, value\n\n\nclass PredictionsModel(QAbstractTableModel):\n    def __init__(self, table=None, headers=None, parent=None):\n        super().__init__(parent)\n        self._table = [[]] if table is None else table\n        if headers is None:\n            headers = [None] * len(self._table)\n        self._header = headers\n        self.__columnCount = max([len(row) for row in self._table] or [0])\n\n    def rowCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else len(self._table)\n\n    def columnCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else self.__columnCount\n\n    def _value(self, index):\n        return self._table[index.row()][index.column()]\n\n    def data(self, index, role=Qt.DisplayRole):\n        if role in (Qt.DisplayRole, Qt.EditRole):\n            return self._value(index)\n        return None\n\n    def headerData(self, section, orientation, role=Qt.DisplayRole):\n        if orientation == Qt.Vertical and role == Qt.DisplayRole:\n            return str(section + 1)\n        if orientation == Qt.Horizontal and role == Qt.DisplayRole:\n            return (self._header[section] if section < len(self._header)\n                    else str(section))\n        return None\n\n\nclass TableView(QTableView):\n    MaxSizeHintSamples = 1000\n\n    def sizeHintForColumn(self, column):\n        \"\"\"\n        Reimplemented from `QTableView.sizeHintForColumn`\n\n        Note: This does not match the QTableView's implementation,\n        in particular size hints from editor/index widgets are not taken\n        into account.\n\n        Parameters\n        ----------\n        column : int\n        \"\"\"\n        # This is probably not needed in Qt5?\n        if self.model() is None:\n            return -1\n\n        self.ensurePolished()\n        model = self.model()\n        vheader = self.verticalHeader()\n        top = vheader.visualIndexAt(0)\n        bottom = vheader.visualIndexAt(self.viewport().height())\n        if bottom < 0:\n            bottom = self.model().rowCount()\n\n        options = self.viewOptions()\n        options.widget = self\n\n        width = 0\n        sample_count = 0\n\n        for row in range(top, bottom):\n            if not vheader.isSectionHidden(vheader.logicalIndex(row)):\n                index = model.index(row, column)\n                delegate = self.itemDelegate(index)\n                if not delegate:\n                    continue\n                size = delegate.sizeHint(options, index)\n                width = max(size.width(), width)\n                sample_count += 1\n\n            if sample_count >= TableView.MaxSizeHintSamples:\n                break\n\n        return width + 1 if self.showGrid() else width\n\n\ndef tool_tip(value):\n    value, dist = value\n    if dist is not None:\n        return \"{!s} {!s}\".format(value, dist)\n    else:\n        return str(value)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    filename = \"iris.tab\"\n    iris = Orange.data.Table(filename)\n    idom = iris.domain\n    dom = Domain(\n        idom.attributes,\n        DiscreteVariable(idom.class_var.name, idom.class_var.values[1::-1])\n    )\n    iris2 = iris[:100].transform(dom)\n\n    def pred_error(data, *args, **kwargs):\n        raise ValueError\n\n    pred_error.domain = iris.domain\n    pred_error.name = \"To err is human\"\n\n    if iris.domain.has_discrete_class:\n        predictors_ = [\n            Orange.classification.SVMLearner(probability=True)(iris2),\n            Orange.classification.LogisticRegressionLearner()(iris),\n            pred_error\n        ]\n    elif iris.domain.has_continuous_class:\n        predictors_ = [\n            Orange.regression.RidgeRegressionLearner(alpha=1.0)(iris),\n            Orange.regression.LinearRegressionLearner()(iris),\n            pred_error\n        ]\n    else:\n        predictors_ = [pred_error]\n\n    WidgetPreview(OWPredictions).run(\n        set_data=iris2,\n        set_predictor=[(pred, i) for i, pred in enumerate(predictors_)])\n",
            "new_file_content": "from collections import namedtuple\nfrom functools import partial\nfrom operator import itemgetter\n\nimport numpy\nfrom AnyQt.QtWidgets import (\n    QTableView, QListWidget, QSplitter, QStyledItemDelegate,\n    QToolTip, QStyle, QApplication, QSizePolicy)\nfrom AnyQt.QtGui import QPainter, QStandardItem, QPen, QColor\nfrom AnyQt.QtCore import (\n    Qt, QSize, QRect, QRectF, QPoint, QLocale,\n    QModelIndex, QAbstractTableModel, QSortFilterProxyModel, pyqtSignal, QTimer)\n\nfrom orangewidget.report import plural\n\nimport Orange\nfrom Orange.evaluation import Results\nfrom Orange.base import Model\nfrom Orange.data import ContinuousVariable, DiscreteVariable, Value, Domain\nfrom Orange.data.table import DomainTransformationError\nfrom Orange.widgets import gui, settings\nfrom Orange.widgets.evaluate.utils import (\n    ScoreTable, usable_scorers, learner_name, scorer_caller)\nfrom Orange.widgets.utils.colorpalette import ColorPaletteGenerator\nfrom Orange.widgets.utils.widgetpreview import WidgetPreview\nfrom Orange.widgets.widget import OWWidget, Msg, Input, Output\nfrom Orange.widgets.utils.itemmodels import TableModel\nfrom Orange.widgets.utils.sql import check_sql_input\n\n\n# Input slot for the Predictors channel\nPredictorSlot = namedtuple(\n    \"PredictorSlot\",\n    [\"predictor\",  # The `Model` instance\n     \"name\",       # Predictor name\n     \"results\"]    # Computed prediction results or None.\n)\n\n\nclass OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        if not self.data and not self.predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = self._get_details()\n        self.info.set_input_summary(summary, details)\n\n    def _get_details(self):\n        n_predictors = len(self.predictors)\n        if self.data:\n            details = plural(\"{number} instance{s}\", len(self.data))\n        else:\n            details = \"No data\"\n        if n_predictors:\n            n_valid = len(self._non_errored_predictors())\n            details += plural(\"\\n{number} model{s}\", n_predictors)\n            if n_valid != n_predictors:\n                details += plural(\" ({number} failed)\", n_predictors - n_valid)\n        else:\n            details += \"\\nNo models\"\n        return details\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_view = self.predictionsview\n            predictions_model = predictions_view.model()\n\n            # use ItemDelegate to style prediction values\n            delegates = [predictions_view.itemDelegateForColumn(i)\n                         for i in range(predictions_model.columnCount())]\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [delegate.displayText(\n                          predictions_model.data(predictions_model.index(i, j)),\n                          QLocale())\n                       for j, delegate in enumerate(delegates)] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self._get_details().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n            self.report_table(\"Scores\", self.score_table.view)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)\n\n\nclass PredictionsItemDelegate(QStyledItemDelegate):\n    \"\"\"\n    A Item Delegate for custom formatting of predictions/probabilities\n    \"\"\"\n    def __init__(\n            self, class_values, colors, shown_probabilities=(),\n            target_format=None, parent=None,\n    ):\n        super().__init__(parent)\n        self.class_values = class_values  # will be None for continuous\n        self.colors = [QColor(*c) for c in colors]\n        self.target_format = target_format  # target format for cont. vars\n        self.shown_probabilities = self.fmt = self.tooltip = None  # set below\n        self.setFormat(shown_probabilities)\n\n    def setFormat(self, shown_probabilities=()):\n        self.shown_probabilities = shown_probabilities\n        if self.class_values is None:\n            # is continuous class\n            self.fmt = f\"{{value:{self.target_format[1:]}}}\"\n        else:\n            self.fmt = \" \\N{RIGHTWARDS ARROW} \".join(\n                [\" : \".join(f\"{{dist[{i}]:.2f}}\" if i is not None else \"-\"\n                            for i in shown_probabilities)]\n                * bool(shown_probabilities)\n                + [\"{value!s}\"])\n        self.tooltip = \"\"\n        if shown_probabilities:\n            val = ', '.join(\n                self.class_values[i] if i is not None else \"-\"\n                for i in shown_probabilities if i is not None\n            )\n            self.tooltip = f\"p({val})\"\n\n    def displayText(self, value, _locale):\n        try:\n            value, dist = value\n        except ValueError:\n            return \"\"\n        else:\n            return self.fmt.format(value=value, dist=dist)\n\n    def helpEvent(self, event, view, option, index):\n        if self.tooltip is not None:\n            # ... but can be an empty string, so the current tooltip is removed\n            QToolTip.showText(event.globalPos(), self.tooltip, view)\n            return True\n        else:\n            return super().helpEvent(event, view, option, index)\n\n    def initStyleOption(self, option, index):\n        super().initStyleOption(option, index)\n        if self.class_values is None:\n            option.displayAlignment = \\\n                (option.displayAlignment & Qt.AlignVertical_Mask) | \\\n                Qt.AlignRight\n\n    def sizeHint(self, option, index):\n        # reimplemented\n        sh = super().sizeHint(option, index)\n        if option.widget is not None:\n            style = option.widget.style()\n        else:\n            style = QApplication.style()\n        margin = style.pixelMetric(\n            QStyle.PM_FocusFrameHMargin, option, option.widget) + 1\n        metrics = option.fontMetrics\n        height = sh.height() + metrics.leading() + 2 * margin\n        return QSize(sh.width(), height)\n\n    @staticmethod\n    def distribution(index):\n        value = index.data(Qt.DisplayRole)\n        if isinstance(value, tuple) and len(value) == 2:\n            _, dist = value\n            return dist\n        else:\n            return None\n\n    def paint(self, painter, option, index):\n        dist = self.distribution(index)\n        if dist is None or self.colors is None:\n            super().paint(painter, option, index)\n            return\n\n        if option.widget is not None:\n            style = option.widget.style()\n        else:\n            style = QApplication.style()\n\n        self.initStyleOption(option, index)\n\n        text = option.text\n        metrics = option.fontMetrics\n\n        margin = style.pixelMetric(\n            QStyle.PM_FocusFrameHMargin, option, option.widget) + 1\n        bottommargin = min(margin, 1)\n        rect = option.rect.adjusted(margin, margin, -margin, -bottommargin)\n\n        textrect = style.subElementRect(\n            QStyle.SE_ItemViewItemText, option, option.widget)\n        # Are the margins included in the subElementRect?? -> No!\n        textrect = textrect.adjusted(margin, margin, -margin, -bottommargin)\n\n        text = option.fontMetrics.elidedText(\n            text, option.textElideMode, textrect.width())\n\n        spacing = max(metrics.leading(), 1)\n\n        distheight = rect.height() - metrics.height() - spacing\n        distheight = numpy.clip(distheight, 2, metrics.height())\n\n        painter.save()\n        painter.setClipRect(option.rect)\n        painter.setFont(option.font)\n        painter.setRenderHint(QPainter.Antialiasing)\n\n        style.drawPrimitive(\n            QStyle.PE_PanelItemViewRow, option, painter, option.widget)\n        style.drawPrimitive(\n            QStyle.PE_PanelItemViewItem, option, painter, option.widget)\n\n        if option.state & QStyle.State_Selected:\n            color = option.palette.highlightedText().color()\n        else:\n            color = option.palette.text().color()\n        painter.setPen(QPen(color))\n\n        textrect = textrect.adjusted(0, 0, 0, -distheight - spacing)\n        distrect = QRect(\n            textrect.bottomLeft() + QPoint(0, spacing),\n            QSize(rect.width(), distheight))\n        painter.setPen(QPen(Qt.lightGray, 0.3))\n        self.drawDistBar(painter, distrect, dist)\n        painter.restore()\n        if text:\n            style.drawItemText(\n                painter, textrect, option.displayAlignment, option.palette,\n                option.state & QStyle.State_Enabled, text)\n\n    def drawDistBar(self, painter, rect, distribution):\n        painter.save()\n        painter.translate(rect.topLeft())\n        for i in self.shown_probabilities:\n            if i is None:\n                continue\n            dvalue = distribution[i]\n            if not dvalue > 0:  # This also skips nans\n                continue\n            painter.setBrush(self.colors[i])\n            width = rect.width() * dvalue\n            painter.drawRoundedRect(QRectF(0, 0, width, rect.height()), 1, 2)\n            painter.translate(width, 0.0)\n        painter.restore()\n\n\nclass SortProxyModel(QSortFilterProxyModel):\n    \"\"\"\n    QSortFilter model used in both TableView and PredictionsView\n    \"\"\"\n    list_sorted = pyqtSignal()\n\n    def __init__(self, parent=None):\n        super().__init__(parent)\n        self.__sortInd = None\n\n    def setSortIndices(self, indices):\n        if indices is not None:\n            indices = numpy.array(indices, dtype=numpy.int)\n            if indices.shape != (self.rowCount(),):\n                raise ValueError(\"indices.shape != (self.rowCount(),)\")\n            indices.flags.writeable = False\n\n        self.__sortInd = indices\n\n        if self.__sortInd is not None:\n            self.custom_sort(0)  # need valid order to call lessThan\n\n    def lessThan(self, left, right):\n        if self.__sortInd is None:\n            return super().lessThan(left, right)\n\n        assert not (left.parent().isValid() or right.parent().isValid()), \\\n            \"Not a table model\"\n\n        rleft, rright = left.row(), right.row()\n        try:\n            ileft, iright = self.__sortInd[rleft], self.__sortInd[rright]\n        except IndexError:\n            return False\n        else:\n            return ileft < iright\n\n    def isSorted(self):\n        return self.__sortInd is not None\n\n    def sort(self, n, order=Qt.AscendingOrder):\n        \"\"\"\n        This sort is called only on click, in other cases we manually call\n        custom_sort\n        \"\"\"\n        # reset sort - otherwise when same parameters set by lessThan function\n        # clicking on header would not trigger resort\n        self.__sortInd = None\n        self.custom_sort(n, order=order)\n        self.list_sorted.emit()\n\n    def custom_sort(self, n, order=Qt.AscendingOrder):\n        \"\"\"\n        When sorting is dmanded because of sort change in the other view\n        this sorting is called. It will not reset __sortInd to None.\n        \"\"\"\n        if self.sortColumn() == n and self.sortOrder() == order:\n            self.invalidate()\n        else:\n            super().sort(n, order)  # need some valid sort column\n\n\nclass PredictionsSortProxyModel(SortProxyModel):\n    def __init__(self, parent=None):\n        super().__init__(parent)\n        self.__probInd = None\n\n    def setProbInd(self, indices):\n        self.__probInd = indices\n        self.invalidate()\n        self.list_sorted.emit()\n\n    def lessThan(self, left, right):\n        if self.isSorted():\n            return super().lessThan(left, right)\n\n        role = self.sortRole()\n        left_data = self.sourceModel().data(left, role)\n        right_data = self.sourceModel().data(right, role)\n\n        return self._key(left_data) < self._key(right_data)\n\n    def _key(self, prediction):\n        value, probs = prediction\n        if probs is not None:\n            if self.__probInd is not None:\n                probs = probs[self.__probInd]\n            probs = tuple(probs)\n\n        return probs, value\n\n\nclass PredictionsModel(QAbstractTableModel):\n    def __init__(self, table=None, headers=None, parent=None):\n        super().__init__(parent)\n        self._table = [[]] if table is None else table\n        if headers is None:\n            headers = [None] * len(self._table)\n        self._header = headers\n        self.__columnCount = max([len(row) for row in self._table] or [0])\n\n    def rowCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else len(self._table)\n\n    def columnCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else self.__columnCount\n\n    def _value(self, index):\n        return self._table[index.row()][index.column()]\n\n    def data(self, index, role=Qt.DisplayRole):\n        if role in (Qt.DisplayRole, Qt.EditRole):\n            return self._value(index)\n        return None\n\n    def headerData(self, section, orientation, role=Qt.DisplayRole):\n        if orientation == Qt.Vertical and role == Qt.DisplayRole:\n            return str(section + 1)\n        if orientation == Qt.Horizontal and role == Qt.DisplayRole:\n            return (self._header[section] if section < len(self._header)\n                    else str(section))\n        return None\n\n\nclass TableView(QTableView):\n    MaxSizeHintSamples = 1000\n\n    def sizeHintForColumn(self, column):\n        \"\"\"\n        Reimplemented from `QTableView.sizeHintForColumn`\n\n        Note: This does not match the QTableView's implementation,\n        in particular size hints from editor/index widgets are not taken\n        into account.\n\n        Parameters\n        ----------\n        column : int\n        \"\"\"\n        # This is probably not needed in Qt5?\n        if self.model() is None:\n            return -1\n\n        self.ensurePolished()\n        model = self.model()\n        vheader = self.verticalHeader()\n        top = vheader.visualIndexAt(0)\n        bottom = vheader.visualIndexAt(self.viewport().height())\n        if bottom < 0:\n            bottom = self.model().rowCount()\n\n        options = self.viewOptions()\n        options.widget = self\n\n        width = 0\n        sample_count = 0\n\n        for row in range(top, bottom):\n            if not vheader.isSectionHidden(vheader.logicalIndex(row)):\n                index = model.index(row, column)\n                delegate = self.itemDelegate(index)\n                if not delegate:\n                    continue\n                size = delegate.sizeHint(options, index)\n                width = max(size.width(), width)\n                sample_count += 1\n\n            if sample_count >= TableView.MaxSizeHintSamples:\n                break\n\n        return width + 1 if self.showGrid() else width\n\n\ndef tool_tip(value):\n    value, dist = value\n    if dist is not None:\n        return \"{!s} {!s}\".format(value, dist)\n    else:\n        return str(value)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    filename = \"iris.tab\"\n    iris = Orange.data.Table(filename)\n    idom = iris.domain\n    dom = Domain(\n        idom.attributes,\n        DiscreteVariable(idom.class_var.name, idom.class_var.values[1::-1])\n    )\n    iris2 = iris[:100].transform(dom)\n\n    def pred_error(data, *args, **kwargs):\n        raise ValueError\n\n    pred_error.domain = iris.domain\n    pred_error.name = \"To err is human\"\n\n    if iris.domain.has_discrete_class:\n        predictors_ = [\n            Orange.classification.SVMLearner(probability=True)(iris2),\n            Orange.classification.LogisticRegressionLearner()(iris),\n            pred_error\n        ]\n    elif iris.domain.has_continuous_class:\n        predictors_ = [\n            Orange.regression.RidgeRegressionLearner(alpha=1.0)(iris),\n            Orange.regression.LinearRegressionLearner()(iris),\n            pred_error\n        ]\n    else:\n        predictors_ = [pred_error]\n\n    WidgetPreview(OWPredictions).run(\n        set_data=iris2,\n        set_predictor=[(pred, i) for i, pred in enumerate(predictors_)])\n",
            "header": {
                "file": {
                    "path": "Orange/widgets/evaluate/owpredictions.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "5bbb09b26",
                "new_commit_hash": "879d754b3",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/widgets/evaluate/owpredictions.py"
            },
            "plus_file": {
                "path": "b/Orange/widgets/evaluate/owpredictions.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 11,
                            "length": 6
                        },
                        "new_range": {
                            "start": 11,
                            "length": 8
                        },
                        "section": "from AnyQt.QtCore import ("
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    Qt, QSize, QRect, QRectF, QPoint, QLocale,",
                                "type": "context"
                            },
                            {
                                "content": "    QModelIndex, QAbstractTableModel, QSortFilterProxyModel, pyqtSignal, QTimer)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "from orangewidget.report import plural",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "import Orange",
                                "type": "context"
                            },
                            {
                                "content": "from Orange.evaluation import Results",
                                "type": "context"
                            },
                            {
                                "content": "from Orange.base import Model",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "Orange/widgets/evaluate/owpredictions.py",
                            "type": "statement",
                            "name": "",
                            "content": "from orangewidget.report import plural",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 14,
                            "end_lineno": 14,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 293,
                            "length": 19
                        },
                        "new_range": {
                            "start": 295,
                            "length": 29
                        },
                        "section": "class OWPredictions(OWWidget):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            self.Warning.wrong_targets.clear()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def _update_info(self):",
                                "type": "context"
                            },
                            {
                                "content": "        n_predictors = len(self.predictors)",
                                "type": "deleted"
                            },
                            {
                                "content": "        if not self.data and not n_predictors:",
                                "type": "deleted"
                            },
                            {
                                "content": "        if not self.data and not self.predictors:",
                                "type": "added"
                            },
                            {
                                "content": "            self.info.set_input_summary(self.info.NoInput)",
                                "type": "context"
                            },
                            {
                                "content": "            return",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        n_valid = len(self._non_errored_predictors())",
                                "type": "deleted"
                            },
                            {
                                "content": "        summary = str(len(self.data)) if self.data else \"0\"",
                                "type": "context"
                            },
                            {
                                "content": "        details = f\"{len(self.data)} instances\" if self.data else \"No data\"",
                                "type": "deleted"
                            },
                            {
                                "content": "        details += f\"\\n{n_predictors} models\" if n_predictors else \"No models\"",
                                "type": "deleted"
                            },
                            {
                                "content": "        if n_valid != n_predictors:",
                                "type": "deleted"
                            },
                            {
                                "content": "            details += f\" ({n_predictors - n_valid} failed)\"",
                                "type": "deleted"
                            },
                            {
                                "content": "        details = self._get_details()",
                                "type": "added"
                            },
                            {
                                "content": "        self.info.set_input_summary(summary, details)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def _get_details(self):",
                                "type": "added"
                            },
                            {
                                "content": "        n_predictors = len(self.predictors)",
                                "type": "added"
                            },
                            {
                                "content": "        if self.data:",
                                "type": "added"
                            },
                            {
                                "content": "            details = plural(\"{number} instance{s}\", len(self.data))",
                                "type": "added"
                            },
                            {
                                "content": "        else:",
                                "type": "added"
                            },
                            {
                                "content": "            details = \"No data\"",
                                "type": "added"
                            },
                            {
                                "content": "        if n_predictors:",
                                "type": "added"
                            },
                            {
                                "content": "            n_valid = len(self._non_errored_predictors())",
                                "type": "added"
                            },
                            {
                                "content": "            details += plural(\"\\n{number} model{s}\", n_predictors)",
                                "type": "added"
                            },
                            {
                                "content": "            if n_valid != n_predictors:",
                                "type": "added"
                            },
                            {
                                "content": "                details += plural(\" ({number} failed)\", n_predictors - n_valid)",
                                "type": "added"
                            },
                            {
                                "content": "        else:",
                                "type": "added"
                            },
                            {
                                "content": "            details += \"\\nNo models\"",
                                "type": "added"
                            },
                            {
                                "content": "        return details",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def _invalidate_predictions(self):",
                                "type": "context"
                            },
                            {
                                "content": "        for inputid, pred in list(self.predictors.items()):",
                                "type": "context"
                            },
                            {
                                "content": "            self.predictors[inputid] = pred._replace(results=None)",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/evaluate/owpredictions.py",
                            "type": "method",
                            "name": "OWPredictions._update_info",
                            "content": "class OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        n_predictors = len(self.predictors)\n        if not self.data and not n_predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        n_valid = len(self._non_errored_predictors())\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = f\"{len(self.data)} instances\" if self.data else \"No data\"\n        details += f\"\\n{n_predictors} models\" if n_predictors else \"No models\"\n        if n_valid != n_predictors:\n            details += f\" ({n_predictors - n_valid} failed)\"\n        self.info.set_input_summary(summary, details)\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_model = self.predictionsview.model()\n\n            # use ItemDelegate to style prediction values\n            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [style(predictions_model.data(predictions_model.index(i, j)))\n                       for j in range(predictions_model.columnCount())] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self.infolabel.text().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 295,
                            "end_lineno": 307,
                            "parent": {
                                "file_name": "Orange/widgets/evaluate/owpredictions.py",
                                "type": "class",
                                "name": "OWPredictions",
                                "content": "class OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        n_predictors = len(self.predictors)\n        if not self.data and not n_predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        n_valid = len(self._non_errored_predictors())\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = f\"{len(self.data)} instances\" if self.data else \"No data\"\n        details += f\"\\n{n_predictors} models\" if n_predictors else \"No models\"\n        if n_valid != n_predictors:\n            details += f\" ({n_predictors - n_valid} failed)\"\n        self.info.set_input_summary(summary, details)\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_model = self.predictionsview.model()\n\n            # use ItemDelegate to style prediction values\n            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [style(predictions_model.data(predictions_model.index(i, j)))\n                       for j in range(predictions_model.columnCount())] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self.infolabel.text().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 38,
                                "end_lineno": 603,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/widgets/evaluate/owpredictions.py",
                            "type": "class",
                            "name": "OWPredictions",
                            "content": "class OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        n_predictors = len(self.predictors)\n        if not self.data and not n_predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        n_valid = len(self._non_errored_predictors())\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = f\"{len(self.data)} instances\" if self.data else \"No data\"\n        details += f\"\\n{n_predictors} models\" if n_predictors else \"No models\"\n        if n_valid != n_predictors:\n            details += f\" ({n_predictors - n_valid} failed)\"\n        self.info.set_input_summary(summary, details)\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_model = self.predictionsview.model()\n\n            # use ItemDelegate to style prediction values\n            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [style(predictions_model.data(predictions_model.index(i, j)))\n                       for j in range(predictions_model.columnCount())] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self.infolabel.text().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 38,
                            "end_lineno": 603,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "Orange/widgets/evaluate/owpredictions.py",
                            "type": "method",
                            "name": "OWPredictions._get_details",
                            "content": "class OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        if not self.data and not self.predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = self._get_details()\n        self.info.set_input_summary(summary, details)\n\n    def _get_details(self):\n        n_predictors = len(self.predictors)\n        if self.data:\n            details = plural(\"{number} instance{s}\", len(self.data))\n        else:\n            details = \"No data\"\n        if n_predictors:\n            n_valid = len(self._non_errored_predictors())\n            details += plural(\"\\n{number} model{s}\", n_predictors)\n            if n_valid != n_predictors:\n                details += plural(\" ({number} failed)\", n_predictors - n_valid)\n        else:\n            details += \"\\nNo models\"\n        return details\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_view = self.predictionsview\n            predictions_model = predictions_view.model()\n\n            # use ItemDelegate to style prediction values\n            delegates = [predictions_view.itemDelegateForColumn(i)\n                         for i in range(predictions_model.columnCount())]\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [delegate.displayText(\n                          predictions_model.data(predictions_model.index(i, j)),\n                          QLocale())\n                       for j, delegate in enumerate(delegates)] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self._get_details().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n            self.report_table(\"Scores\", self.score_table.view)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 306,
                            "end_lineno": 319,
                            "parent": {
                                "file_name": "Orange/widgets/evaluate/owpredictions.py",
                                "type": "class",
                                "name": "OWPredictions",
                                "content": "class OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        if not self.data and not self.predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = self._get_details()\n        self.info.set_input_summary(summary, details)\n\n    def _get_details(self):\n        n_predictors = len(self.predictors)\n        if self.data:\n            details = plural(\"{number} instance{s}\", len(self.data))\n        else:\n            details = \"No data\"\n        if n_predictors:\n            n_valid = len(self._non_errored_predictors())\n            details += plural(\"\\n{number} model{s}\", n_predictors)\n            if n_valid != n_predictors:\n                details += plural(\" ({number} failed)\", n_predictors - n_valid)\n        else:\n            details += \"\\nNo models\"\n        return details\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_view = self.predictionsview\n            predictions_model = predictions_view.model()\n\n            # use ItemDelegate to style prediction values\n            delegates = [predictions_view.itemDelegateForColumn(i)\n                         for i in range(predictions_model.columnCount())]\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [delegate.displayText(\n                          predictions_model.data(predictions_model.index(i, j)),\n                          QLocale())\n                       for j, delegate in enumerate(delegates)] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self._get_details().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n            self.report_table(\"Scores\", self.score_table.view)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 40,
                                "end_lineno": 621,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 560,
                            "length": 10
                        },
                        "new_range": {
                            "start": 572,
                            "length": 12
                        },
                        "section": "class OWPredictions(OWWidget):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    def send_report(self):",
                                "type": "context"
                            },
                            {
                                "content": "        def merge_data_with_predictions():",
                                "type": "context"
                            },
                            {
                                "content": "            data_model = self.dataview.model()",
                                "type": "context"
                            },
                            {
                                "content": "            predictions_model = self.predictionsview.model()",
                                "type": "deleted"
                            },
                            {
                                "content": "            predictions_view = self.predictionsview",
                                "type": "added"
                            },
                            {
                                "content": "            predictions_model = predictions_view.model()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "            # use ItemDelegate to style prediction values",
                                "type": "context"
                            },
                            {
                                "content": "            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())",
                                "type": "deleted"
                            },
                            {
                                "content": "            delegates = [predictions_view.itemDelegateForColumn(i)",
                                "type": "added"
                            },
                            {
                                "content": "                         for i in range(predictions_model.columnCount())]",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "            # iterate only over visible columns of data's QTableView",
                                "type": "context"
                            },
                            {
                                "content": "            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/evaluate/owpredictions.py",
                            "type": "method",
                            "name": "OWPredictions.send_report",
                            "content": "class OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        n_predictors = len(self.predictors)\n        if not self.data and not n_predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        n_valid = len(self._non_errored_predictors())\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = f\"{len(self.data)} instances\" if self.data else \"No data\"\n        details += f\"\\n{n_predictors} models\" if n_predictors else \"No models\"\n        if n_valid != n_predictors:\n            details += f\" ({n_predictors - n_valid} failed)\"\n        self.info.set_input_summary(summary, details)\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_model = self.predictionsview.model()\n\n            # use ItemDelegate to style prediction values\n            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [style(predictions_model.data(predictions_model.index(i, j)))\n                       for j in range(predictions_model.columnCount())] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self.infolabel.text().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 560,
                            "end_lineno": 595,
                            "parent": {
                                "file_name": "Orange/widgets/evaluate/owpredictions.py",
                                "type": "class",
                                "name": "OWPredictions",
                                "content": "class OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        n_predictors = len(self.predictors)\n        if not self.data and not n_predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        n_valid = len(self._non_errored_predictors())\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = f\"{len(self.data)} instances\" if self.data else \"No data\"\n        details += f\"\\n{n_predictors} models\" if n_predictors else \"No models\"\n        if n_valid != n_predictors:\n            details += f\" ({n_predictors - n_valid} failed)\"\n        self.info.set_input_summary(summary, details)\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_model = self.predictionsview.model()\n\n            # use ItemDelegate to style prediction values\n            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [style(predictions_model.data(predictions_model.index(i, j)))\n                       for j in range(predictions_model.columnCount())] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self.infolabel.text().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 38,
                                "end_lineno": 603,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/widgets/evaluate/owpredictions.py",
                            "type": "class",
                            "name": "OWPredictions",
                            "content": "class OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        n_predictors = len(self.predictors)\n        if not self.data and not n_predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        n_valid = len(self._non_errored_predictors())\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = f\"{len(self.data)} instances\" if self.data else \"No data\"\n        details += f\"\\n{n_predictors} models\" if n_predictors else \"No models\"\n        if n_valid != n_predictors:\n            details += f\" ({n_predictors - n_valid} failed)\"\n        self.info.set_input_summary(summary, details)\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_model = self.predictionsview.model()\n\n            # use ItemDelegate to style prediction values\n            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [style(predictions_model.data(predictions_model.index(i, j)))\n                       for j in range(predictions_model.columnCount())] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self.infolabel.text().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 38,
                            "end_lineno": 603,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 579,
                            "length": 13
                        },
                        "new_range": {
                            "start": 593,
                            "length": 15
                        },
                        "section": "class OWPredictions(OWWidget):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            # print data & predictions",
                                "type": "context"
                            },
                            {
                                "content": "            for i in range(data_model.rowCount()):",
                                "type": "context"
                            },
                            {
                                "content": "                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\",
                                "type": "context"
                            },
                            {
                                "content": "                      [style(predictions_model.data(predictions_model.index(i, j)))",
                                "type": "deleted"
                            },
                            {
                                "content": "                       for j in range(predictions_model.columnCount())] + \\",
                                "type": "deleted"
                            },
                            {
                                "content": "                      [delegate.displayText(",
                                "type": "added"
                            },
                            {
                                "content": "                          predictions_model.data(predictions_model.index(i, j)),",
                                "type": "added"
                            },
                            {
                                "content": "                          QLocale())",
                                "type": "added"
                            },
                            {
                                "content": "                       for j, delegate in enumerate(delegates)] + \\",
                                "type": "added"
                            },
                            {
                                "content": "                      [data_model.data(data_model.index(i, j))",
                                "type": "context"
                            },
                            {
                                "content": "                       for j in iter_data_cols]",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        if self.data:",
                                "type": "context"
                            },
                            {
                                "content": "            text = self.infolabel.text().replace('\\n', '<br>')",
                                "type": "deleted"
                            },
                            {
                                "content": "            text = self._get_details().replace('\\n', '<br>')",
                                "type": "added"
                            },
                            {
                                "content": "            if self.selected_classes:",
                                "type": "context"
                            },
                            {
                                "content": "                text += '<br>Showing probabilities for: '",
                                "type": "context"
                            },
                            {
                                "content": "                text += ', '. join([self.class_values[i]",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/evaluate/owpredictions.py",
                            "type": "method",
                            "name": "OWPredictions.send_report",
                            "content": "class OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        n_predictors = len(self.predictors)\n        if not self.data and not n_predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        n_valid = len(self._non_errored_predictors())\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = f\"{len(self.data)} instances\" if self.data else \"No data\"\n        details += f\"\\n{n_predictors} models\" if n_predictors else \"No models\"\n        if n_valid != n_predictors:\n            details += f\" ({n_predictors - n_valid} failed)\"\n        self.info.set_input_summary(summary, details)\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_model = self.predictionsview.model()\n\n            # use ItemDelegate to style prediction values\n            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [style(predictions_model.data(predictions_model.index(i, j)))\n                       for j in range(predictions_model.columnCount())] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self.infolabel.text().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 560,
                            "end_lineno": 595,
                            "parent": {
                                "file_name": "Orange/widgets/evaluate/owpredictions.py",
                                "type": "class",
                                "name": "OWPredictions",
                                "content": "class OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        n_predictors = len(self.predictors)\n        if not self.data and not n_predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        n_valid = len(self._non_errored_predictors())\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = f\"{len(self.data)} instances\" if self.data else \"No data\"\n        details += f\"\\n{n_predictors} models\" if n_predictors else \"No models\"\n        if n_valid != n_predictors:\n            details += f\" ({n_predictors - n_valid} failed)\"\n        self.info.set_input_summary(summary, details)\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_model = self.predictionsview.model()\n\n            # use ItemDelegate to style prediction values\n            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [style(predictions_model.data(predictions_model.index(i, j)))\n                       for j in range(predictions_model.columnCount())] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self.infolabel.text().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 38,
                                "end_lineno": 603,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/widgets/evaluate/owpredictions.py",
                            "type": "class",
                            "name": "OWPredictions",
                            "content": "class OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        n_predictors = len(self.predictors)\n        if not self.data and not n_predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        n_valid = len(self._non_errored_predictors())\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = f\"{len(self.data)} instances\" if self.data else \"No data\"\n        details += f\"\\n{n_predictors} models\" if n_predictors else \"No models\"\n        if n_valid != n_predictors:\n            details += f\" ({n_predictors - n_valid} failed)\"\n        self.info.set_input_summary(summary, details)\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_model = self.predictionsview.model()\n\n            # use ItemDelegate to style prediction values\n            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [style(predictions_model.data(predictions_model.index(i, j)))\n                       for j in range(predictions_model.columnCount())] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self.infolabel.text().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 38,
                            "end_lineno": 603,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 594,
                            "length": 6
                        },
                        "new_range": {
                            "start": 610,
                            "length": 8
                        },
                        "section": "class OWPredictions(OWWidget):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),",
                                "type": "context"
                            },
                            {
                                "content": "                              header_rows=1, header_columns=1)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "            self.report_table(\"Scores\", self.score_table.view)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def resizeEvent(self, event):",
                                "type": "context"
                            },
                            {
                                "content": "        super().resizeEvent(event)",
                                "type": "context"
                            },
                            {
                                "content": "        self._update_splitter()",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/evaluate/owpredictions.py",
                            "type": "method",
                            "name": "OWPredictions.send_report",
                            "content": "class OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        if not self.data and not self.predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = self._get_details()\n        self.info.set_input_summary(summary, details)\n\n    def _get_details(self):\n        n_predictors = len(self.predictors)\n        if self.data:\n            details = plural(\"{number} instance{s}\", len(self.data))\n        else:\n            details = \"No data\"\n        if n_predictors:\n            n_valid = len(self._non_errored_predictors())\n            details += plural(\"\\n{number} model{s}\", n_predictors)\n            if n_valid != n_predictors:\n                details += plural(\" ({number} failed)\", n_predictors - n_valid)\n        else:\n            details += \"\\nNo models\"\n        return details\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_view = self.predictionsview\n            predictions_model = predictions_view.model()\n\n            # use ItemDelegate to style prediction values\n            delegates = [predictions_view.itemDelegateForColumn(i)\n                         for i in range(predictions_model.columnCount())]\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [delegate.displayText(\n                          predictions_model.data(predictions_model.index(i, j)),\n                          QLocale())\n                       for j, delegate in enumerate(delegates)] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self._get_details().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n            self.report_table(\"Scores\", self.score_table.view)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 572,
                            "end_lineno": 613,
                            "parent": {
                                "file_name": "Orange/widgets/evaluate/owpredictions.py",
                                "type": "class",
                                "name": "OWPredictions",
                                "content": "class OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        if not self.data and not self.predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = self._get_details()\n        self.info.set_input_summary(summary, details)\n\n    def _get_details(self):\n        n_predictors = len(self.predictors)\n        if self.data:\n            details = plural(\"{number} instance{s}\", len(self.data))\n        else:\n            details = \"No data\"\n        if n_predictors:\n            n_valid = len(self._non_errored_predictors())\n            details += plural(\"\\n{number} model{s}\", n_predictors)\n            if n_valid != n_predictors:\n                details += plural(\" ({number} failed)\", n_predictors - n_valid)\n        else:\n            details += \"\\nNo models\"\n        return details\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_view = self.predictionsview\n            predictions_model = predictions_view.model()\n\n            # use ItemDelegate to style prediction values\n            delegates = [predictions_view.itemDelegateForColumn(i)\n                         for i in range(predictions_model.columnCount())]\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [delegate.displayText(\n                          predictions_model.data(predictions_model.index(i, j)),\n                          QLocale())\n                       for j, delegate in enumerate(delegates)] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self._get_details().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n            self.report_table(\"Scores\", self.score_table.view)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 40,
                                "end_lineno": 621,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/widgets/evaluate/owpredictions.py",
                            "type": "class",
                            "name": "OWPredictions",
                            "content": "class OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        if not self.data and not self.predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = self._get_details()\n        self.info.set_input_summary(summary, details)\n\n    def _get_details(self):\n        n_predictors = len(self.predictors)\n        if self.data:\n            details = plural(\"{number} instance{s}\", len(self.data))\n        else:\n            details = \"No data\"\n        if n_predictors:\n            n_valid = len(self._non_errored_predictors())\n            details += plural(\"\\n{number} model{s}\", n_predictors)\n            if n_valid != n_predictors:\n                details += plural(\" ({number} failed)\", n_predictors - n_valid)\n        else:\n            details += \"\\nNo models\"\n        return details\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_view = self.predictionsview\n            predictions_model = predictions_view.model()\n\n            # use ItemDelegate to style prediction values\n            delegates = [predictions_view.itemDelegateForColumn(i)\n                         for i in range(predictions_model.columnCount())]\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [delegate.displayText(\n                          predictions_model.data(predictions_model.index(i, j)),\n                          QLocale())\n                       for j, delegate in enumerate(delegates)] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self._get_details().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n            self.report_table(\"Scores\", self.score_table.view)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 40,
                            "end_lineno": 621,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "\"\"\"Tests for OWPredictions\"\"\"\nimport io\nfrom unittest.mock import Mock\n\nimport numpy as np\n\nfrom Orange.base import Model\nfrom Orange.classification import LogisticRegressionLearner\nfrom Orange.data.io import TabReader\nfrom Orange.widgets.tests.base import WidgetTest\nfrom Orange.widgets.evaluate.owpredictions import OWPredictions\nfrom Orange.widgets.evaluate.owcalibrationplot import OWCalibrationPlot\nfrom Orange.widgets.evaluate.owconfusionmatrix import OWConfusionMatrix\nfrom Orange.widgets.evaluate.owliftcurve import OWLiftCurve\nfrom Orange.widgets.evaluate.owrocanalysis import OWROCAnalysis\n\nfrom Orange.data import Table, Domain, DiscreteVariable\nfrom Orange.modelling import ConstantLearner, TreeLearner\nfrom Orange.evaluation import Results\nfrom Orange.widgets.tests.utils import excepthook_catch\nfrom Orange.widgets.utils.colorpalette import ColorPaletteGenerator\n\n\nclass TestOWPredictions(WidgetTest):\n\n    def setUp(self):\n        self.widget = self.create_widget(OWPredictions)  # type: OWPredictions\n        self.iris = Table(\"iris\")\n\n    def test_rowCount_from_model(self):\n        \"\"\"Don't crash if the bottom row is visible\"\"\"\n        self.send_signal(self.widget.Inputs.data, self.iris[:5])\n        self.widget.dataview.sizeHintForColumn(0)\n\n    def test_nan_target_input(self):\n        data = self.iris[::10].copy()\n        data.Y[1] = np.nan\n        yvec, _ = data.get_column_view(data.domain.class_var)\n        self.send_signal(self.widget.Inputs.data, data)\n        self.send_signal(self.widget.Inputs.predictors, ConstantLearner()(data), 1)\n        pred = self.get_output(self.widget.Outputs.predictions)\n        self.assertIsInstance(pred, Table)\n        np.testing.assert_array_equal(\n            yvec, pred.get_column_view(data.domain.class_var)[0])\n\n        evres = self.get_output(self.widget.Outputs.evaluation_results)\n        self.assertIsInstance(evres, Results)\n        self.assertIsInstance(evres.data, Table)\n        ev_yvec, _ = evres.data.get_column_view(data.domain.class_var)\n\n        self.assertTrue(np.all(~np.isnan(ev_yvec)))\n        self.assertTrue(np.all(~np.isnan(evres.actual)))\n\n        data.Y[:] = np.nan\n        self.send_signal(self.widget.Inputs.data, data)\n        evres = self.get_output(self.widget.Outputs.evaluation_results)\n        self.assertEqual(len(evres.data), 0)\n\n    def test_no_values_target(self):\n        train = Table(\"titanic\")\n        model = ConstantLearner()(train)\n        self.send_signal(self.widget.Inputs.predictors, model)\n        domain = Domain([DiscreteVariable(\"status\", values=(\"first\", \"third\")),\n                         DiscreteVariable(\"age\", values=(\"adult\", \"child\")),\n                         DiscreteVariable(\"sex\", values=(\"female\", \"male\"))],\n                        [DiscreteVariable(\"survived\", values=())])\n        test = Table(domain, np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]]),\n                     np.full((3, 1), np.nan))\n        self.send_signal(self.widget.Inputs.data, test)\n        pred = self.get_output(self.widget.Outputs.predictions)\n        self.assertEqual(len(pred), len(test))\n\n        results = self.get_output(self.widget.Outputs.evaluation_results)\n\n        cm_widget = self.create_widget(OWConfusionMatrix)\n        self.send_signal(cm_widget.Inputs.evaluation_results, results,\n                         widget=cm_widget)\n\n        ra_widget = self.create_widget(OWROCAnalysis)\n        self.send_signal(ra_widget.Inputs.evaluation_results, results,\n                         widget=ra_widget)\n\n        lc_widget = self.create_widget(OWLiftCurve)\n        self.send_signal(lc_widget.Inputs.evaluation_results, results,\n                         widget=lc_widget)\n\n        cp_widget = self.create_widget(OWCalibrationPlot)\n        self.send_signal(cp_widget.Inputs.evaluation_results, results,\n                         widget=cp_widget)\n\n    def test_mismatching_targets(self):\n        warning = self.widget.Warning\n\n        maj_iris = ConstantLearner()(self.iris)\n        dom = self.iris.domain\n        iris3 = self.iris.transform(Domain(dom[:3], dom[3]))\n        maj_iris3 = ConstantLearner()(iris3)\n\n        self.send_signal(self.widget.Inputs.predictors, maj_iris, 1)\n        self.send_signal(self.widget.Inputs.predictors, maj_iris3, 2)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.assertTrue(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.predictors, None, 2)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.predictors, maj_iris3, 2)\n        self.assertTrue(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n    def test_no_class_on_test(self):\n        \"\"\"Allow test data with no class\"\"\"\n        titanic = Table(\"titanic\")\n        majority_titanic = ConstantLearner()(titanic)\n\n        no_class = titanic.transform(Domain(titanic.domain.attributes, None))\n        self.send_signal(self.widget.Inputs.predictors, majority_titanic, 1)\n        self.send_signal(self.widget.Inputs.data, no_class)\n        out = self.get_output(self.widget.Outputs.predictions)\n        np.testing.assert_allclose(out.get_column_view(\"constant\")[0], 0)\n\n    def test_bad_data(self):\n        \"\"\"\n        Firstly it creates predictions with TreeLearner. Then sends predictions and\n        different data with different domain to Predictions widget. Those different\n        data and domain are similar to original data and domain but they have three\n        different target values instead of two.\n        GH-2129\n        \"\"\"\n        filestr1 = \"\"\"\\\n        age\\tsex\\tsurvived\n        d\\td\\td\n        \\t\\tclass\n        adult\\tmale\\tyes\n        adult\\tfemale\\tno\n        child\\tmale\\tyes\n        child\\tfemale\\tyes\n        \"\"\"\n        file1 = io.StringIO(filestr1)\n        table = TabReader(file1).read()\n        learner = TreeLearner()\n        tree = learner(table)\n\n        filestr2 = \"\"\"\\\n        age\\tsex\\tsurvived\n        d\\td\\td\n        \\t\\tclass\n        adult\\tmale\\tyes\n        adult\\tfemale\\tno\n        child\\tmale\\tyes\n        child\\tfemale\\tunknown\n        \"\"\"\n        file2 = io.StringIO(filestr2)\n        bad_table = TabReader(file2).read()\n\n        self.send_signal(self.widget.Inputs.predictors, tree, 1)\n\n        with excepthook_catch():\n            self.send_signal(self.widget.Inputs.data, bad_table)\n\n    def test_continuous_class(self):\n        data = Table(\"housing\")\n        cl_data = ConstantLearner()(data)\n        self.send_signal(self.widget.Inputs.predictors, cl_data, 1)\n        self.send_signal(self.widget.Inputs.data, data)\n\n    def test_predictor_fails(self):\n        titanic = Table(\"titanic\")\n        failing_model = ConstantLearner()(titanic)\n        failing_model.predict = Mock(side_effect=ValueError(\"foo\"))\n        self.send_signal(self.widget.Inputs.predictors, failing_model, 1)\n        self.send_signal(self.widget.Inputs.data, titanic)\n\n        model2 = ConstantLearner()(titanic)\n        self.send_signal(self.widget.Inputs.predictors, model2, 2)\n\n    def test_sort_matching(self):\n        def get_items_order(model):\n            n = pred_model.rowCount()\n            return [\n                pred_model.mapToSource(model.index(i, 0)).row()\n                for i in range(n)\n            ]\n\n        w = self.widget\n\n        titanic = Table(\"titanic\")\n        majority_titanic = LogisticRegressionLearner()(titanic)\n        self.send_signal(self.widget.Inputs.predictors, majority_titanic)\n        self.send_signal(self.widget.Inputs.data, titanic)\n\n        pred_model = w.predictionsview.model()\n        data_model = w.predictionsview.model()\n        n = pred_model.rowCount()\n\n        # no sort\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, list(range(n)))\n        self.assertListEqual(data_order, list(range(n)))\n\n        # sort by first column in prediction table\n        pred_model.sort(0)\n        w.predictionsview.horizontalHeader().sectionClicked.emit(0)\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, data_order)\n\n        # sort by second column in data table\n        data_model.sort(1)\n        w.dataview.horizontalHeader().sectionClicked.emit(0)\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, data_order)\n\n        # restore order\n        w.reset_button.click()\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, list(range(n)))\n        self.assertListEqual(data_order, list(range(n)))\n\n    def test_sort_predictions(self):\n        \"\"\"\n        Test whether sorting of probabilities by FilterSortProxy is correct.\n        \"\"\"\n        def get_items_order(model):\n            n = pred_model.rowCount()\n            return [\n                pred_model.mapToSource(model.index(i, 0)).row()\n                for i in range(n)\n            ]\n\n        log_reg_iris = LogisticRegressionLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, log_reg_iris)\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        _, log_reg_probs = log_reg_iris(self.iris, Model.ValueProbs)\n        # here I assume that classes are in order 0, 1, 2 in widget\n\n        pred_model = self.widget.predictionsview.model()\n        pred_model.sort(0)\n        widget_order = get_items_order(pred_model)\n\n        # correct order first sort by probs[:,0] then probs[:,1], ...\n        keys = tuple(\n            log_reg_probs[:, i] for i in range(\n                log_reg_probs.shape[1] - 1, -1, -1))\n        sort_order = np.lexsort(keys)\n        np.testing.assert_array_equal(widget_order, sort_order)\n\n    def test_reset_no_data(self):\n        \"\"\"\n        Check no error when resetting the view without model and data\n        \"\"\"\n        self.widget.reset_button.click()\n\n    def test_colors_same_domain(self):\n        \"\"\"\n        Test whether the color selection for values is correct.\n        \"\"\"\n        # pylint: disable=protected-access\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        # case 1: one same model\n        predictor_iris = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(\n            colors, self.iris.domain.class_var.colors)\n\n        # case 2: two same models\n        predictor_iris1 = ConstantLearner()(self.iris)\n        predictor_iris2 = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        # assume that colors have same order since values have same order\n        np.testing.assert_array_equal(\n            colors, self.iris.domain.class_var.colors)\n\n        # case 3: two same models - changed color order\n        idom = self.iris.domain\n        dom = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom.class_var.colors = dom.class_var.colors[::-1]\n        iris2 = self.iris.transform(dom)\n\n        predictor_iris1 = ConstantLearner()(iris2)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris2.domain.class_var.colors)\n\n    def test_colors_diff_domain(self):\n        \"\"\"\n        Test whether the color selection for values is correct.\n        \"\"\"\n        # pylint: disable=protected-access\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        # case 1: two domains one subset other\n        idom = self.iris.domain\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[:2])\n        )\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n        # case 2: two domains one subset other - different color order\n        idom = self.iris.domain\n        colors = idom.class_var.colors[::-1]\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[:2])\n        )\n        dom1.class_var.colors = colors\n        dom2.class_var.colors = colors[:2]\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n        # case 3: domain color, values miss-match - use default colors\n        idom = self.iris.domain\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom1.class_var.colors = dom1.class_var.colors[::-1]\n        iris1 = self.iris.transform(dom1)\n        iris2 = self.iris.transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, ColorPaletteGenerator.palette(3))\n\n        # case 4: two domains different values order, matching colors\n        idom = self.iris.domain\n        # this way we know that default colors are not used\n        colors = ColorPaletteGenerator.palette(5)[2:]\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[::-1])\n        )\n        dom1.class_var.colors = colors\n        dom2.class_var.colors = colors[::-1]  # colors mixed same than values\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n    def test_colors_continuous(self):\n        \"\"\"\n        When only continuous variables in predictor no color should be selected\n        we do not work with classes.\n        When we add one classifier there should be colors.\n        \"\"\"\n        # pylint: disable=protected-access\n        data = Table(\"housing\")\n        cl_data = ConstantLearner()(data)\n        self.send_signal(self.widget.Inputs.predictors, cl_data)\n        self.send_signal(self.widget.Inputs.data, data)\n        colors = self.widget._get_colors()\n        self.assertListEqual([], colors)\n\n        predictor_iris = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris, 1)\n        colors = self.widget._get_colors()\n        self.assertEqual(3, len(colors))\n\n\nif __name__ == \"__main__\":\n    import unittest\n    unittest.main()\n",
            "new_file_content": "\"\"\"Tests for OWPredictions\"\"\"\nimport io\nfrom unittest.mock import Mock\n\nimport numpy as np\n\nfrom Orange.base import Model\nfrom Orange.classification import LogisticRegressionLearner\nfrom Orange.data.io import TabReader\nfrom Orange.widgets.tests.base import WidgetTest\nfrom Orange.widgets.evaluate.owpredictions import OWPredictions\nfrom Orange.widgets.evaluate.owcalibrationplot import OWCalibrationPlot\nfrom Orange.widgets.evaluate.owconfusionmatrix import OWConfusionMatrix\nfrom Orange.widgets.evaluate.owliftcurve import OWLiftCurve\nfrom Orange.widgets.evaluate.owrocanalysis import OWROCAnalysis\n\nfrom Orange.data import Table, Domain, DiscreteVariable\nfrom Orange.modelling import ConstantLearner, TreeLearner\nfrom Orange.evaluation import Results\nfrom Orange.widgets.tests.utils import excepthook_catch\nfrom Orange.widgets.utils.colorpalette import ColorPaletteGenerator\n\n\nclass TestOWPredictions(WidgetTest):\n\n    def setUp(self):\n        self.widget = self.create_widget(OWPredictions)  # type: OWPredictions\n        self.iris = Table(\"iris\")\n\n    def test_rowCount_from_model(self):\n        \"\"\"Don't crash if the bottom row is visible\"\"\"\n        self.send_signal(self.widget.Inputs.data, self.iris[:5])\n        self.widget.dataview.sizeHintForColumn(0)\n\n    def test_nan_target_input(self):\n        data = self.iris[::10].copy()\n        data.Y[1] = np.nan\n        yvec, _ = data.get_column_view(data.domain.class_var)\n        self.send_signal(self.widget.Inputs.data, data)\n        self.send_signal(self.widget.Inputs.predictors, ConstantLearner()(data), 1)\n        pred = self.get_output(self.widget.Outputs.predictions)\n        self.assertIsInstance(pred, Table)\n        np.testing.assert_array_equal(\n            yvec, pred.get_column_view(data.domain.class_var)[0])\n\n        evres = self.get_output(self.widget.Outputs.evaluation_results)\n        self.assertIsInstance(evres, Results)\n        self.assertIsInstance(evres.data, Table)\n        ev_yvec, _ = evres.data.get_column_view(data.domain.class_var)\n\n        self.assertTrue(np.all(~np.isnan(ev_yvec)))\n        self.assertTrue(np.all(~np.isnan(evres.actual)))\n\n        data.Y[:] = np.nan\n        self.send_signal(self.widget.Inputs.data, data)\n        evres = self.get_output(self.widget.Outputs.evaluation_results)\n        self.assertEqual(len(evres.data), 0)\n\n    def test_no_values_target(self):\n        train = Table(\"titanic\")\n        model = ConstantLearner()(train)\n        self.send_signal(self.widget.Inputs.predictors, model)\n        domain = Domain([DiscreteVariable(\"status\", values=(\"first\", \"third\")),\n                         DiscreteVariable(\"age\", values=(\"adult\", \"child\")),\n                         DiscreteVariable(\"sex\", values=(\"female\", \"male\"))],\n                        [DiscreteVariable(\"survived\", values=())])\n        test = Table(domain, np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]]),\n                     np.full((3, 1), np.nan))\n        self.send_signal(self.widget.Inputs.data, test)\n        pred = self.get_output(self.widget.Outputs.predictions)\n        self.assertEqual(len(pred), len(test))\n\n        results = self.get_output(self.widget.Outputs.evaluation_results)\n\n        cm_widget = self.create_widget(OWConfusionMatrix)\n        self.send_signal(cm_widget.Inputs.evaluation_results, results,\n                         widget=cm_widget)\n\n        ra_widget = self.create_widget(OWROCAnalysis)\n        self.send_signal(ra_widget.Inputs.evaluation_results, results,\n                         widget=ra_widget)\n\n        lc_widget = self.create_widget(OWLiftCurve)\n        self.send_signal(lc_widget.Inputs.evaluation_results, results,\n                         widget=lc_widget)\n\n        cp_widget = self.create_widget(OWCalibrationPlot)\n        self.send_signal(cp_widget.Inputs.evaluation_results, results,\n                         widget=cp_widget)\n\n    def test_mismatching_targets(self):\n        warning = self.widget.Warning\n\n        maj_iris = ConstantLearner()(self.iris)\n        dom = self.iris.domain\n        iris3 = self.iris.transform(Domain(dom[:3], dom[3]))\n        maj_iris3 = ConstantLearner()(iris3)\n\n        self.send_signal(self.widget.Inputs.predictors, maj_iris, 1)\n        self.send_signal(self.widget.Inputs.predictors, maj_iris3, 2)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.assertTrue(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.predictors, None, 2)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.predictors, maj_iris3, 2)\n        self.assertTrue(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n    def test_no_class_on_test(self):\n        \"\"\"Allow test data with no class\"\"\"\n        titanic = Table(\"titanic\")\n        majority_titanic = ConstantLearner()(titanic)\n\n        no_class = titanic.transform(Domain(titanic.domain.attributes, None))\n        self.send_signal(self.widget.Inputs.predictors, majority_titanic, 1)\n        self.send_signal(self.widget.Inputs.data, no_class)\n        out = self.get_output(self.widget.Outputs.predictions)\n        np.testing.assert_allclose(out.get_column_view(\"constant\")[0], 0)\n\n    def test_bad_data(self):\n        \"\"\"\n        Firstly it creates predictions with TreeLearner. Then sends predictions and\n        different data with different domain to Predictions widget. Those different\n        data and domain are similar to original data and domain but they have three\n        different target values instead of two.\n        GH-2129\n        \"\"\"\n        filestr1 = \"\"\"\\\n        age\\tsex\\tsurvived\n        d\\td\\td\n        \\t\\tclass\n        adult\\tmale\\tyes\n        adult\\tfemale\\tno\n        child\\tmale\\tyes\n        child\\tfemale\\tyes\n        \"\"\"\n        file1 = io.StringIO(filestr1)\n        table = TabReader(file1).read()\n        learner = TreeLearner()\n        tree = learner(table)\n\n        filestr2 = \"\"\"\\\n        age\\tsex\\tsurvived\n        d\\td\\td\n        \\t\\tclass\n        adult\\tmale\\tyes\n        adult\\tfemale\\tno\n        child\\tmale\\tyes\n        child\\tfemale\\tunknown\n        \"\"\"\n        file2 = io.StringIO(filestr2)\n        bad_table = TabReader(file2).read()\n\n        self.send_signal(self.widget.Inputs.predictors, tree, 1)\n\n        with excepthook_catch():\n            self.send_signal(self.widget.Inputs.data, bad_table)\n\n    def test_continuous_class(self):\n        data = Table(\"housing\")\n        cl_data = ConstantLearner()(data)\n        self.send_signal(self.widget.Inputs.predictors, cl_data, 1)\n        self.send_signal(self.widget.Inputs.data, data)\n\n    def test_predictor_fails(self):\n        titanic = Table(\"titanic\")\n        failing_model = ConstantLearner()(titanic)\n        failing_model.predict = Mock(side_effect=ValueError(\"foo\"))\n        self.send_signal(self.widget.Inputs.predictors, failing_model, 1)\n        self.send_signal(self.widget.Inputs.data, titanic)\n\n        model2 = ConstantLearner()(titanic)\n        self.send_signal(self.widget.Inputs.predictors, model2, 2)\n\n    def test_sort_matching(self):\n        def get_items_order(model):\n            n = pred_model.rowCount()\n            return [\n                pred_model.mapToSource(model.index(i, 0)).row()\n                for i in range(n)\n            ]\n\n        w = self.widget\n\n        titanic = Table(\"titanic\")\n        majority_titanic = LogisticRegressionLearner()(titanic)\n        self.send_signal(self.widget.Inputs.predictors, majority_titanic)\n        self.send_signal(self.widget.Inputs.data, titanic)\n\n        pred_model = w.predictionsview.model()\n        data_model = w.predictionsview.model()\n        n = pred_model.rowCount()\n\n        # no sort\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, list(range(n)))\n        self.assertListEqual(data_order, list(range(n)))\n\n        # sort by first column in prediction table\n        pred_model.sort(0)\n        w.predictionsview.horizontalHeader().sectionClicked.emit(0)\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, data_order)\n\n        # sort by second column in data table\n        data_model.sort(1)\n        w.dataview.horizontalHeader().sectionClicked.emit(0)\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, data_order)\n\n        # restore order\n        w.reset_button.click()\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, list(range(n)))\n        self.assertListEqual(data_order, list(range(n)))\n\n    def test_sort_predictions(self):\n        \"\"\"\n        Test whether sorting of probabilities by FilterSortProxy is correct.\n        \"\"\"\n        def get_items_order(model):\n            n = pred_model.rowCount()\n            return [\n                pred_model.mapToSource(model.index(i, 0)).row()\n                for i in range(n)\n            ]\n\n        log_reg_iris = LogisticRegressionLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, log_reg_iris)\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        _, log_reg_probs = log_reg_iris(self.iris, Model.ValueProbs)\n        # here I assume that classes are in order 0, 1, 2 in widget\n\n        pred_model = self.widget.predictionsview.model()\n        pred_model.sort(0)\n        widget_order = get_items_order(pred_model)\n\n        # correct order first sort by probs[:,0] then probs[:,1], ...\n        keys = tuple(\n            log_reg_probs[:, i] for i in range(\n                log_reg_probs.shape[1] - 1, -1, -1))\n        sort_order = np.lexsort(keys)\n        np.testing.assert_array_equal(widget_order, sort_order)\n\n    def test_reset_no_data(self):\n        \"\"\"\n        Check no error when resetting the view without model and data\n        \"\"\"\n        self.widget.reset_button.click()\n\n    def test_colors_same_domain(self):\n        \"\"\"\n        Test whether the color selection for values is correct.\n        \"\"\"\n        # pylint: disable=protected-access\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        # case 1: one same model\n        predictor_iris = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(\n            colors, self.iris.domain.class_var.colors)\n\n        # case 2: two same models\n        predictor_iris1 = ConstantLearner()(self.iris)\n        predictor_iris2 = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        # assume that colors have same order since values have same order\n        np.testing.assert_array_equal(\n            colors, self.iris.domain.class_var.colors)\n\n        # case 3: two same models - changed color order\n        idom = self.iris.domain\n        dom = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom.class_var.colors = dom.class_var.colors[::-1]\n        iris2 = self.iris.transform(dom)\n\n        predictor_iris1 = ConstantLearner()(iris2)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris2.domain.class_var.colors)\n\n    def test_colors_diff_domain(self):\n        \"\"\"\n        Test whether the color selection for values is correct.\n        \"\"\"\n        # pylint: disable=protected-access\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        # case 1: two domains one subset other\n        idom = self.iris.domain\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[:2])\n        )\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n        # case 2: two domains one subset other - different color order\n        idom = self.iris.domain\n        colors = idom.class_var.colors[::-1]\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[:2])\n        )\n        dom1.class_var.colors = colors\n        dom2.class_var.colors = colors[:2]\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n        # case 3: domain color, values miss-match - use default colors\n        idom = self.iris.domain\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom1.class_var.colors = dom1.class_var.colors[::-1]\n        iris1 = self.iris.transform(dom1)\n        iris2 = self.iris.transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, ColorPaletteGenerator.palette(3))\n\n        # case 4: two domains different values order, matching colors\n        idom = self.iris.domain\n        # this way we know that default colors are not used\n        colors = ColorPaletteGenerator.palette(5)[2:]\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[::-1])\n        )\n        dom1.class_var.colors = colors\n        dom2.class_var.colors = colors[::-1]  # colors mixed same than values\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n    def test_colors_continuous(self):\n        \"\"\"\n        When only continuous variables in predictor no color should be selected\n        we do not work with classes.\n        When we add one classifier there should be colors.\n        \"\"\"\n        # pylint: disable=protected-access\n        data = Table(\"housing\")\n        cl_data = ConstantLearner()(data)\n        self.send_signal(self.widget.Inputs.predictors, cl_data)\n        self.send_signal(self.widget.Inputs.data, data)\n        colors = self.widget._get_colors()\n        self.assertListEqual([], colors)\n\n        predictor_iris = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris, 1)\n        colors = self.widget._get_colors()\n        self.assertEqual(3, len(colors))\n\n        self.widget.send_report()  # just a quick check that it doesn't crash\n\n\nif __name__ == \"__main__\":\n    import unittest\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "Orange/widgets/evaluate/tests/test_owpredictions.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "2bf0ec31e",
                "new_commit_hash": "f746ea27c",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/widgets/evaluate/tests/test_owpredictions.py"
            },
            "plus_file": {
                "path": "b/Orange/widgets/evaluate/tests/test_owpredictions.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 412,
                            "length": 6
                        },
                        "new_range": {
                            "start": 412,
                            "length": 8
                        },
                        "section": "class TestOWPredictions(WidgetTest):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        colors = self.widget._get_colors()",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(3, len(colors))",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        self.widget.send_report()  # just a quick check that it doesn't crash",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "if __name__ == \"__main__\":",
                                "type": "context"
                            },
                            {
                                "content": "    import unittest",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/evaluate/tests/test_owpredictions.py",
                            "type": "class",
                            "name": "TestOWPredictions",
                            "content": "class TestOWPredictions(WidgetTest):\n\n    def setUp(self):\n        self.widget = self.create_widget(OWPredictions)  # type: OWPredictions\n        self.iris = Table(\"iris\")\n\n    def test_rowCount_from_model(self):\n        \"\"\"Don't crash if the bottom row is visible\"\"\"\n        self.send_signal(self.widget.Inputs.data, self.iris[:5])\n        self.widget.dataview.sizeHintForColumn(0)\n\n    def test_nan_target_input(self):\n        data = self.iris[::10].copy()\n        data.Y[1] = np.nan\n        yvec, _ = data.get_column_view(data.domain.class_var)\n        self.send_signal(self.widget.Inputs.data, data)\n        self.send_signal(self.widget.Inputs.predictors, ConstantLearner()(data), 1)\n        pred = self.get_output(self.widget.Outputs.predictions)\n        self.assertIsInstance(pred, Table)\n        np.testing.assert_array_equal(\n            yvec, pred.get_column_view(data.domain.class_var)[0])\n\n        evres = self.get_output(self.widget.Outputs.evaluation_results)\n        self.assertIsInstance(evres, Results)\n        self.assertIsInstance(evres.data, Table)\n        ev_yvec, _ = evres.data.get_column_view(data.domain.class_var)\n\n        self.assertTrue(np.all(~np.isnan(ev_yvec)))\n        self.assertTrue(np.all(~np.isnan(evres.actual)))\n\n        data.Y[:] = np.nan\n        self.send_signal(self.widget.Inputs.data, data)\n        evres = self.get_output(self.widget.Outputs.evaluation_results)\n        self.assertEqual(len(evres.data), 0)\n\n    def test_no_values_target(self):\n        train = Table(\"titanic\")\n        model = ConstantLearner()(train)\n        self.send_signal(self.widget.Inputs.predictors, model)\n        domain = Domain([DiscreteVariable(\"status\", values=(\"first\", \"third\")),\n                         DiscreteVariable(\"age\", values=(\"adult\", \"child\")),\n                         DiscreteVariable(\"sex\", values=(\"female\", \"male\"))],\n                        [DiscreteVariable(\"survived\", values=())])\n        test = Table(domain, np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]]),\n                     np.full((3, 1), np.nan))\n        self.send_signal(self.widget.Inputs.data, test)\n        pred = self.get_output(self.widget.Outputs.predictions)\n        self.assertEqual(len(pred), len(test))\n\n        results = self.get_output(self.widget.Outputs.evaluation_results)\n\n        cm_widget = self.create_widget(OWConfusionMatrix)\n        self.send_signal(cm_widget.Inputs.evaluation_results, results,\n                         widget=cm_widget)\n\n        ra_widget = self.create_widget(OWROCAnalysis)\n        self.send_signal(ra_widget.Inputs.evaluation_results, results,\n                         widget=ra_widget)\n\n        lc_widget = self.create_widget(OWLiftCurve)\n        self.send_signal(lc_widget.Inputs.evaluation_results, results,\n                         widget=lc_widget)\n\n        cp_widget = self.create_widget(OWCalibrationPlot)\n        self.send_signal(cp_widget.Inputs.evaluation_results, results,\n                         widget=cp_widget)\n\n    def test_mismatching_targets(self):\n        warning = self.widget.Warning\n\n        maj_iris = ConstantLearner()(self.iris)\n        dom = self.iris.domain\n        iris3 = self.iris.transform(Domain(dom[:3], dom[3]))\n        maj_iris3 = ConstantLearner()(iris3)\n\n        self.send_signal(self.widget.Inputs.predictors, maj_iris, 1)\n        self.send_signal(self.widget.Inputs.predictors, maj_iris3, 2)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.assertTrue(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.predictors, None, 2)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.predictors, maj_iris3, 2)\n        self.assertTrue(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n    def test_no_class_on_test(self):\n        \"\"\"Allow test data with no class\"\"\"\n        titanic = Table(\"titanic\")\n        majority_titanic = ConstantLearner()(titanic)\n\n        no_class = titanic.transform(Domain(titanic.domain.attributes, None))\n        self.send_signal(self.widget.Inputs.predictors, majority_titanic, 1)\n        self.send_signal(self.widget.Inputs.data, no_class)\n        out = self.get_output(self.widget.Outputs.predictions)\n        np.testing.assert_allclose(out.get_column_view(\"constant\")[0], 0)\n\n    def test_bad_data(self):\n        \"\"\"\n        Firstly it creates predictions with TreeLearner. Then sends predictions and\n        different data with different domain to Predictions widget. Those different\n        data and domain are similar to original data and domain but they have three\n        different target values instead of two.\n        GH-2129\n        \"\"\"\n        filestr1 = \"\"\"\\\n        age\\tsex\\tsurvived\n        d\\td\\td\n        \\t\\tclass\n        adult\\tmale\\tyes\n        adult\\tfemale\\tno\n        child\\tmale\\tyes\n        child\\tfemale\\tyes\n        \"\"\"\n        file1 = io.StringIO(filestr1)\n        table = TabReader(file1).read()\n        learner = TreeLearner()\n        tree = learner(table)\n\n        filestr2 = \"\"\"\\\n        age\\tsex\\tsurvived\n        d\\td\\td\n        \\t\\tclass\n        adult\\tmale\\tyes\n        adult\\tfemale\\tno\n        child\\tmale\\tyes\n        child\\tfemale\\tunknown\n        \"\"\"\n        file2 = io.StringIO(filestr2)\n        bad_table = TabReader(file2).read()\n\n        self.send_signal(self.widget.Inputs.predictors, tree, 1)\n\n        with excepthook_catch():\n            self.send_signal(self.widget.Inputs.data, bad_table)\n\n    def test_continuous_class(self):\n        data = Table(\"housing\")\n        cl_data = ConstantLearner()(data)\n        self.send_signal(self.widget.Inputs.predictors, cl_data, 1)\n        self.send_signal(self.widget.Inputs.data, data)\n\n    def test_predictor_fails(self):\n        titanic = Table(\"titanic\")\n        failing_model = ConstantLearner()(titanic)\n        failing_model.predict = Mock(side_effect=ValueError(\"foo\"))\n        self.send_signal(self.widget.Inputs.predictors, failing_model, 1)\n        self.send_signal(self.widget.Inputs.data, titanic)\n\n        model2 = ConstantLearner()(titanic)\n        self.send_signal(self.widget.Inputs.predictors, model2, 2)\n\n    def test_sort_matching(self):\n        def get_items_order(model):\n            n = pred_model.rowCount()\n            return [\n                pred_model.mapToSource(model.index(i, 0)).row()\n                for i in range(n)\n            ]\n\n        w = self.widget\n\n        titanic = Table(\"titanic\")\n        majority_titanic = LogisticRegressionLearner()(titanic)\n        self.send_signal(self.widget.Inputs.predictors, majority_titanic)\n        self.send_signal(self.widget.Inputs.data, titanic)\n\n        pred_model = w.predictionsview.model()\n        data_model = w.predictionsview.model()\n        n = pred_model.rowCount()\n\n        # no sort\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, list(range(n)))\n        self.assertListEqual(data_order, list(range(n)))\n\n        # sort by first column in prediction table\n        pred_model.sort(0)\n        w.predictionsview.horizontalHeader().sectionClicked.emit(0)\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, data_order)\n\n        # sort by second column in data table\n        data_model.sort(1)\n        w.dataview.horizontalHeader().sectionClicked.emit(0)\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, data_order)\n\n        # restore order\n        w.reset_button.click()\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, list(range(n)))\n        self.assertListEqual(data_order, list(range(n)))\n\n    def test_sort_predictions(self):\n        \"\"\"\n        Test whether sorting of probabilities by FilterSortProxy is correct.\n        \"\"\"\n        def get_items_order(model):\n            n = pred_model.rowCount()\n            return [\n                pred_model.mapToSource(model.index(i, 0)).row()\n                for i in range(n)\n            ]\n\n        log_reg_iris = LogisticRegressionLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, log_reg_iris)\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        _, log_reg_probs = log_reg_iris(self.iris, Model.ValueProbs)\n        # here I assume that classes are in order 0, 1, 2 in widget\n\n        pred_model = self.widget.predictionsview.model()\n        pred_model.sort(0)\n        widget_order = get_items_order(pred_model)\n\n        # correct order first sort by probs[:,0] then probs[:,1], ...\n        keys = tuple(\n            log_reg_probs[:, i] for i in range(\n                log_reg_probs.shape[1] - 1, -1, -1))\n        sort_order = np.lexsort(keys)\n        np.testing.assert_array_equal(widget_order, sort_order)\n\n    def test_reset_no_data(self):\n        \"\"\"\n        Check no error when resetting the view without model and data\n        \"\"\"\n        self.widget.reset_button.click()\n\n    def test_colors_same_domain(self):\n        \"\"\"\n        Test whether the color selection for values is correct.\n        \"\"\"\n        # pylint: disable=protected-access\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        # case 1: one same model\n        predictor_iris = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(\n            colors, self.iris.domain.class_var.colors)\n\n        # case 2: two same models\n        predictor_iris1 = ConstantLearner()(self.iris)\n        predictor_iris2 = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        # assume that colors have same order since values have same order\n        np.testing.assert_array_equal(\n            colors, self.iris.domain.class_var.colors)\n\n        # case 3: two same models - changed color order\n        idom = self.iris.domain\n        dom = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom.class_var.colors = dom.class_var.colors[::-1]\n        iris2 = self.iris.transform(dom)\n\n        predictor_iris1 = ConstantLearner()(iris2)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris2.domain.class_var.colors)\n\n    def test_colors_diff_domain(self):\n        \"\"\"\n        Test whether the color selection for values is correct.\n        \"\"\"\n        # pylint: disable=protected-access\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        # case 1: two domains one subset other\n        idom = self.iris.domain\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[:2])\n        )\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n        # case 2: two domains one subset other - different color order\n        idom = self.iris.domain\n        colors = idom.class_var.colors[::-1]\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[:2])\n        )\n        dom1.class_var.colors = colors\n        dom2.class_var.colors = colors[:2]\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n        # case 3: domain color, values miss-match - use default colors\n        idom = self.iris.domain\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom1.class_var.colors = dom1.class_var.colors[::-1]\n        iris1 = self.iris.transform(dom1)\n        iris2 = self.iris.transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, ColorPaletteGenerator.palette(3))\n\n        # case 4: two domains different values order, matching colors\n        idom = self.iris.domain\n        # this way we know that default colors are not used\n        colors = ColorPaletteGenerator.palette(5)[2:]\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[::-1])\n        )\n        dom1.class_var.colors = colors\n        dom2.class_var.colors = colors[::-1]  # colors mixed same than values\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n    def test_colors_continuous(self):\n        \"\"\"\n        When only continuous variables in predictor no color should be selected\n        we do not work with classes.\n        When we add one classifier there should be colors.\n        \"\"\"\n        # pylint: disable=protected-access\n        data = Table(\"housing\")\n        cl_data = ConstantLearner()(data)\n        self.send_signal(self.widget.Inputs.predictors, cl_data)\n        self.send_signal(self.widget.Inputs.data, data)\n        colors = self.widget._get_colors()\n        self.assertListEqual([], colors)\n\n        predictor_iris = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris, 1)\n        colors = self.widget._get_colors()\n        self.assertEqual(3, len(colors))\n\n        self.widget.send_report()",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 24,
                            "end_lineno": 415,
                            "parent": null
                        },
                        {
                            "file_name": "Orange/widgets/evaluate/tests/test_owpredictions.py",
                            "type": "method",
                            "name": "TestOWPredictions.test_colors_continuous",
                            "content": "class TestOWPredictions(WidgetTest):\n\n    def setUp(self):\n        self.widget = self.create_widget(OWPredictions)  # type: OWPredictions\n        self.iris = Table(\"iris\")\n\n    def test_rowCount_from_model(self):\n        \"\"\"Don't crash if the bottom row is visible\"\"\"\n        self.send_signal(self.widget.Inputs.data, self.iris[:5])\n        self.widget.dataview.sizeHintForColumn(0)\n\n    def test_nan_target_input(self):\n        data = self.iris[::10].copy()\n        data.Y[1] = np.nan\n        yvec, _ = data.get_column_view(data.domain.class_var)\n        self.send_signal(self.widget.Inputs.data, data)\n        self.send_signal(self.widget.Inputs.predictors, ConstantLearner()(data), 1)\n        pred = self.get_output(self.widget.Outputs.predictions)\n        self.assertIsInstance(pred, Table)\n        np.testing.assert_array_equal(\n            yvec, pred.get_column_view(data.domain.class_var)[0])\n\n        evres = self.get_output(self.widget.Outputs.evaluation_results)\n        self.assertIsInstance(evres, Results)\n        self.assertIsInstance(evres.data, Table)\n        ev_yvec, _ = evres.data.get_column_view(data.domain.class_var)\n\n        self.assertTrue(np.all(~np.isnan(ev_yvec)))\n        self.assertTrue(np.all(~np.isnan(evres.actual)))\n\n        data.Y[:] = np.nan\n        self.send_signal(self.widget.Inputs.data, data)\n        evres = self.get_output(self.widget.Outputs.evaluation_results)\n        self.assertEqual(len(evres.data), 0)\n\n    def test_no_values_target(self):\n        train = Table(\"titanic\")\n        model = ConstantLearner()(train)\n        self.send_signal(self.widget.Inputs.predictors, model)\n        domain = Domain([DiscreteVariable(\"status\", values=(\"first\", \"third\")),\n                         DiscreteVariable(\"age\", values=(\"adult\", \"child\")),\n                         DiscreteVariable(\"sex\", values=(\"female\", \"male\"))],\n                        [DiscreteVariable(\"survived\", values=())])\n        test = Table(domain, np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]]),\n                     np.full((3, 1), np.nan))\n        self.send_signal(self.widget.Inputs.data, test)\n        pred = self.get_output(self.widget.Outputs.predictions)\n        self.assertEqual(len(pred), len(test))\n\n        results = self.get_output(self.widget.Outputs.evaluation_results)\n\n        cm_widget = self.create_widget(OWConfusionMatrix)\n        self.send_signal(cm_widget.Inputs.evaluation_results, results,\n                         widget=cm_widget)\n\n        ra_widget = self.create_widget(OWROCAnalysis)\n        self.send_signal(ra_widget.Inputs.evaluation_results, results,\n                         widget=ra_widget)\n\n        lc_widget = self.create_widget(OWLiftCurve)\n        self.send_signal(lc_widget.Inputs.evaluation_results, results,\n                         widget=lc_widget)\n\n        cp_widget = self.create_widget(OWCalibrationPlot)\n        self.send_signal(cp_widget.Inputs.evaluation_results, results,\n                         widget=cp_widget)\n\n    def test_mismatching_targets(self):\n        warning = self.widget.Warning\n\n        maj_iris = ConstantLearner()(self.iris)\n        dom = self.iris.domain\n        iris3 = self.iris.transform(Domain(dom[:3], dom[3]))\n        maj_iris3 = ConstantLearner()(iris3)\n\n        self.send_signal(self.widget.Inputs.predictors, maj_iris, 1)\n        self.send_signal(self.widget.Inputs.predictors, maj_iris3, 2)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.assertTrue(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.predictors, None, 2)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.predictors, maj_iris3, 2)\n        self.assertTrue(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n    def test_no_class_on_test(self):\n        \"\"\"Allow test data with no class\"\"\"\n        titanic = Table(\"titanic\")\n        majority_titanic = ConstantLearner()(titanic)\n\n        no_class = titanic.transform(Domain(titanic.domain.attributes, None))\n        self.send_signal(self.widget.Inputs.predictors, majority_titanic, 1)\n        self.send_signal(self.widget.Inputs.data, no_class)\n        out = self.get_output(self.widget.Outputs.predictions)\n        np.testing.assert_allclose(out.get_column_view(\"constant\")[0], 0)\n\n    def test_bad_data(self):\n        \"\"\"\n        Firstly it creates predictions with TreeLearner. Then sends predictions and\n        different data with different domain to Predictions widget. Those different\n        data and domain are similar to original data and domain but they have three\n        different target values instead of two.\n        GH-2129\n        \"\"\"\n        filestr1 = \"\"\"\\\n        age\\tsex\\tsurvived\n        d\\td\\td\n        \\t\\tclass\n        adult\\tmale\\tyes\n        adult\\tfemale\\tno\n        child\\tmale\\tyes\n        child\\tfemale\\tyes\n        \"\"\"\n        file1 = io.StringIO(filestr1)\n        table = TabReader(file1).read()\n        learner = TreeLearner()\n        tree = learner(table)\n\n        filestr2 = \"\"\"\\\n        age\\tsex\\tsurvived\n        d\\td\\td\n        \\t\\tclass\n        adult\\tmale\\tyes\n        adult\\tfemale\\tno\n        child\\tmale\\tyes\n        child\\tfemale\\tunknown\n        \"\"\"\n        file2 = io.StringIO(filestr2)\n        bad_table = TabReader(file2).read()\n\n        self.send_signal(self.widget.Inputs.predictors, tree, 1)\n\n        with excepthook_catch():\n            self.send_signal(self.widget.Inputs.data, bad_table)\n\n    def test_continuous_class(self):\n        data = Table(\"housing\")\n        cl_data = ConstantLearner()(data)\n        self.send_signal(self.widget.Inputs.predictors, cl_data, 1)\n        self.send_signal(self.widget.Inputs.data, data)\n\n    def test_predictor_fails(self):\n        titanic = Table(\"titanic\")\n        failing_model = ConstantLearner()(titanic)\n        failing_model.predict = Mock(side_effect=ValueError(\"foo\"))\n        self.send_signal(self.widget.Inputs.predictors, failing_model, 1)\n        self.send_signal(self.widget.Inputs.data, titanic)\n\n        model2 = ConstantLearner()(titanic)\n        self.send_signal(self.widget.Inputs.predictors, model2, 2)\n\n    def test_sort_matching(self):\n        def get_items_order(model):\n            n = pred_model.rowCount()\n            return [\n                pred_model.mapToSource(model.index(i, 0)).row()\n                for i in range(n)\n            ]\n\n        w = self.widget\n\n        titanic = Table(\"titanic\")\n        majority_titanic = LogisticRegressionLearner()(titanic)\n        self.send_signal(self.widget.Inputs.predictors, majority_titanic)\n        self.send_signal(self.widget.Inputs.data, titanic)\n\n        pred_model = w.predictionsview.model()\n        data_model = w.predictionsview.model()\n        n = pred_model.rowCount()\n\n        # no sort\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, list(range(n)))\n        self.assertListEqual(data_order, list(range(n)))\n\n        # sort by first column in prediction table\n        pred_model.sort(0)\n        w.predictionsview.horizontalHeader().sectionClicked.emit(0)\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, data_order)\n\n        # sort by second column in data table\n        data_model.sort(1)\n        w.dataview.horizontalHeader().sectionClicked.emit(0)\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, data_order)\n\n        # restore order\n        w.reset_button.click()\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, list(range(n)))\n        self.assertListEqual(data_order, list(range(n)))\n\n    def test_sort_predictions(self):\n        \"\"\"\n        Test whether sorting of probabilities by FilterSortProxy is correct.\n        \"\"\"\n        def get_items_order(model):\n            n = pred_model.rowCount()\n            return [\n                pred_model.mapToSource(model.index(i, 0)).row()\n                for i in range(n)\n            ]\n\n        log_reg_iris = LogisticRegressionLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, log_reg_iris)\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        _, log_reg_probs = log_reg_iris(self.iris, Model.ValueProbs)\n        # here I assume that classes are in order 0, 1, 2 in widget\n\n        pred_model = self.widget.predictionsview.model()\n        pred_model.sort(0)\n        widget_order = get_items_order(pred_model)\n\n        # correct order first sort by probs[:,0] then probs[:,1], ...\n        keys = tuple(\n            log_reg_probs[:, i] for i in range(\n                log_reg_probs.shape[1] - 1, -1, -1))\n        sort_order = np.lexsort(keys)\n        np.testing.assert_array_equal(widget_order, sort_order)\n\n    def test_reset_no_data(self):\n        \"\"\"\n        Check no error when resetting the view without model and data\n        \"\"\"\n        self.widget.reset_button.click()\n\n    def test_colors_same_domain(self):\n        \"\"\"\n        Test whether the color selection for values is correct.\n        \"\"\"\n        # pylint: disable=protected-access\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        # case 1: one same model\n        predictor_iris = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(\n            colors, self.iris.domain.class_var.colors)\n\n        # case 2: two same models\n        predictor_iris1 = ConstantLearner()(self.iris)\n        predictor_iris2 = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        # assume that colors have same order since values have same order\n        np.testing.assert_array_equal(\n            colors, self.iris.domain.class_var.colors)\n\n        # case 3: two same models - changed color order\n        idom = self.iris.domain\n        dom = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom.class_var.colors = dom.class_var.colors[::-1]\n        iris2 = self.iris.transform(dom)\n\n        predictor_iris1 = ConstantLearner()(iris2)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris2.domain.class_var.colors)\n\n    def test_colors_diff_domain(self):\n        \"\"\"\n        Test whether the color selection for values is correct.\n        \"\"\"\n        # pylint: disable=protected-access\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        # case 1: two domains one subset other\n        idom = self.iris.domain\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[:2])\n        )\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n        # case 2: two domains one subset other - different color order\n        idom = self.iris.domain\n        colors = idom.class_var.colors[::-1]\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[:2])\n        )\n        dom1.class_var.colors = colors\n        dom2.class_var.colors = colors[:2]\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n        # case 3: domain color, values miss-match - use default colors\n        idom = self.iris.domain\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom1.class_var.colors = dom1.class_var.colors[::-1]\n        iris1 = self.iris.transform(dom1)\n        iris2 = self.iris.transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, ColorPaletteGenerator.palette(3))\n\n        # case 4: two domains different values order, matching colors\n        idom = self.iris.domain\n        # this way we know that default colors are not used\n        colors = ColorPaletteGenerator.palette(5)[2:]\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[::-1])\n        )\n        dom1.class_var.colors = colors\n        dom2.class_var.colors = colors[::-1]  # colors mixed same than values\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n    def test_colors_continuous(self):\n        \"\"\"\n        When only continuous variables in predictor no color should be selected\n        we do not work with classes.\n        When we add one classifier there should be colors.\n        \"\"\"\n        # pylint: disable=protected-access\n        data = Table(\"housing\")\n        cl_data = ConstantLearner()(data)\n        self.send_signal(self.widget.Inputs.predictors, cl_data)\n        self.send_signal(self.widget.Inputs.data, data)\n        colors = self.widget._get_colors()\n        self.assertListEqual([], colors)\n\n        predictor_iris = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris, 1)\n        colors = self.widget._get_colors()\n        self.assertEqual(3, len(colors))\n\n        self.widget.send_report()",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 396,
                            "end_lineno": 415,
                            "parent": {
                                "file_name": "Orange/widgets/evaluate/tests/test_owpredictions.py",
                                "type": "class",
                                "name": "TestOWPredictions",
                                "content": "class TestOWPredictions(WidgetTest):\n\n    def setUp(self):\n        self.widget = self.create_widget(OWPredictions)  # type: OWPredictions\n        self.iris = Table(\"iris\")\n\n    def test_rowCount_from_model(self):\n        \"\"\"Don't crash if the bottom row is visible\"\"\"\n        self.send_signal(self.widget.Inputs.data, self.iris[:5])\n        self.widget.dataview.sizeHintForColumn(0)\n\n    def test_nan_target_input(self):\n        data = self.iris[::10].copy()\n        data.Y[1] = np.nan\n        yvec, _ = data.get_column_view(data.domain.class_var)\n        self.send_signal(self.widget.Inputs.data, data)\n        self.send_signal(self.widget.Inputs.predictors, ConstantLearner()(data), 1)\n        pred = self.get_output(self.widget.Outputs.predictions)\n        self.assertIsInstance(pred, Table)\n        np.testing.assert_array_equal(\n            yvec, pred.get_column_view(data.domain.class_var)[0])\n\n        evres = self.get_output(self.widget.Outputs.evaluation_results)\n        self.assertIsInstance(evres, Results)\n        self.assertIsInstance(evres.data, Table)\n        ev_yvec, _ = evres.data.get_column_view(data.domain.class_var)\n\n        self.assertTrue(np.all(~np.isnan(ev_yvec)))\n        self.assertTrue(np.all(~np.isnan(evres.actual)))\n\n        data.Y[:] = np.nan\n        self.send_signal(self.widget.Inputs.data, data)\n        evres = self.get_output(self.widget.Outputs.evaluation_results)\n        self.assertEqual(len(evres.data), 0)\n\n    def test_no_values_target(self):\n        train = Table(\"titanic\")\n        model = ConstantLearner()(train)\n        self.send_signal(self.widget.Inputs.predictors, model)\n        domain = Domain([DiscreteVariable(\"status\", values=(\"first\", \"third\")),\n                         DiscreteVariable(\"age\", values=(\"adult\", \"child\")),\n                         DiscreteVariable(\"sex\", values=(\"female\", \"male\"))],\n                        [DiscreteVariable(\"survived\", values=())])\n        test = Table(domain, np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]]),\n                     np.full((3, 1), np.nan))\n        self.send_signal(self.widget.Inputs.data, test)\n        pred = self.get_output(self.widget.Outputs.predictions)\n        self.assertEqual(len(pred), len(test))\n\n        results = self.get_output(self.widget.Outputs.evaluation_results)\n\n        cm_widget = self.create_widget(OWConfusionMatrix)\n        self.send_signal(cm_widget.Inputs.evaluation_results, results,\n                         widget=cm_widget)\n\n        ra_widget = self.create_widget(OWROCAnalysis)\n        self.send_signal(ra_widget.Inputs.evaluation_results, results,\n                         widget=ra_widget)\n\n        lc_widget = self.create_widget(OWLiftCurve)\n        self.send_signal(lc_widget.Inputs.evaluation_results, results,\n                         widget=lc_widget)\n\n        cp_widget = self.create_widget(OWCalibrationPlot)\n        self.send_signal(cp_widget.Inputs.evaluation_results, results,\n                         widget=cp_widget)\n\n    def test_mismatching_targets(self):\n        warning = self.widget.Warning\n\n        maj_iris = ConstantLearner()(self.iris)\n        dom = self.iris.domain\n        iris3 = self.iris.transform(Domain(dom[:3], dom[3]))\n        maj_iris3 = ConstantLearner()(iris3)\n\n        self.send_signal(self.widget.Inputs.predictors, maj_iris, 1)\n        self.send_signal(self.widget.Inputs.predictors, maj_iris3, 2)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.assertTrue(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.predictors, None, 2)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.predictors, maj_iris3, 2)\n        self.assertTrue(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n    def test_no_class_on_test(self):\n        \"\"\"Allow test data with no class\"\"\"\n        titanic = Table(\"titanic\")\n        majority_titanic = ConstantLearner()(titanic)\n\n        no_class = titanic.transform(Domain(titanic.domain.attributes, None))\n        self.send_signal(self.widget.Inputs.predictors, majority_titanic, 1)\n        self.send_signal(self.widget.Inputs.data, no_class)\n        out = self.get_output(self.widget.Outputs.predictions)\n        np.testing.assert_allclose(out.get_column_view(\"constant\")[0], 0)\n\n    def test_bad_data(self):\n        \"\"\"\n        Firstly it creates predictions with TreeLearner. Then sends predictions and\n        different data with different domain to Predictions widget. Those different\n        data and domain are similar to original data and domain but they have three\n        different target values instead of two.\n        GH-2129\n        \"\"\"\n        filestr1 = \"\"\"\\\n        age\\tsex\\tsurvived\n        d\\td\\td\n        \\t\\tclass\n        adult\\tmale\\tyes\n        adult\\tfemale\\tno\n        child\\tmale\\tyes\n        child\\tfemale\\tyes\n        \"\"\"\n        file1 = io.StringIO(filestr1)\n        table = TabReader(file1).read()\n        learner = TreeLearner()\n        tree = learner(table)\n\n        filestr2 = \"\"\"\\\n        age\\tsex\\tsurvived\n        d\\td\\td\n        \\t\\tclass\n        adult\\tmale\\tyes\n        adult\\tfemale\\tno\n        child\\tmale\\tyes\n        child\\tfemale\\tunknown\n        \"\"\"\n        file2 = io.StringIO(filestr2)\n        bad_table = TabReader(file2).read()\n\n        self.send_signal(self.widget.Inputs.predictors, tree, 1)\n\n        with excepthook_catch():\n            self.send_signal(self.widget.Inputs.data, bad_table)\n\n    def test_continuous_class(self):\n        data = Table(\"housing\")\n        cl_data = ConstantLearner()(data)\n        self.send_signal(self.widget.Inputs.predictors, cl_data, 1)\n        self.send_signal(self.widget.Inputs.data, data)\n\n    def test_predictor_fails(self):\n        titanic = Table(\"titanic\")\n        failing_model = ConstantLearner()(titanic)\n        failing_model.predict = Mock(side_effect=ValueError(\"foo\"))\n        self.send_signal(self.widget.Inputs.predictors, failing_model, 1)\n        self.send_signal(self.widget.Inputs.data, titanic)\n\n        model2 = ConstantLearner()(titanic)\n        self.send_signal(self.widget.Inputs.predictors, model2, 2)\n\n    def test_sort_matching(self):\n        def get_items_order(model):\n            n = pred_model.rowCount()\n            return [\n                pred_model.mapToSource(model.index(i, 0)).row()\n                for i in range(n)\n            ]\n\n        w = self.widget\n\n        titanic = Table(\"titanic\")\n        majority_titanic = LogisticRegressionLearner()(titanic)\n        self.send_signal(self.widget.Inputs.predictors, majority_titanic)\n        self.send_signal(self.widget.Inputs.data, titanic)\n\n        pred_model = w.predictionsview.model()\n        data_model = w.predictionsview.model()\n        n = pred_model.rowCount()\n\n        # no sort\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, list(range(n)))\n        self.assertListEqual(data_order, list(range(n)))\n\n        # sort by first column in prediction table\n        pred_model.sort(0)\n        w.predictionsview.horizontalHeader().sectionClicked.emit(0)\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, data_order)\n\n        # sort by second column in data table\n        data_model.sort(1)\n        w.dataview.horizontalHeader().sectionClicked.emit(0)\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, data_order)\n\n        # restore order\n        w.reset_button.click()\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, list(range(n)))\n        self.assertListEqual(data_order, list(range(n)))\n\n    def test_sort_predictions(self):\n        \"\"\"\n        Test whether sorting of probabilities by FilterSortProxy is correct.\n        \"\"\"\n        def get_items_order(model):\n            n = pred_model.rowCount()\n            return [\n                pred_model.mapToSource(model.index(i, 0)).row()\n                for i in range(n)\n            ]\n\n        log_reg_iris = LogisticRegressionLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, log_reg_iris)\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        _, log_reg_probs = log_reg_iris(self.iris, Model.ValueProbs)\n        # here I assume that classes are in order 0, 1, 2 in widget\n\n        pred_model = self.widget.predictionsview.model()\n        pred_model.sort(0)\n        widget_order = get_items_order(pred_model)\n\n        # correct order first sort by probs[:,0] then probs[:,1], ...\n        keys = tuple(\n            log_reg_probs[:, i] for i in range(\n                log_reg_probs.shape[1] - 1, -1, -1))\n        sort_order = np.lexsort(keys)\n        np.testing.assert_array_equal(widget_order, sort_order)\n\n    def test_reset_no_data(self):\n        \"\"\"\n        Check no error when resetting the view without model and data\n        \"\"\"\n        self.widget.reset_button.click()\n\n    def test_colors_same_domain(self):\n        \"\"\"\n        Test whether the color selection for values is correct.\n        \"\"\"\n        # pylint: disable=protected-access\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        # case 1: one same model\n        predictor_iris = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(\n            colors, self.iris.domain.class_var.colors)\n\n        # case 2: two same models\n        predictor_iris1 = ConstantLearner()(self.iris)\n        predictor_iris2 = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        # assume that colors have same order since values have same order\n        np.testing.assert_array_equal(\n            colors, self.iris.domain.class_var.colors)\n\n        # case 3: two same models - changed color order\n        idom = self.iris.domain\n        dom = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom.class_var.colors = dom.class_var.colors[::-1]\n        iris2 = self.iris.transform(dom)\n\n        predictor_iris1 = ConstantLearner()(iris2)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris2.domain.class_var.colors)\n\n    def test_colors_diff_domain(self):\n        \"\"\"\n        Test whether the color selection for values is correct.\n        \"\"\"\n        # pylint: disable=protected-access\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        # case 1: two domains one subset other\n        idom = self.iris.domain\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[:2])\n        )\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n        # case 2: two domains one subset other - different color order\n        idom = self.iris.domain\n        colors = idom.class_var.colors[::-1]\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[:2])\n        )\n        dom1.class_var.colors = colors\n        dom2.class_var.colors = colors[:2]\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n        # case 3: domain color, values miss-match - use default colors\n        idom = self.iris.domain\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom1.class_var.colors = dom1.class_var.colors[::-1]\n        iris1 = self.iris.transform(dom1)\n        iris2 = self.iris.transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, ColorPaletteGenerator.palette(3))\n\n        # case 4: two domains different values order, matching colors\n        idom = self.iris.domain\n        # this way we know that default colors are not used\n        colors = ColorPaletteGenerator.palette(5)[2:]\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[::-1])\n        )\n        dom1.class_var.colors = colors\n        dom2.class_var.colors = colors[::-1]  # colors mixed same than values\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n    def test_colors_continuous(self):\n        \"\"\"\n        When only continuous variables in predictor no color should be selected\n        we do not work with classes.\n        When we add one classifier there should be colors.\n        \"\"\"\n        # pylint: disable=protected-access\n        data = Table(\"housing\")\n        cl_data = ConstantLearner()(data)\n        self.send_signal(self.widget.Inputs.predictors, cl_data)\n        self.send_signal(self.widget.Inputs.data, data)\n        colors = self.widget._get_colors()\n        self.assertListEqual([], colors)\n\n        predictor_iris = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris, 1)\n        colors = self.widget._get_colors()\n        self.assertEqual(3, len(colors))\n\n        self.widget.send_report()",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 24,
                                "end_lineno": 415,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "41e015e4bc1bd1c2c65955d53150c4128979275b^",
    "new_commit_hash": "41e015e4bc1bd1c2c65955d53150c4128979275b",
    "commit_message": "Merge pull request #4709 from janezd/predictions-fix-report\n\n[FIX] Fix report in Predictions",
    "commit_date": "2020-05-08T10:47:19+02:00",
    "metadata": {}
}
{
    "repo_name": "orange3",
    "new_commit_hash": "41e015e4bc1bd1c2c65955d53150c4128979275b",
    "test_file_codes": [
        "\"\"\"Tests for OWPredictions\"\"\"\nimport io\nfrom unittest.mock import Mock\n\nimport numpy as np\n\nfrom Orange.base import Model\nfrom Orange.classification import LogisticRegressionLearner\nfrom Orange.data.io import TabReader\nfrom Orange.widgets.tests.base import WidgetTest\nfrom Orange.widgets.evaluate.owpredictions import OWPredictions\nfrom Orange.widgets.evaluate.owcalibrationplot import OWCalibrationPlot\nfrom Orange.widgets.evaluate.owconfusionmatrix import OWConfusionMatrix\nfrom Orange.widgets.evaluate.owliftcurve import OWLiftCurve\nfrom Orange.widgets.evaluate.owrocanalysis import OWROCAnalysis\n\nfrom Orange.data import Table, Domain, DiscreteVariable\nfrom Orange.modelling import ConstantLearner, TreeLearner\nfrom Orange.evaluation import Results\nfrom Orange.widgets.tests.utils import excepthook_catch\nfrom Orange.widgets.utils.colorpalette import ColorPaletteGenerator\n\n\nclass TestOWPredictions(WidgetTest):\n\n    def setUp(self):\n        self.widget = self.create_widget(OWPredictions)  # type: OWPredictions\n        self.iris = Table(\"iris\")\n\n    def test_rowCount_from_model(self):\n        \"\"\"Don't crash if the bottom row is visible\"\"\"\n        self.send_signal(self.widget.Inputs.data, self.iris[:5])\n        self.widget.dataview.sizeHintForColumn(0)\n\n    def test_nan_target_input(self):\n        data = self.iris[::10].copy()\n        data.Y[1] = np.nan\n        yvec, _ = data.get_column_view(data.domain.class_var)\n        self.send_signal(self.widget.Inputs.data, data)\n        self.send_signal(self.widget.Inputs.predictors, ConstantLearner()(data), 1)\n        pred = self.get_output(self.widget.Outputs.predictions)\n        self.assertIsInstance(pred, Table)\n        np.testing.assert_array_equal(\n            yvec, pred.get_column_view(data.domain.class_var)[0])\n\n        evres = self.get_output(self.widget.Outputs.evaluation_results)\n        self.assertIsInstance(evres, Results)\n        self.assertIsInstance(evres.data, Table)\n        ev_yvec, _ = evres.data.get_column_view(data.domain.class_var)\n\n        self.assertTrue(np.all(~np.isnan(ev_yvec)))\n        self.assertTrue(np.all(~np.isnan(evres.actual)))\n\n        data.Y[:] = np.nan\n        self.send_signal(self.widget.Inputs.data, data)\n        evres = self.get_output(self.widget.Outputs.evaluation_results)\n        self.assertEqual(len(evres.data), 0)\n\n    def test_no_values_target(self):\n        train = Table(\"titanic\")\n        model = ConstantLearner()(train)\n        self.send_signal(self.widget.Inputs.predictors, model)\n        domain = Domain([DiscreteVariable(\"status\", values=(\"first\", \"third\")),\n                         DiscreteVariable(\"age\", values=(\"adult\", \"child\")),\n                         DiscreteVariable(\"sex\", values=(\"female\", \"male\"))],\n                        [DiscreteVariable(\"survived\", values=())])\n        test = Table(domain, np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]]),\n                     np.full((3, 1), np.nan))\n        self.send_signal(self.widget.Inputs.data, test)\n        pred = self.get_output(self.widget.Outputs.predictions)\n        self.assertEqual(len(pred), len(test))\n\n        results = self.get_output(self.widget.Outputs.evaluation_results)\n\n        cm_widget = self.create_widget(OWConfusionMatrix)\n        self.send_signal(cm_widget.Inputs.evaluation_results, results,\n                         widget=cm_widget)\n\n        ra_widget = self.create_widget(OWROCAnalysis)\n        self.send_signal(ra_widget.Inputs.evaluation_results, results,\n                         widget=ra_widget)\n\n        lc_widget = self.create_widget(OWLiftCurve)\n        self.send_signal(lc_widget.Inputs.evaluation_results, results,\n                         widget=lc_widget)\n\n        cp_widget = self.create_widget(OWCalibrationPlot)\n        self.send_signal(cp_widget.Inputs.evaluation_results, results,\n                         widget=cp_widget)\n\n    def test_mismatching_targets(self):\n        warning = self.widget.Warning\n\n        maj_iris = ConstantLearner()(self.iris)\n        dom = self.iris.domain\n        iris3 = self.iris.transform(Domain(dom[:3], dom[3]))\n        maj_iris3 = ConstantLearner()(iris3)\n\n        self.send_signal(self.widget.Inputs.predictors, maj_iris, 1)\n        self.send_signal(self.widget.Inputs.predictors, maj_iris3, 2)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.assertTrue(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.predictors, None, 2)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.predictors, maj_iris3, 2)\n        self.assertTrue(warning.wrong_targets.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.assertFalse(warning.wrong_targets.is_shown())\n\n    def test_no_class_on_test(self):\n        \"\"\"Allow test data with no class\"\"\"\n        titanic = Table(\"titanic\")\n        majority_titanic = ConstantLearner()(titanic)\n\n        no_class = titanic.transform(Domain(titanic.domain.attributes, None))\n        self.send_signal(self.widget.Inputs.predictors, majority_titanic, 1)\n        self.send_signal(self.widget.Inputs.data, no_class)\n        out = self.get_output(self.widget.Outputs.predictions)\n        np.testing.assert_allclose(out.get_column_view(\"constant\")[0], 0)\n\n    def test_bad_data(self):\n        \"\"\"\n        Firstly it creates predictions with TreeLearner. Then sends predictions and\n        different data with different domain to Predictions widget. Those different\n        data and domain are similar to original data and domain but they have three\n        different target values instead of two.\n        GH-2129\n        \"\"\"\n        filestr1 = \"\"\"\\\n        age\\tsex\\tsurvived\n        d\\td\\td\n        \\t\\tclass\n        adult\\tmale\\tyes\n        adult\\tfemale\\tno\n        child\\tmale\\tyes\n        child\\tfemale\\tyes\n        \"\"\"\n        file1 = io.StringIO(filestr1)\n        table = TabReader(file1).read()\n        learner = TreeLearner()\n        tree = learner(table)\n\n        filestr2 = \"\"\"\\\n        age\\tsex\\tsurvived\n        d\\td\\td\n        \\t\\tclass\n        adult\\tmale\\tyes\n        adult\\tfemale\\tno\n        child\\tmale\\tyes\n        child\\tfemale\\tunknown\n        \"\"\"\n        file2 = io.StringIO(filestr2)\n        bad_table = TabReader(file2).read()\n\n        self.send_signal(self.widget.Inputs.predictors, tree, 1)\n\n        with excepthook_catch():\n            self.send_signal(self.widget.Inputs.data, bad_table)\n\n    def test_continuous_class(self):\n        data = Table(\"housing\")\n        cl_data = ConstantLearner()(data)\n        self.send_signal(self.widget.Inputs.predictors, cl_data, 1)\n        self.send_signal(self.widget.Inputs.data, data)\n\n    def test_predictor_fails(self):\n        titanic = Table(\"titanic\")\n        failing_model = ConstantLearner()(titanic)\n        failing_model.predict = Mock(side_effect=ValueError(\"foo\"))\n        self.send_signal(self.widget.Inputs.predictors, failing_model, 1)\n        self.send_signal(self.widget.Inputs.data, titanic)\n\n        model2 = ConstantLearner()(titanic)\n        self.send_signal(self.widget.Inputs.predictors, model2, 2)\n\n    def test_sort_matching(self):\n        def get_items_order(model):\n            n = pred_model.rowCount()\n            return [\n                pred_model.mapToSource(model.index(i, 0)).row()\n                for i in range(n)\n            ]\n\n        w = self.widget\n\n        titanic = Table(\"titanic\")\n        majority_titanic = LogisticRegressionLearner()(titanic)\n        self.send_signal(self.widget.Inputs.predictors, majority_titanic)\n        self.send_signal(self.widget.Inputs.data, titanic)\n\n        pred_model = w.predictionsview.model()\n        data_model = w.predictionsview.model()\n        n = pred_model.rowCount()\n\n        # no sort\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, list(range(n)))\n        self.assertListEqual(data_order, list(range(n)))\n\n        # sort by first column in prediction table\n        pred_model.sort(0)\n        w.predictionsview.horizontalHeader().sectionClicked.emit(0)\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, data_order)\n\n        # sort by second column in data table\n        data_model.sort(1)\n        w.dataview.horizontalHeader().sectionClicked.emit(0)\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, data_order)\n\n        # restore order\n        w.reset_button.click()\n        pred_order = get_items_order(pred_model)\n        data_order = get_items_order(data_model)\n        self.assertListEqual(pred_order, list(range(n)))\n        self.assertListEqual(data_order, list(range(n)))\n\n    def test_sort_predictions(self):\n        \"\"\"\n        Test whether sorting of probabilities by FilterSortProxy is correct.\n        \"\"\"\n        def get_items_order(model):\n            n = pred_model.rowCount()\n            return [\n                pred_model.mapToSource(model.index(i, 0)).row()\n                for i in range(n)\n            ]\n\n        log_reg_iris = LogisticRegressionLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, log_reg_iris)\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        _, log_reg_probs = log_reg_iris(self.iris, Model.ValueProbs)\n        # here I assume that classes are in order 0, 1, 2 in widget\n\n        pred_model = self.widget.predictionsview.model()\n        pred_model.sort(0)\n        widget_order = get_items_order(pred_model)\n\n        # correct order first sort by probs[:,0] then probs[:,1], ...\n        keys = tuple(\n            log_reg_probs[:, i] for i in range(\n                log_reg_probs.shape[1] - 1, -1, -1))\n        sort_order = np.lexsort(keys)\n        np.testing.assert_array_equal(widget_order, sort_order)\n\n    def test_reset_no_data(self):\n        \"\"\"\n        Check no error when resetting the view without model and data\n        \"\"\"\n        self.widget.reset_button.click()\n\n    def test_colors_same_domain(self):\n        \"\"\"\n        Test whether the color selection for values is correct.\n        \"\"\"\n        # pylint: disable=protected-access\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        # case 1: one same model\n        predictor_iris = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(\n            colors, self.iris.domain.class_var.colors)\n\n        # case 2: two same models\n        predictor_iris1 = ConstantLearner()(self.iris)\n        predictor_iris2 = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        # assume that colors have same order since values have same order\n        np.testing.assert_array_equal(\n            colors, self.iris.domain.class_var.colors)\n\n        # case 3: two same models - changed color order\n        idom = self.iris.domain\n        dom = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom.class_var.colors = dom.class_var.colors[::-1]\n        iris2 = self.iris.transform(dom)\n\n        predictor_iris1 = ConstantLearner()(iris2)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris2.domain.class_var.colors)\n\n    def test_colors_diff_domain(self):\n        \"\"\"\n        Test whether the color selection for values is correct.\n        \"\"\"\n        # pylint: disable=protected-access\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        # case 1: two domains one subset other\n        idom = self.iris.domain\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[:2])\n        )\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n        # case 2: two domains one subset other - different color order\n        idom = self.iris.domain\n        colors = idom.class_var.colors[::-1]\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[:2])\n        )\n        dom1.class_var.colors = colors\n        dom2.class_var.colors = colors[:2]\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n        # case 3: domain color, values miss-match - use default colors\n        idom = self.iris.domain\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom1.class_var.colors = dom1.class_var.colors[::-1]\n        iris1 = self.iris.transform(dom1)\n        iris2 = self.iris.transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, ColorPaletteGenerator.palette(3))\n\n        # case 4: two domains different values order, matching colors\n        idom = self.iris.domain\n        # this way we know that default colors are not used\n        colors = ColorPaletteGenerator.palette(5)[2:]\n        dom1 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values)\n        )\n        dom2 = Domain(\n            idom.attributes,\n            DiscreteVariable(idom.class_var.name, idom.class_var.values[::-1])\n        )\n        dom1.class_var.colors = colors\n        dom2.class_var.colors = colors[::-1]  # colors mixed same than values\n        iris1 = self.iris[:100].transform(dom1)\n        iris2 = self.iris[:100].transform(dom2)\n\n        predictor_iris1 = ConstantLearner()(iris1)\n        predictor_iris2 = ConstantLearner()(iris2)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris1)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris2, 1)\n        colors = self.widget._get_colors()\n        np.testing.assert_array_equal(colors, iris1.domain.class_var.colors)\n\n    def test_colors_continuous(self):\n        \"\"\"\n        When only continuous variables in predictor no color should be selected\n        we do not work with classes.\n        When we add one classifier there should be colors.\n        \"\"\"\n        # pylint: disable=protected-access\n        data = Table(\"housing\")\n        cl_data = ConstantLearner()(data)\n        self.send_signal(self.widget.Inputs.predictors, cl_data)\n        self.send_signal(self.widget.Inputs.data, data)\n        colors = self.widget._get_colors()\n        self.assertListEqual([], colors)\n\n        predictor_iris = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris, 1)\n        colors = self.widget._get_colors()\n        self.assertEqual(3, len(colors))\n\n        self.widget.send_report()  # just a quick check that it doesn't crash\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/tmp22hk_31m/tmp\ncreating /tmp/tmp22hk_31m/tmp/tmp22hk_31m\ncompile options: '-MMD -MF /tmp/tmp22hk_31m/file.c.d -c'\ncc: /tmp/tmp22hk_31m/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/tmp4uvfcrji/tmp\ncreating /tmp/tmp4uvfcrji/tmp/tmp4uvfcrji\ncompile options: '-MMD -MF /tmp/tmp4uvfcrji/file.c.d -c'\ncc: /tmp/tmp4uvfcrji/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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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/tmph9govaof/tmp\ncreating /tmp/tmph9govaof/tmp/tmph9govaof\ncompile options: '-MMD -MF /tmp/tmph9govaof/file.c.d -c'\ncc: /tmp/tmph9govaof/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/tmp2a_vglt9/tmp\ncreating /tmp/tmp2a_vglt9/tmp/tmp2a_vglt9\ncompile options: '-MMD -MF /tmp/tmp2a_vglt9/file.c.d -c'\ncc: /tmp/tmp2a_vglt9/file.c\ncustomize UnixCCompiler using build_ext\nCreating /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/Orange3.egg-link (link to .)\nAdding Orange3 3.26.0.dev0+41e015e to easy-install.pth file\nInstalling orange-canvas script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\n\nInstalled /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b\nProcessing dependencies for Orange3==3.26.0.dev0+41e015e\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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\nInstalling pip3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\nInstalling pip3.10 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages\nSearching for orange-widget-base==4.22.0\nBest match: orange-widget-base 4.22.0\nAdding orange-widget-base 4.22.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages\nSearching for openpyxl==3.1.3\nBest match: openpyxl 3.1.3\nAdding openpyxl 3.1.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\nInstalling f2py3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\nInstalling f2py3.7 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages\nSearching for httpx==0.24.1\nBest match: httpx 0.24.1\nAdding httpx 0.24.1 to easy-install.pth file\nInstalling httpx script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages\nSearching for baycomp==1.0.3\nBest match: baycomp 1.0.3\nAdding baycomp 1.0.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages\nSearching for et-xmlfile==1.1.0\nBest match: et-xmlfile 1.1.0\nAdding et-xmlfile 1.1.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\nInstalling pyftmerge script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\nInstalling pyftsubset script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\nInstalling ttx script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages\nSearching for sniffio==1.3.1\nBest match: sniffio 1.3.1\nAdding sniffio 1.3.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages\nSearching for httpcore==0.17.3\nBest match: httpcore 0.17.3\nAdding httpcore 0.17.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages\nSearching for h11==0.14.0\nBest match: h11 0.14.0\nAdding h11 0.14.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages\nSearching for anyio==3.7.1\nBest match: anyio 3.7.1\nAdding anyio 3.7.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages\nFinished processing dependencies for Orange3==3.26.0.dev0+41e015e\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 96ms\nPrepared 18 packages in 2ms\nInstalled 18 packages in 91ms\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 54 packages in 371ms\nInstalled 47 packages in 613ms\n + anyio==3.7.1\n + baycomp==1.0.3\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 + cycler==0.11.0\n + et-xmlfile==1.1.0\n + fonttools==4.38.0\n + h11==0.14.0\n + httpcore==0.17.3\n + httpx==0.24.1\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 + kiwisolver==1.4.5\n + matplotlib==3.5.3\n + more-itertools==9.1.0\n + networkx==2.6.3\n + openpyxl==3.1.3\n + opentsne==1.0.1\n + pandas==1.3.5\n + pillow==9.5.0\n + pip==24.0\n + pycparser==2.21\n + pyparsing==3.1.4\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 + sniffio==1.3.1\n + threadpoolctl==3.1.0\n + urllib3==2.0.7\n + xlrd==2.0.1\n + xlsxwriter==3.2.0\nResolved 34 packages in 119ms\nInstalled 13 packages in 142ms\n + anyqt==0.2.0\n + attrs==24.2.0\n + cattrs==23.1.2\n + commonmark==0.9.1\n + dictdiffer==0.9.0\n + docutils==0.20.1\n + orange-canvas-core==0.1.35\n + orange-widget-base==4.22.0\n + platformdirs==4.0.0\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 53ms\n + psycopg2==2.9.9\n + pymssql==2.3.2\nAudited 1 package in 58ms\nAudited 2 packages in 24ms\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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/data/_contingency.c:598:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/distance/_distance.c:598:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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_41e015e4bc1bd1c2c65955d53150c4128979275b/.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": 0,
    "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_41e015e4bc1bd1c2c65955d53150c4128979275b\nplugins: anyio-3.7.1\ncollected 20 items\n\nr2e_tests/test_1.py sss.................                                 [100%]\n\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_bad_data\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_colors_continuous\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_colors_diff_domain\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_colors_same_domain\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_continuous_class\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_image_export\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_minimum_size\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_mismatching_targets\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_msg_base_class\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_nan_target_input\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_no_class_on_test\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_no_values_target\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_predictor_fails\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_reset_no_data\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_rowCount_from_model\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_sort_matching\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_sort_predictions\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:244: image exporting not tested as .widget was not set\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:238: minimum size not tested as .widget was not set\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:250: msg base class not tested as .widget was not set\n======================== 17 passed, 3 skipped in 6.29s =========================\nWidgets left: 0    Max widgets: 2408 \n\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_41e015e4bc1bd1c2c65955d53150c4128979275b\nplugins: anyio-3.7.1\ncollected 20 items\n\nr2e_tests/test_1.py sss.F...............                                 [100%]\n\n=================================== FAILURES ===================================\n___________________ TestOWPredictions.test_colors_continuous ___________________\n\nself = <r2e_tests.test_1.TestOWPredictions testMethod=test_colors_continuous>\n\n    def test_colors_continuous(self):\n        \"\"\"\n        When only continuous variables in predictor no color should be selected\n        we do not work with classes.\n        When we add one classifier there should be colors.\n        \"\"\"\n        # pylint: disable=protected-access\n        data = Table(\"housing\")\n        cl_data = ConstantLearner()(data)\n        self.send_signal(self.widget.Inputs.predictors, cl_data)\n        self.send_signal(self.widget.Inputs.data, data)\n        colors = self.widget._get_colors()\n        self.assertListEqual([], colors)\n    \n        predictor_iris = ConstantLearner()(self.iris)\n        self.send_signal(self.widget.Inputs.predictors, predictor_iris, 1)\n        colors = self.widget._get_colors()\n        self.assertEqual(3, len(colors))\n    \n>       self.widget.send_report()  # just a quick check that it doesn't crash\n\nr2e_tests/test_1.py:415: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <Orange.widgets.evaluate.owpredictions.OWPredictions object at 0x791f0d124f50>\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_model = self.predictionsview.model()\n    \n            # use ItemDelegate to style prediction values\n            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())\n    \n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n    \n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n    \n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [style(predictions_model.data(predictions_model.index(i, j)))\n                       for j in range(predictions_model.columnCount())] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n    \n        if self.data:\n>           text = self.infolabel.text().replace('\\n', '<br>')\nE           AttributeError: 'OWPredictions' object has no attribute 'infolabel'\n\nOrange/widgets/evaluate/owpredictions.py:588: AttributeError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_bad_data\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_colors_diff_domain\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_colors_same_domain\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_continuous_class\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_image_export\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_minimum_size\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_mismatching_targets\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_msg_base_class\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_nan_target_input\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_no_class_on_test\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_no_values_target\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_predictor_fails\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_reset_no_data\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_rowCount_from_model\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_sort_matching\nPASSED r2e_tests/test_1.py::TestOWPredictions::test_sort_predictions\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:244: image exporting not tested as .widget was not set\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:238: minimum size not tested as .widget was not set\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:250: msg base class not tested as .widget was not set\nFAILED r2e_tests/test_1.py::TestOWPredictions::test_colors_continuous - Attri...\n=================== 1 failed, 16 passed, 3 skipped in 4.45s ====================\nWidgets left: 0    Max widgets: 2408 \n\n",
    "old_commit_res_stderr": ""
}
Orange/widgets/evaluate/owpredictions.py Orange/widgets/evaluate/tests/test_owpredictions.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `send_report` Method Raises AttributeError Due to Missing `infolabel` in Predictions Widget

**Description:**
When attempting to generate a report using the `send_report` method in the Predictions widget, an `AttributeError` is thrown because the widget lacks the `infolabel` attribute. This prevents the report from being created successfully.

**Example Code:**
```python
widget = OWPredictions()
widget.send_report()
```

**Expected Behavior:**
Calling `send_report` should generate and compile the report without any errors, regardless of whether `infolabel` is present in the widget.

**Actual Behavior:**
An error occurs indicating that the `infolabel` attribute does not exist in the `OWPredictions` object.

**Error Message:**
```
AttributeError: 'OWPredictions' object has no attribute 'infolabel'
```
[/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/evaluate/owpredictions.py
from collections import namedtuple
from functools import partial
from operator import itemgetter

import numpy
from AnyQt.QtWidgets import (
    QTableView, QListWidget, QSplitter, QStyledItemDelegate,
    QToolTip, QStyle, QApplication, QSizePolicy)
from AnyQt.QtGui import QPainter, QStandardItem, QPen, QColor
from AnyQt.QtCore import (
    Qt, QSize, QRect, QRectF, QPoint, QLocale,
    QModelIndex, QAbstractTableModel, QSortFilterProxyModel, pyqtSignal, QTimer)

import Orange
from Orange.evaluation import Results
from Orange.base import Model
from Orange.data import ContinuousVariable, DiscreteVariable, Value, Domain
from Orange.data.table import DomainTransformationError
from Orange.widgets import gui, settings
from Orange.widgets.evaluate.utils import (
    ScoreTable, usable_scorers, learner_name, scorer_caller)
from Orange.widgets.utils.colorpalette import ColorPaletteGenerator
from Orange.widgets.utils.widgetpreview import WidgetPreview
from Orange.widgets.widget import OWWidget, Msg, Input, Output
from Orange.widgets.utils.itemmodels import TableModel
from Orange.widgets.utils.sql import check_sql_input


# Input slot for the Predictors channel
PredictorSlot = namedtuple(
    "PredictorSlot",
    ["predictor",  # The `Model` instance
     "name",       # Predictor name
     "results"]    # Computed prediction results or None.
)


class OWPredictions(OWWidget):
    name = "Predictions"
    icon = "icons/Predictions.svg"
    priority = 200
    description = "Display predictions of models for an input dataset."
    keywords = []

    class Inputs:
        data = Input("Data", Orange.data.Table)
        predictors = Input("Predictors", Model, multiple=True)

    class Outputs:
        predictions = Output("Predictions", Orange.data.Table)
        evaluation_results = Output("Evaluation Results", Results)

    class Warning(OWWidget.Warning):
        empty_data = Msg("Empty dataset")
        wrong_targets = Msg(
            "Some model(s) predict a different target (see more ...)\n{}")

    class Error(OWWidget.Error):
        predictor_failed = Msg("Some predictor(s) failed (see more ...)\n{}")
        scorer_failed = Msg("Some scorer(s) failed (see more ...)\n{}")

    settingsHandler = settings.ClassValuesContextHandler()
    score_table = settings.SettingProvider(ScoreTable)

    #: List of selected class value indices in the `class_values` list
    selected_classes = settings.ContextSetting([])

    def __init__(self):
        super().__init__()

        self.data = None  # type: Optional[Orange.data.Table]
        self.predictors = {}  # type: Dict[object, PredictorSlot]
        self.class_values = []  # type: List[str]
        self._delegates = []
        self.left_width = 10

        gui.listBox(self.controlArea, self, "selected_classes", "class_values",
                    box="Show probabibilities for",
                    callback=self._update_prediction_delegate,
                    selectionMode=QListWidget.ExtendedSelection,
                    addSpace=False,
                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))
        gui.rubber(self.controlArea)
        self.reset_button = gui.button(
            self.controlArea, self, "Restore Original Order",
            callback=self._reset_order,
            tooltip="Show rows in the original order")

        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,
                          horizontalScrollMode=QTableView.ScrollPerPixel,
                          selectionMode=QTableView.NoSelection,
                          focusPolicy=Qt.StrongFocus)
        self.dataview = TableView(
            sortingEnabled=True,
            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,
            **table_opts)
        self.predictionsview = TableView(
            sortingEnabled=True,
            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
            **table_opts)
        self.dataview.verticalHeader().hide()
        dsbar = self.dataview.verticalScrollBar()
        psbar = self.predictionsview.verticalScrollBar()
        psbar.valueChanged.connect(dsbar.setValue)
        dsbar.valueChanged.connect(psbar.setValue)

        self.dataview.verticalHeader().setDefaultSectionSize(22)
        self.predictionsview.verticalHeader().setDefaultSectionSize(22)
        self.dataview.verticalHeader().sectionResized.connect(
            lambda index, _, size:
            self.predictionsview.verticalHeader().resizeSection(index, size))

        self.splitter = QSplitter(
            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)
        self.splitter.splitterMoved.connect(self.splitter_resized)
        self.splitter.addWidget(self.predictionsview)
        self.splitter.addWidget(self.dataview)

        self.score_table = ScoreTable(self)
        self.vsplitter = gui.vBox(self.mainArea)
        self.vsplitter.layout().addWidget(self.splitter)
        self.vsplitter.layout().addWidget(self.score_table.view)

    @Inputs.data
    @check_sql_input
    def set_data(self, data):
        self.Warning.empty_data(shown=data is not None and not data)
        self.data = data
        if not data:
            self.dataview.setModel(None)
            self.predictionsview.setModel(None)
        else:
            # force full reset of the view's HeaderView state
            self.dataview.setModel(None)
            model = TableModel(data, parent=None)
            modelproxy = SortProxyModel()
            modelproxy.setSourceModel(model)
            self.dataview.setModel(modelproxy)

            self.dataview.model().list_sorted.connect(
                partial(
                    self._update_data_sort_order, self.dataview,
                    self.predictionsview))

        self._invalidate_predictions()

    @property
    def class_var(self):
        return self.data and self.data.domain.class_var

    # pylint: disable=redefined-builtin
    @Inputs.predictors
    def set_predictor(self, predictor=None, id=None):
        if id in self.predictors:
            if predictor is not None:
                self.predictors[id] = self.predictors[id]._replace(
                    predictor=predictor, name=predictor.name, results=None)
            else:
                del self.predictors[id]
        elif predictor is not None:
            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)

    def _set_class_values(self):
        class_values = []
        for slot in self.predictors.values():
            class_var = slot.predictor.domain.class_var
            if class_var and class_var.is_discrete:
                for value in class_var.values:
                    if value not in class_values:
                        class_values.append(value)

        if self.class_var and self.class_var.is_discrete:
            values = self.class_var.values
            self.class_values = sorted(
                class_values, key=lambda val: val not in values)
            self.selected_classes = [
                i for i, name in enumerate(class_values) if name in values]
        else:
            self.class_values = class_values  # This assignment updates listview
            self.selected_classes = []

    def handleNewSignals(self):
        self._set_class_values()
        self._call_predictors()
        self._update_scores()
        self._update_predictions_model()
        self._update_prediction_delegate()
        self._set_errors()
        self._update_info()
        self.commit()

    def _call_predictors(self):
        if not self.data:
            return
        if self.class_var:
            domain = self.data.domain
            classless_data = self.data.transform(
                Domain(domain.attributes, None, domain.metas))
        else:
            classless_data = self.data

        for inputid, slot in self.predictors.items():
            if isinstance(slot.results, Results):
                continue

            predictor = slot.predictor
            try:
                if predictor.domain.class_var.is_discrete:
                    pred, prob = predictor(classless_data, Model.ValueProbs)
                else:
                    pred = predictor(classless_data, Model.Value)
                    prob = numpy.zeros((len(pred), 0))
            except (ValueError, DomainTransformationError) as err:
                self.predictors[inputid] = \
                    slot._replace(results=f"{predictor.name}: {err}")
                continue

            results = Results()
            results.data = self.data
            results.domain = self.data.domain
            results.row_indices = numpy.arange(len(self.data))
            results.folds = (Ellipsis, )
            results.actual = self.data.Y
            results.unmapped_probabilities = prob
            results.unmapped_predicted = pred
            results.probabilities = results.predicted = None
            self.predictors[inputid] = slot._replace(results=results)

            target = predictor.domain.class_var
            if target != self.class_var:
                continue

            if target is not self.class_var and target.is_discrete:
                backmappers, n_values = predictor.get_backmappers(self.data)
                prob = predictor.backmap_probs(prob, n_values, backmappers)
                pred = predictor.backmap_value(pred, prob, n_values, backmappers)
            results.predicted = pred.reshape((1, len(self.data)))
            results.probabilities = prob.reshape((1,) + prob.shape)

    def _update_scores(self):
        model = self.score_table.model
        model.clear()
        scorers = usable_scorers(self.class_var) if self.class_var else []
        self.score_table.update_header(scorers)
        errors = []
        for inputid, pred in self.predictors.items():
            results = self.predictors[inputid].results
            if not isinstance(results, Results) or results.predicted is None:
                continue
            row = [QStandardItem(learner_name(pred.predictor)),
                   QStandardItem("N/A"), QStandardItem("N/A")]
            for scorer in scorers:
                item = QStandardItem()
                try:
                    score = scorer_caller(scorer, results)()[0]
                    item.setText(f"{score:.3f}")
                except Exception as exc:  # pylint: disable=broad-except
                    item.setToolTip(str(exc))
                    if scorer.name in self.score_table.shown_scores:
                        errors.append(str(exc))
                row.append(item)
            self.score_table.model.appendRow(row)

        view = self.score_table.view
        if model.rowCount():
            view.setVisible(True)
            view.ensurePolished()
            view.setFixedHeight(
                5 + view.horizontalHeader().height() +
                view.verticalHeader().sectionSize(0) * model.rowCount())
        else:
            view.setVisible(False)

        self.Error.scorer_failed("\n".join(errors), shown=bool(errors))

    def _set_errors(self):
        # Not all predictors are run every time, so errors can't be collected
        # in _call_predictors
        errors = "\n".join(
            f"- {p.predictor.name}: {p.results}"
            for p in self.predictors.values()
            if isinstance(p.results, str) and p.results)
        self.Error.predictor_failed(errors, shown=bool(errors))

        if self.class_var:
            inv_targets = "\n".join(
                f"- {pred.name} predicts '{pred.domain.class_var.name}'"
                for pred in (p.predictor for p in self.predictors.values()
                             if isinstance(p.results, Results)
                             and p.results.probabilities is None))
            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))
        else:
            self.Warning.wrong_targets.clear()

    def _update_info(self):
        n_predictors = len(self.predictors)
        if not self.data and not n_predictors:
            self.info.set_input_summary(self.info.NoInput)
            return

        n_valid = len(self._non_errored_predictors())
        summary = str(len(self.data)) if self.data else "0"
        details = f"{len(self.data)} instances" if self.data else "No data"
        details += f"\n{n_predictors} models" if n_predictors else "No models"
        if n_valid != n_predictors:
            details += f" ({n_predictors - n_valid} failed)"
        self.info.set_input_summary(summary, details)

    def _invalidate_predictions(self):
        for inputid, pred in list(self.predictors.items()):
            self.predictors[inputid] = pred._replace(results=None)

    def _non_errored_predictors(self):
        return [p for p in self.predictors.values()
                if isinstance(p.results, Results)]

    def _reordered_probabilities(self, prediction):
        cur_values = prediction.predictor.domain.class_var.values
        new_ind = [self.class_values.index(x) for x in cur_values]
        probs = prediction.results.unmapped_probabilities
        new_probs = numpy.full(
            (probs.shape[0], len(self.class_values)), numpy.nan)
        new_probs[:, new_ind] = probs
        return new_probs

    def _update_predictions_model(self):
        results = []
        headers = []
        for p in self._non_errored_predictors():
            values = p.results.unmapped_predicted
            target = p.predictor.domain.class_var
            if target.is_discrete:
                # order probabilities in order from Show prob. for
                prob = self._reordered_probabilities(p)
                values = [Value(target, v) for v in values]
            else:
                prob = numpy.zeros((len(values), 0))
            results.append((values, prob))
            headers.append(p.predictor.name)

        if results:
            results = list(zip(*(zip(*res) for res in results)))
            model = PredictionsModel(results, headers)
        else:
            model = None

        predmodel = PredictionsSortProxyModel()
        predmodel.setSourceModel(model)
        predmodel.setDynamicSortFilter(True)
        self.predictionsview.setModel(predmodel)
        hheader = self.predictionsview.horizontalHeader()
        hheader.setSortIndicatorShown(False)
        # SortFilterProxyModel is slow due to large abstraction overhead
        # (every comparison triggers multiple `model.index(...)`,
        # model.rowCount(...), `model.parent`, ... calls)
        hheader.setSectionsClickable(predmodel.rowCount() < 20000)

        self.predictionsview.model().list_sorted.connect(
            partial(
                self._update_data_sort_order, self.predictionsview,
                self.dataview))

        self.predictionsview.resizeColumnsToContents()

    @staticmethod
    def _update_data_sort_order(sort_source_view, sort_dest_view):
        sort_dest = sort_dest_view.model()
        sort_source = sort_source_view.model()
        sortindicatorshown = False
        if sort_dest is not None:
            assert isinstance(sort_dest, QSortFilterProxyModel)
            n = sort_dest.rowCount()
            if sort_source is not None and sort_source.sortColumn() >= 0:
                sortind = numpy.argsort(
                    [sort_source.mapToSource(sort_source.index(i, 0)).row()
                     for i in range(n)])
                sortind = numpy.array(sortind, numpy.int)
                sortindicatorshown = True
            else:
                sortind = None

            sort_dest.setSortIndices(sortind)

        sort_dest_view.horizontalHeader().setSortIndicatorShown(
            False)
        sort_source_view.horizontalHeader().setSortIndicatorShown(
            sortindicatorshown)

    def _reset_order(self):
        datamodel = self.dataview.model()
        predmodel = self.predictionsview.model()
        if datamodel is not None:
            datamodel.setSortIndices(None)
            datamodel.sort(-1)
        if predmodel is not None:
            predmodel.setSortIndices(None)
            predmodel.sort(-1)
        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)
        self.dataview.horizontalHeader().setSortIndicatorShown(False)

    def _all_color_values(self):
        """
        Return list of colors together with their values from all predictors
        classes. Colors and values are sorted according to the values order
        for simpler comparison.
        """
        predictors = self._non_errored_predictors()
        color_values = [
            list(zip(*sorted(zip(
                p.predictor.domain.class_var.colors,
                p.predictor.domain.class_var.values
            ), key=itemgetter(1))))
            for p in predictors if p.predictor.domain.class_var.is_discrete
        ]
        return color_values if color_values else [([], [])]

    @staticmethod
    def _colors_match(colors1, values1, color2, values2):
        """
        Test whether colors for values match. Colors matches when all
        values match for shorter list and colors match for shorter list.
        It is assumed that values will be sorted together with their colors.
        """
        shorter_length = min(len(colors1), len(color2))
        return (values1[:shorter_length] == values2[:shorter_length]
                and (numpy.array(colors1[:shorter_length]) ==
                     numpy.array(color2[:shorter_length])).all())

    def _get_colors(self):
        """
        Defines colors for values. If colors match in all models use the union
        otherwise use standard colors.
        """
        all_colors_values = self._all_color_values()
        base_color, base_values = all_colors_values[0]
        for c, v in all_colors_values[1:]:
            if not self._colors_match(base_color, base_values, c, v):
                base_color = []
                break
            # replace base_color if longer
            if len(v) > len(base_color):
                base_color = c
                base_values = v

        if len(base_color) != len(self.class_values):
            return ColorPaletteGenerator.palette(len(self.class_values))
        # reorder colors to widgets order
        colors = [None] * len(self.class_values)
        for c, v in zip(base_color, base_values):
            colors[self.class_values.index(v)] = c
        return colors

    def _update_prediction_delegate(self):
        self._delegates.clear()
        colors = self._get_colors()
        for col, slot in enumerate(self.predictors.values()):
            target = slot.predictor.domain.class_var
            shown_probs = (
                () if target.is_continuous else
                [val if self.class_values[val] in target.values else None
                 for val in self.selected_classes]
            )
            delegate = PredictionsItemDelegate(
                None if target.is_continuous else self.class_values,
                colors,
                shown_probs,
                target.format_str if target.is_continuous else None
            )
            # QAbstractItemView does not take ownership of delegates, so we must
            self._delegates.append(delegate)
            self.predictionsview.setItemDelegateForColumn(col, delegate)
            self.predictionsview.setColumnHidden(col, False)

        self.predictionsview.resizeColumnsToContents()
        self._recompute_splitter_sizes()
        if self.predictionsview.model() is not None:
            self.predictionsview.model().setProbInd(self.selected_classes)

    def _recompute_splitter_sizes(self):
        if not self.data:
            return
        view = self.predictionsview
        self.left_width = \
            view.horizontalHeader().length() + view.verticalHeader().width()
        self._update_splitter()

    def _update_splitter(self):
        w1, w2 = self.splitter.sizes()
        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])

    def splitter_resized(self):
        self.left_width = self.splitter.sizes()[0]

    def commit(self):
        self._commit_predictions()
        self._commit_evaluation_results()

    def _commit_evaluation_results(self):
        slots = [p for p in self._non_errored_predictors()
                 if p.results.predicted is not None]
        if not slots:
            self.Outputs.evaluation_results.send(None)
            return

        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])
        data = self.data[~nanmask]
        results = Results(data, store_data=True)
        results.folds = None
        results.row_indices = numpy.arange(len(data))
        results.actual = data.Y.ravel()
        results.predicted = numpy.vstack(
            tuple(p.results.predicted[0][~nanmask] for p in slots))
        if self.class_var and self.class_var.is_discrete:
            results.probabilities = numpy.array(
                [p.results.probabilities[0][~nanmask] for p in slots])
        results.learner_names = [p.name for p in slots]
        self.Outputs.evaluation_results.send(results)

    def _commit_predictions(self):
        if not self.data:
            self.Outputs.predictions.send(None)
            return

        newmetas = []
        newcolumns = []
        for slot in self._non_errored_predictors():
            if slot.predictor.domain.class_var.is_discrete:
                self._add_classification_out_columns(slot, newmetas, newcolumns)
            else:
                self._add_regression_out_columns(slot, newmetas, newcolumns)

        attrs = list(self.data.domain.attributes)
        metas = list(self.data.domain.metas) + newmetas
        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)
        predictions = self.data.transform(domain)
        if newcolumns:
            newcolumns = numpy.hstack(
                [numpy.atleast_2d(cols) for cols in newcolumns])
            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns
        self.Outputs.predictions.send(predictions)

    @staticmethod
    def _add_classification_out_columns(slot, newmetas, newcolumns):
        # Mapped or unmapped predictions?!
        # Or provide a checkbox so the user decides?
        pred = slot.predictor
        name = pred.name
        values = pred.domain.class_var.values
        newmetas.append(DiscreteVariable(name=name, values=values))
        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))
        newmetas += [ContinuousVariable(name=f"{name} ({value})")
                     for value in values]
        newcolumns.append(slot.results.unmapped_probabilities)

    @staticmethod
    def _add_regression_out_columns(slot, newmetas, newcolumns):
        newmetas.append(ContinuousVariable(name=slot.predictor.name))
        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))

    def send_report(self):
        def merge_data_with_predictions():
            data_model = self.dataview.model()
            predictions_model = self.predictionsview.model()

            # use ItemDelegate to style prediction values
            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())

            # iterate only over visible columns of data's QTableView
            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),
                                         range(data_model.columnCount())))

            # print header
            yield [''] + \
                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)
                   for col in range(predictions_model.columnCount())] + \
                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)
                   for col in iter_data_cols]

            # print data & predictions
            for i in range(data_model.rowCount()):
                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \
                      [style(predictions_model.data(predictions_model.index(i, j)))
                       for j in range(predictions_model.columnCount())] + \
                      [data_model.data(data_model.index(i, j))
                       for j in iter_data_cols]

        if self.data:
            text = self.infolabel.text().replace('\n', '<br>')
            if self.selected_classes:
                text += '<br>Showing probabilities for: '
                text += ', '. join([self.class_values[i]
                                    for i in self.selected_classes])
            self.report_paragraph('Info', text)
            self.report_table("Data & Predictions", merge_data_with_predictions(),
                              header_rows=1, header_columns=1)

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self._update_splitter()

    def showEvent(self, event):
        super().showEvent(event)
        QTimer.singleShot(0, self._update_splitter)


class PredictionsItemDelegate(QStyledItemDelegate):
    """
    A Item Delegate for custom formatting of predictions/probabilities
    """
    def __init__(
            self, class_values, colors, shown_probabilities=(),
            target_format=None, parent=None,
    ):
        super().__init__(parent)
        self.class_values = class_values  # will be None for continuous
        self.colors = [QColor(*c) for c in colors]
        self.target_format = target_format  # target format for cont. vars
        self.shown_probabilities = self.fmt = self.tooltip = None  # set below
        self.setFormat(shown_probabilities)

    def setFormat(self, shown_probabilities=()):
        self.shown_probabilities = shown_probabilities
        if self.class_values is None:
            # is continuous class
            self.fmt = f"{{value:{self.target_format[1:]}}}"
        else:
            self.fmt = " \N{RIGHTWARDS ARROW} ".join(
                [" : ".join(f"{{dist[{i}]:.2f}}" if i is not None else "-"
                            for i in shown_probabilities)]
                * bool(shown_probabilities)
                + ["{value!s}"])
        self.tooltip = ""
        if shown_probabilities:
            val = ', '.join(
                self.class_values[i] if i is not None else "-"
                for i in shown_probabilities if i is not None
            )
            self.tooltip = f"p({val})"

    def displayText(self, value, _locale):
        try:
            value, dist = value
        except ValueError:
            return ""
        else:
            return self.fmt.format(value=value, dist=dist)

    def helpEvent(self, event, view, option, index):
        if self.tooltip is not None:
            # ... but can be an empty string, so the current tooltip is removed
            QToolTip.showText(event.globalPos(), self.tooltip, view)
            return True
        else:
            return super().helpEvent(event, view, option, index)

    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        if self.class_values is None:
            option.displayAlignment = \
                (option.displayAlignment & Qt.AlignVertical_Mask) | \
                Qt.AlignRight

    def sizeHint(self, option, index):
        # reimplemented
        sh = super().sizeHint(option, index)
        if option.widget is not None:
            style = option.widget.style()
        else:
            style = QApplication.style()
        margin = style.pixelMetric(
            QStyle.PM_FocusFrameHMargin, option, option.widget) + 1
        metrics = option.fontMetrics
        height = sh.height() + metrics.leading() + 2 * margin
        return QSize(sh.width(), height)

    @staticmethod
    def distribution(index):
        value = index.data(Qt.DisplayRole)
        if isinstance(value, tuple) and len(value) == 2:
            _, dist = value
            return dist
        else:
            return None

    def paint(self, painter, option, index):
        dist = self.distribution(index)
        if dist is None or self.colors is None:
            super().paint(painter, option, index)
            return

        if option.widget is not None:
            style = option.widget.style()
        else:
            style = QApplication.style()

        self.initStyleOption(option, index)

        text = option.text
        metrics = option.fontMetrics

        margin = style.pixelMetric(
            QStyle.PM_FocusFrameHMargin, option, option.widget) + 1
        bottommargin = min(margin, 1)
        rect = option.rect.adjusted(margin, margin, -margin, -bottommargin)

        textrect = style.subElementRect(
            QStyle.SE_ItemViewItemText, option, option.widget)
        # Are the margins included in the subElementRect?? -> No!
        textrect = textrect.adjusted(margin, margin, -margin, -bottommargin)

        text = option.fontMetrics.elidedText(
            text, option.textElideMode, textrect.width())

        spacing = max(metrics.leading(), 1)

        distheight = rect.height() - metrics.height() - spacing
        distheight = numpy.clip(distheight, 2, metrics.height())

        painter.save()
        painter.setClipRect(option.rect)
        painter.setFont(option.font)
        painter.setRenderHint(QPainter.Antialiasing)

        style.drawPrimitive(
            QStyle.PE_PanelItemViewRow, option, painter, option.widget)
        style.drawPrimitive(
            QStyle.PE_PanelItemViewItem, option, painter, option.widget)

        if option.state & QStyle.State_Selected:
            color = option.palette.highlightedText().color()
        else:
            color = option.palette.text().color()
        painter.setPen(QPen(color))

        textrect = textrect.adjusted(0, 0, 0, -distheight - spacing)
        distrect = QRect(
            textrect.bottomLeft() + QPoint(0, spacing),
            QSize(rect.width(), distheight))
        painter.setPen(QPen(Qt.lightGray, 0.3))
        self.drawDistBar(painter, distrect, dist)
        painter.restore()
        if text:
            style.drawItemText(
                painter, textrect, option.displayAlignment, option.palette,
                option.state & QStyle.State_Enabled, text)

    def drawDistBar(self, painter, rect, distribution):
        painter.save()
        painter.translate(rect.topLeft())
        for i in self.shown_probabilities:
            if i is None:
                continue
            dvalue = distribution[i]
            if not dvalue > 0:  # This also skips nans
                continue
            painter.setBrush(self.colors[i])
            width = rect.width() * dvalue
            painter.drawRoundedRect(QRectF(0, 0, width, rect.height()), 1, 2)
            painter.translate(width, 0.0)
        painter.restore()


class SortProxyModel(QSortFilterProxyModel):
    """
    QSortFilter model used in both TableView and PredictionsView
    """
    list_sorted = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.__sortInd = None

    def setSortIndices(self, indices):
        if indices is not None:
            indices = numpy.array(indices, dtype=numpy.int)
            if indices.shape != (self.rowCount(),):
                raise ValueError("indices.shape != (self.rowCount(),)")
            indices.flags.writeable = False

        self.__sortInd = indices

        if self.__sortInd is not None:
            self.custom_sort(0)  # need valid order to call lessThan

    def lessThan(self, left, right):
        if self.__sortInd is None:
            return super().lessThan(left, right)

        assert not (left.parent().isValid() or right.parent().isValid()), \
            "Not a table model"

        rleft, rright = left.row(), right.row()
        try:
            ileft, iright = self.__sortInd[rleft], self.__sortInd[rright]
        except IndexError:
            return False
        else:
            return ileft < iright

    def isSorted(self):
        return self.__sortInd is not None

    def sort(self, n, order=Qt.AscendingOrder):
        """
        This sort is called only on click, in other cases we manually call
        custom_sort
        """
        # reset sort - otherwise when same parameters set by lessThan function
        # clicking on header would not trigger resort
        self.__sortInd = None
        self.custom_sort(n, order=order)
        self.list_sorted.emit()

    def custom_sort(self, n, order=Qt.AscendingOrder):
        """
        When sorting is dmanded because of sort change in the other view
        this sorting is called. It will not reset __sortInd to None.
        """
        if self.sortColumn() == n and self.sortOrder() == order:
            self.invalidate()
        else:
            super().sort(n, order)  # need some valid sort column


class PredictionsSortProxyModel(SortProxyModel):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.__probInd = None

    def setProbInd(self, indices):
        self.__probInd = indices
        self.invalidate()
        self.list_sorted.emit()

    def lessThan(self, left, right):
        if self.isSorted():
            return super().lessThan(left, right)

        role = self.sortRole()
        left_data = self.sourceModel().data(left, role)
        right_data = self.sourceModel().data(right, role)

        return self._key(left_data) < self._key(right_data)

    def _key(self, prediction):
        value, probs = prediction
        if probs is not None:
            if self.__probInd is not None:
                probs = probs[self.__probInd]
            probs = tuple(probs)

        return probs, value


class PredictionsModel(QAbstractTableModel):
    def __init__(self, table=None, headers=None, parent=None):
        super().__init__(parent)
        self._table = [[]] if table is None else table
        if headers is None:
            headers = [None] * len(self._table)
        self._header = headers
        self.__columnCount = max([len(row) for row in self._table] or [0])

    def rowCount(self, parent=QModelIndex()):
        return 0 if parent.isValid() else len(self._table)

    def columnCount(self, parent=QModelIndex()):
        return 0 if parent.isValid() else self.__columnCount

    def _value(self, index):
        return self._table[index.row()][index.column()]

    def data(self, index, role=Qt.DisplayRole):
        if role in (Qt.DisplayRole, Qt.EditRole):
            return self._value(index)
        return None

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if orientation == Qt.Vertical and role == Qt.DisplayRole:
            return str(section + 1)
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return (self._header[section] if section < len(self._header)
                    else str(section))
        return None


class TableView(QTableView):
    MaxSizeHintSamples = 1000

    def sizeHintForColumn(self, column):
        """
        Reimplemented from `QTableView.sizeHintForColumn`

        Note: This does not match the QTableView's implementation,
        in particular size hints from editor/index widgets are not taken
        into account.

        Parameters
        ----------
        column : int
        """
        # This is probably not needed in Qt5?
        if self.model() is None:
            return -1

        self.ensurePolished()
        model = self.model()
        vheader = self.verticalHeader()
        top = vheader.visualIndexAt(0)
        bottom = vheader.visualIndexAt(self.viewport().height())
        if bottom < 0:
            bottom = self.model().rowCount()

        options = self.viewOptions()
        options.widget = self

        width = 0
        sample_count = 0

        for row in range(top, bottom):
            if not vheader.isSectionHidden(vheader.logicalIndex(row)):
                index = model.index(row, column)
                delegate = self.itemDelegate(index)
                if not delegate:
                    continue
                size = delegate.sizeHint(options, index)
                width = max(size.width(), width)
                sample_count += 1

            if sample_count >= TableView.MaxSizeHintSamples:
                break

        return width + 1 if self.showGrid() else width


def tool_tip(value):
    value, dist = value
    if dist is not None:
        return "{!s} {!s}".format(value, dist)
    else:
        return str(value)


if __name__ == "__main__":  # pragma: no cover
    filename = "iris.tab"
    iris = Orange.data.Table(filename)
    idom = iris.domain
    dom = Domain(
        idom.attributes,
        DiscreteVariable(idom.class_var.name, idom.class_var.values[1::-1])
    )
    iris2 = iris[:100].transform(dom)

    def pred_error(data, *args, **kwargs):
        raise ValueError

    pred_error.domain = iris.domain
    pred_error.name = "To err is human"

    if iris.domain.has_discrete_class:
        predictors_ = [
            Orange.classification.SVMLearner(probability=True)(iris2),
            Orange.classification.LogisticRegressionLearner()(iris),
            pred_error
        ]
    elif iris.domain.has_continuous_class:
        predictors_ = [
            Orange.regression.RidgeRegressionLearner(alpha=1.0)(iris),
            Orange.regression.LinearRegressionLearner()(iris),
            pred_error
        ]
    else:
        predictors_ = [pred_error]

    WidgetPreview(OWPredictions).run(
        set_data=iris2,
        set_predictor=[(pred, i) for i, pred in enumerate(predictors_)])

```
--- 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:** `send_report` Method Raises AttributeError Due to Missing `infolabel` in Predictions Widget

**Description:**
When attempting to generate a report using the `send_report` method in the Predictions widget, an `AttributeError` is thrown because the widget lacks the `infolabel` attribute. This prevents the report from being created successfully.

**Example Code:**
```python
widget = OWPredictions()
widget.send_report()
```

**Expected Behavior:**
Calling `send_report` should generate and compile the report without any errors, regardless of whether `infolabel` is present in the widget.

**Actual Behavior:**
An error occurs indicating that the `infolabel` attribute does not exist in the `OWPredictions` object.

**Error Message:**
```
AttributeError: 'OWPredictions' object has no attribute 'infolabel'
```
[/ISSUE]
{
    "TestOWPredictions.test_bad_data": "PASSED",
    "TestOWPredictions.test_colors_continuous": "PASSED",
    "TestOWPredictions.test_colors_diff_domain": "PASSED",
    "TestOWPredictions.test_colors_same_domain": "PASSED",
    "TestOWPredictions.test_continuous_class": "PASSED",
    "TestOWPredictions.test_image_export": "PASSED",
    "TestOWPredictions.test_minimum_size": "PASSED",
    "TestOWPredictions.test_mismatching_targets": "PASSED",
    "TestOWPredictions.test_msg_base_class": "PASSED",
    "TestOWPredictions.test_nan_target_input": "PASSED",
    "TestOWPredictions.test_no_class_on_test": "PASSED",
    "TestOWPredictions.test_no_values_target": "PASSED",
    "TestOWPredictions.test_predictor_fails": "PASSED",
    "TestOWPredictions.test_reset_no_data": "PASSED",
    "TestOWPredictions.test_rowCount_from_model": "PASSED",
    "TestOWPredictions.test_sort_matching": "PASSED",
    "TestOWPredictions.test_sort_predictions": "PASSED"
}
diff --git a/Orange/widgets/evaluate/owpredictions.py b/Orange/widgets/evaluate/owpredictions.py
index 5bbb09b26..879d754b3 100644
--- a/Orange/widgets/evaluate/owpredictions.py
+++ b/Orange/widgets/evaluate/owpredictions.py
@@ -11,6 +11,8 @@ from AnyQt.QtCore import (
     Qt, QSize, QRect, QRectF, QPoint, QLocale,
     QModelIndex, QAbstractTableModel, QSortFilterProxyModel, pyqtSignal, QTimer)
 
+from orangewidget.report import plural
+
 import Orange
 from Orange.evaluation import Results
 from Orange.base import Model
@@ -293,19 +295,29 @@ class OWPredictions(OWWidget):
             self.Warning.wrong_targets.clear()
 
     def _update_info(self):
-        n_predictors = len(self.predictors)
-        if not self.data and not n_predictors:
+        if not self.data and not self.predictors:
             self.info.set_input_summary(self.info.NoInput)
             return
 
-        n_valid = len(self._non_errored_predictors())
         summary = str(len(self.data)) if self.data else "0"
-        details = f"{len(self.data)} instances" if self.data else "No data"
-        details += f"\n{n_predictors} models" if n_predictors else "No models"
-        if n_valid != n_predictors:
-            details += f" ({n_predictors - n_valid} failed)"
+        details = self._get_details()
         self.info.set_input_summary(summary, details)
 
+    def _get_details(self):
+        n_predictors = len(self.predictors)
+        if self.data:
+            details = plural("{number} instance{s}", len(self.data))
+        else:
+            details = "No data"
+        if n_predictors:
+            n_valid = len(self._non_errored_predictors())
+            details += plural("\n{number} model{s}", n_predictors)
+            if n_valid != n_predictors:
+                details += plural(" ({number} failed)", n_predictors - n_valid)
+        else:
+            details += "\nNo models"
+        return details
+
     def _invalidate_predictions(self):
         for inputid, pred in list(self.predictors.items()):
             self.predictors[inputid] = pred._replace(results=None)
@@ -560,10 +572,12 @@ class OWPredictions(OWWidget):
     def send_report(self):
         def merge_data_with_predictions():
             data_model = self.dataview.model()
-            predictions_model = self.predictionsview.model()
+            predictions_view = self.predictionsview
+            predictions_model = predictions_view.model()
 
             # use ItemDelegate to style prediction values
-            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())
+            delegates = [predictions_view.itemDelegateForColumn(i)
+                         for i in range(predictions_model.columnCount())]
 
             # iterate only over visible columns of data's QTableView
             iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),
@@ -579,13 +593,15 @@ class OWPredictions(OWWidget):
             # print data & predictions
             for i in range(data_model.rowCount()):
                 yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \
-                      [style(predictions_model.data(predictions_model.index(i, j)))
-                       for j in range(predictions_model.columnCount())] + \
+                      [delegate.displayText(
+                          predictions_model.data(predictions_model.index(i, j)),
+                          QLocale())
+                       for j, delegate in enumerate(delegates)] + \
                       [data_model.data(data_model.index(i, j))
                        for j in iter_data_cols]
 
         if self.data:
-            text = self.infolabel.text().replace('\n', '<br>')
+            text = self._get_details().replace('\n', '<br>')
             if self.selected_classes:
                 text += '<br>Showing probabilities for: '
                 text += ', '. join([self.class_values[i]
@@ -594,6 +610,8 @@ class OWPredictions(OWWidget):
             self.report_table("Data & Predictions", merge_data_with_predictions(),
                               header_rows=1, header_columns=1)
 
+            self.report_table("Scores", self.score_table.view)
+
     def resizeEvent(self, event):
         super().resizeEvent(event)
         self._update_splitter()

{"Orange/widgets/evaluate/owpredictions.py": "from collections import namedtuple\nfrom functools import partial\nfrom operator import itemgetter\n\nimport numpy\nfrom AnyQt.QtWidgets import (\n    QTableView, QListWidget, QSplitter, QStyledItemDelegate,\n    QToolTip, QStyle, QApplication, QSizePolicy)\nfrom AnyQt.QtGui import QPainter, QStandardItem, QPen, QColor\nfrom AnyQt.QtCore import (\n    Qt, QSize, QRect, QRectF, QPoint, QLocale,\n    QModelIndex, QAbstractTableModel, QSortFilterProxyModel, pyqtSignal, QTimer)\n\nimport Orange\nfrom Orange.evaluation import Results\nfrom Orange.base import Model\nfrom Orange.data import ContinuousVariable, DiscreteVariable, Value, Domain\nfrom Orange.data.table import DomainTransformationError\nfrom Orange.widgets import gui, settings\nfrom Orange.widgets.evaluate.utils import (\n    ScoreTable, usable_scorers, learner_name, scorer_caller)\nfrom Orange.widgets.utils.colorpalette import ColorPaletteGenerator\nfrom Orange.widgets.utils.widgetpreview import WidgetPreview\nfrom Orange.widgets.widget import OWWidget, Msg, Input, Output\nfrom Orange.widgets.utils.itemmodels import TableModel\nfrom Orange.widgets.utils.sql import check_sql_input\n\n\n# Input slot for the Predictors channel\nPredictorSlot = namedtuple(\n    \"PredictorSlot\",\n    [\"predictor\",  # The `Model` instance\n     \"name\",       # Predictor name\n     \"results\"]    # Computed prediction results or None.\n)\n\n\nclass OWPredictions(OWWidget):\n    name = \"Predictions\"\n    icon = \"icons/Predictions.svg\"\n    priority = 200\n    description = \"Display predictions of models for an input dataset.\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n        predictors = Input(\"Predictors\", Model, multiple=True)\n\n    class Outputs:\n        predictions = Output(\"Predictions\", Orange.data.Table)\n        evaluation_results = Output(\"Evaluation Results\", Results)\n\n    class Warning(OWWidget.Warning):\n        empty_data = Msg(\"Empty dataset\")\n        wrong_targets = Msg(\n            \"Some model(s) predict a different target (see more ...)\\n{}\")\n\n    class Error(OWWidget.Error):\n        predictor_failed = Msg(\"Some predictor(s) failed (see more ...)\\n{}\")\n        scorer_failed = Msg(\"Some scorer(s) failed (see more ...)\\n{}\")\n\n    settingsHandler = settings.ClassValuesContextHandler()\n    score_table = settings.SettingProvider(ScoreTable)\n\n    #: List of selected class value indices in the `class_values` list\n    selected_classes = settings.ContextSetting([])\n\n    def __init__(self):\n        super().__init__()\n\n        self.data = None  # type: Optional[Orange.data.Table]\n        self.predictors = {}  # type: Dict[object, PredictorSlot]\n        self.class_values = []  # type: List[str]\n        self._delegates = []\n        self.left_width = 10\n\n        gui.listBox(self.controlArea, self, \"selected_classes\", \"class_values\",\n                    box=\"Show probabibilities for\",\n                    callback=self._update_prediction_delegate,\n                    selectionMode=QListWidget.ExtendedSelection,\n                    addSpace=False,\n                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))\n        gui.rubber(self.controlArea)\n        self.reset_button = gui.button(\n            self.controlArea, self, \"Restore Original Order\",\n            callback=self._reset_order,\n            tooltip=\"Show rows in the original order\")\n\n        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n                          horizontalScrollMode=QTableView.ScrollPerPixel,\n                          selectionMode=QTableView.NoSelection,\n                          focusPolicy=Qt.StrongFocus)\n        self.dataview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,\n            **table_opts)\n        self.predictionsview = TableView(\n            sortingEnabled=True,\n            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,\n            **table_opts)\n        self.dataview.verticalHeader().hide()\n        dsbar = self.dataview.verticalScrollBar()\n        psbar = self.predictionsview.verticalScrollBar()\n        psbar.valueChanged.connect(dsbar.setValue)\n        dsbar.valueChanged.connect(psbar.setValue)\n\n        self.dataview.verticalHeader().setDefaultSectionSize(22)\n        self.predictionsview.verticalHeader().setDefaultSectionSize(22)\n        self.dataview.verticalHeader().sectionResized.connect(\n            lambda index, _, size:\n            self.predictionsview.verticalHeader().resizeSection(index, size))\n\n        self.splitter = QSplitter(\n            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)\n        self.splitter.splitterMoved.connect(self.splitter_resized)\n        self.splitter.addWidget(self.predictionsview)\n        self.splitter.addWidget(self.dataview)\n\n        self.score_table = ScoreTable(self)\n        self.vsplitter = gui.vBox(self.mainArea)\n        self.vsplitter.layout().addWidget(self.splitter)\n        self.vsplitter.layout().addWidget(self.score_table.view)\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.Warning.empty_data(shown=data is not None and not data)\n        self.data = data\n        if not data:\n            self.dataview.setModel(None)\n            self.predictionsview.setModel(None)\n        else:\n            # force full reset of the view's HeaderView state\n            self.dataview.setModel(None)\n            model = TableModel(data, parent=None)\n            modelproxy = SortProxyModel()\n            modelproxy.setSourceModel(model)\n            self.dataview.setModel(modelproxy)\n\n            self.dataview.model().list_sorted.connect(\n                partial(\n                    self._update_data_sort_order, self.dataview,\n                    self.predictionsview))\n\n        self._invalidate_predictions()\n\n    @property\n    def class_var(self):\n        return self.data and self.data.domain.class_var\n\n    # pylint: disable=redefined-builtin\n    @Inputs.predictors\n    def set_predictor(self, predictor=None, id=None):\n        if id in self.predictors:\n            if predictor is not None:\n                self.predictors[id] = self.predictors[id]._replace(\n                    predictor=predictor, name=predictor.name, results=None)\n            else:\n                del self.predictors[id]\n        elif predictor is not None:\n            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)\n\n    def _set_class_values(self):\n        class_values = []\n        for slot in self.predictors.values():\n            class_var = slot.predictor.domain.class_var\n            if class_var and class_var.is_discrete:\n                for value in class_var.values:\n                    if value not in class_values:\n                        class_values.append(value)\n\n        if self.class_var and self.class_var.is_discrete:\n            values = self.class_var.values\n            self.class_values = sorted(\n                class_values, key=lambda val: val not in values)\n            self.selected_classes = [\n                i for i, name in enumerate(class_values) if name in values]\n        else:\n            self.class_values = class_values  # This assignment updates listview\n            self.selected_classes = []\n\n    def handleNewSignals(self):\n        self._set_class_values()\n        self._call_predictors()\n        self._update_scores()\n        self._update_predictions_model()\n        self._update_prediction_delegate()\n        self._set_errors()\n        self._update_info()\n        self.commit()\n\n    def _call_predictors(self):\n        if not self.data:\n            return\n        if self.class_var:\n            domain = self.data.domain\n            classless_data = self.data.transform(\n                Domain(domain.attributes, None, domain.metas))\n        else:\n            classless_data = self.data\n\n        for inputid, slot in self.predictors.items():\n            if isinstance(slot.results, Results):\n                continue\n\n            predictor = slot.predictor\n            try:\n                if predictor.domain.class_var.is_discrete:\n                    pred, prob = predictor(classless_data, Model.ValueProbs)\n                else:\n                    pred = predictor(classless_data, Model.Value)\n                    prob = numpy.zeros((len(pred), 0))\n            except (ValueError, DomainTransformationError) as err:\n                self.predictors[inputid] = \\\n                    slot._replace(results=f\"{predictor.name}: {err}\")\n                continue\n\n            results = Results()\n            results.data = self.data\n            results.domain = self.data.domain\n            results.row_indices = numpy.arange(len(self.data))\n            results.folds = (Ellipsis, )\n            results.actual = self.data.Y\n            results.unmapped_probabilities = prob\n            results.unmapped_predicted = pred\n            results.probabilities = results.predicted = None\n            self.predictors[inputid] = slot._replace(results=results)\n\n            target = predictor.domain.class_var\n            if target != self.class_var:\n                continue\n\n            if target is not self.class_var and target.is_discrete:\n                backmappers, n_values = predictor.get_backmappers(self.data)\n                prob = predictor.backmap_probs(prob, n_values, backmappers)\n                pred = predictor.backmap_value(pred, prob, n_values, backmappers)\n            results.predicted = pred.reshape((1, len(self.data)))\n            results.probabilities = prob.reshape((1,) + prob.shape)\n\n    def _update_scores(self):\n        model = self.score_table.model\n        model.clear()\n        scorers = usable_scorers(self.class_var) if self.class_var else []\n        self.score_table.update_header(scorers)\n        errors = []\n        for inputid, pred in self.predictors.items():\n            results = self.predictors[inputid].results\n            if not isinstance(results, Results) or results.predicted is None:\n                continue\n            row = [QStandardItem(learner_name(pred.predictor)),\n                   QStandardItem(\"N/A\"), QStandardItem(\"N/A\")]\n            for scorer in scorers:\n                item = QStandardItem()\n                try:\n                    score = scorer_caller(scorer, results)()[0]\n                    item.setText(f\"{score:.3f}\")\n                except Exception as exc:  # pylint: disable=broad-except\n                    item.setToolTip(str(exc))\n                    if scorer.name in self.score_table.shown_scores:\n                        errors.append(str(exc))\n                row.append(item)\n            self.score_table.model.appendRow(row)\n\n        view = self.score_table.view\n        if model.rowCount():\n            view.setVisible(True)\n            view.ensurePolished()\n            view.setFixedHeight(\n                5 + view.horizontalHeader().height() +\n                view.verticalHeader().sectionSize(0) * model.rowCount())\n        else:\n            view.setVisible(False)\n\n        self.Error.scorer_failed(\"\\n\".join(errors), shown=bool(errors))\n\n    def _set_errors(self):\n        # Not all predictors are run every time, so errors can't be collected\n        # in _call_predictors\n        errors = \"\\n\".join(\n            f\"- {p.predictor.name}: {p.results}\"\n            for p in self.predictors.values()\n            if isinstance(p.results, str) and p.results)\n        self.Error.predictor_failed(errors, shown=bool(errors))\n\n        if self.class_var:\n            inv_targets = \"\\n\".join(\n                f\"- {pred.name} predicts '{pred.domain.class_var.name}'\"\n                for pred in (p.predictor for p in self.predictors.values()\n                             if isinstance(p.results, Results)\n                             and p.results.probabilities is None))\n            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))\n        else:\n            self.Warning.wrong_targets.clear()\n\n    def _update_info(self):\n        n_predictors = len(self.predictors)\n        if not self.data and not n_predictors:\n            self.info.set_input_summary(self.info.NoInput)\n            return\n\n        n_valid = len(self._non_errored_predictors())\n        summary = str(len(self.data)) if self.data else \"0\"\n        details = f\"{len(self.data)} instances\" if self.data else \"No data\"\n        details += f\"\\n{n_predictors} models\" if n_predictors else \"No models\"\n        if n_valid != n_predictors:\n            details += f\" ({n_predictors - n_valid} failed)\"\n        self.info.set_input_summary(summary, details)\n\n    def _invalidate_predictions(self):\n        for inputid, pred in list(self.predictors.items()):\n            self.predictors[inputid] = pred._replace(results=None)\n\n    def _non_errored_predictors(self):\n        return [p for p in self.predictors.values()\n                if isinstance(p.results, Results)]\n\n    def _reordered_probabilities(self, prediction):\n        cur_values = prediction.predictor.domain.class_var.values\n        new_ind = [self.class_values.index(x) for x in cur_values]\n        probs = prediction.results.unmapped_probabilities\n        new_probs = numpy.full(\n            (probs.shape[0], len(self.class_values)), numpy.nan)\n        new_probs[:, new_ind] = probs\n        return new_probs\n\n    def _update_predictions_model(self):\n        results = []\n        headers = []\n        for p in self._non_errored_predictors():\n            values = p.results.unmapped_predicted\n            target = p.predictor.domain.class_var\n            if target.is_discrete:\n                # order probabilities in order from Show prob. for\n                prob = self._reordered_probabilities(p)\n                values = [Value(target, v) for v in values]\n            else:\n                prob = numpy.zeros((len(values), 0))\n            results.append((values, prob))\n            headers.append(p.predictor.name)\n\n        if results:\n            results = list(zip(*(zip(*res) for res in results)))\n            model = PredictionsModel(results, headers)\n        else:\n            model = None\n\n        predmodel = PredictionsSortProxyModel()\n        predmodel.setSourceModel(model)\n        predmodel.setDynamicSortFilter(True)\n        self.predictionsview.setModel(predmodel)\n        hheader = self.predictionsview.horizontalHeader()\n        hheader.setSortIndicatorShown(False)\n        # SortFilterProxyModel is slow due to large abstraction overhead\n        # (every comparison triggers multiple `model.index(...)`,\n        # model.rowCount(...), `model.parent`, ... calls)\n        hheader.setSectionsClickable(predmodel.rowCount() < 20000)\n\n        self.predictionsview.model().list_sorted.connect(\n            partial(\n                self._update_data_sort_order, self.predictionsview,\n                self.dataview))\n\n        self.predictionsview.resizeColumnsToContents()\n\n    @staticmethod\n    def _update_data_sort_order(sort_source_view, sort_dest_view):\n        sort_dest = sort_dest_view.model()\n        sort_source = sort_source_view.model()\n        sortindicatorshown = False\n        if sort_dest is not None:\n            assert isinstance(sort_dest, QSortFilterProxyModel)\n            n = sort_dest.rowCount()\n            if sort_source is not None and sort_source.sortColumn() >= 0:\n                sortind = numpy.argsort(\n                    [sort_source.mapToSource(sort_source.index(i, 0)).row()\n                     for i in range(n)])\n                sortind = numpy.array(sortind, numpy.int)\n                sortindicatorshown = True\n            else:\n                sortind = None\n\n            sort_dest.setSortIndices(sortind)\n\n        sort_dest_view.horizontalHeader().setSortIndicatorShown(\n            False)\n        sort_source_view.horizontalHeader().setSortIndicatorShown(\n            sortindicatorshown)\n\n    def _reset_order(self):\n        datamodel = self.dataview.model()\n        predmodel = self.predictionsview.model()\n        if datamodel is not None:\n            datamodel.setSortIndices(None)\n            datamodel.sort(-1)\n        if predmodel is not None:\n            predmodel.setSortIndices(None)\n            predmodel.sort(-1)\n        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)\n        self.dataview.horizontalHeader().setSortIndicatorShown(False)\n\n    def _all_color_values(self):\n        \"\"\"\n        Return list of colors together with their values from all predictors\n        classes. Colors and values are sorted according to the values order\n        for simpler comparison.\n        \"\"\"\n        predictors = self._non_errored_predictors()\n        color_values = [\n            list(zip(*sorted(zip(\n                p.predictor.domain.class_var.colors,\n                p.predictor.domain.class_var.values\n            ), key=itemgetter(1))))\n            for p in predictors if p.predictor.domain.class_var.is_discrete\n        ]\n        return color_values if color_values else [([], [])]\n\n    @staticmethod\n    def _colors_match(colors1, values1, color2, values2):\n        \"\"\"\n        Test whether colors for values match. Colors matches when all\n        values match for shorter list and colors match for shorter list.\n        It is assumed that values will be sorted together with their colors.\n        \"\"\"\n        shorter_length = min(len(colors1), len(color2))\n        return (values1[:shorter_length] == values2[:shorter_length]\n                and (numpy.array(colors1[:shorter_length]) ==\n                     numpy.array(color2[:shorter_length])).all())\n\n    def _get_colors(self):\n        \"\"\"\n        Defines colors for values. If colors match in all models use the union\n        otherwise use standard colors.\n        \"\"\"\n        all_colors_values = self._all_color_values()\n        base_color, base_values = all_colors_values[0]\n        for c, v in all_colors_values[1:]:\n            if not self._colors_match(base_color, base_values, c, v):\n                base_color = []\n                break\n            # replace base_color if longer\n            if len(v) > len(base_color):\n                base_color = c\n                base_values = v\n\n        if len(base_color) != len(self.class_values):\n            return ColorPaletteGenerator.palette(len(self.class_values))\n        # reorder colors to widgets order\n        colors = [None] * len(self.class_values)\n        for c, v in zip(base_color, base_values):\n            colors[self.class_values.index(v)] = c\n        return colors\n\n    def _update_prediction_delegate(self):\n        self._delegates.clear()\n        colors = self._get_colors()\n        for col, slot in enumerate(self.predictors.values()):\n            target = slot.predictor.domain.class_var\n            shown_probs = (\n                () if target.is_continuous else\n                [val if self.class_values[val] in target.values else None\n                 for val in self.selected_classes]\n            )\n            delegate = PredictionsItemDelegate(\n                None if target.is_continuous else self.class_values,\n                colors,\n                shown_probs,\n                target.format_str if target.is_continuous else None\n            )\n            # QAbstractItemView does not take ownership of delegates, so we must\n            self._delegates.append(delegate)\n            self.predictionsview.setItemDelegateForColumn(col, delegate)\n            self.predictionsview.setColumnHidden(col, False)\n\n        self.predictionsview.resizeColumnsToContents()\n        self._recompute_splitter_sizes()\n        if self.predictionsview.model() is not None:\n            self.predictionsview.model().setProbInd(self.selected_classes)\n\n    def _recompute_splitter_sizes(self):\n        if not self.data:\n            return\n        view = self.predictionsview\n        self.left_width = \\\n            view.horizontalHeader().length() + view.verticalHeader().width()\n        self._update_splitter()\n\n    def _update_splitter(self):\n        w1, w2 = self.splitter.sizes()\n        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])\n\n    def splitter_resized(self):\n        self.left_width = self.splitter.sizes()[0]\n\n    def commit(self):\n        self._commit_predictions()\n        self._commit_evaluation_results()\n\n    def _commit_evaluation_results(self):\n        slots = [p for p in self._non_errored_predictors()\n                 if p.results.predicted is not None]\n        if not slots:\n            self.Outputs.evaluation_results.send(None)\n            return\n\n        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])\n        data = self.data[~nanmask]\n        results = Results(data, store_data=True)\n        results.folds = None\n        results.row_indices = numpy.arange(len(data))\n        results.actual = data.Y.ravel()\n        results.predicted = numpy.vstack(\n            tuple(p.results.predicted[0][~nanmask] for p in slots))\n        if self.class_var and self.class_var.is_discrete:\n            results.probabilities = numpy.array(\n                [p.results.probabilities[0][~nanmask] for p in slots])\n        results.learner_names = [p.name for p in slots]\n        self.Outputs.evaluation_results.send(results)\n\n    def _commit_predictions(self):\n        if not self.data:\n            self.Outputs.predictions.send(None)\n            return\n\n        newmetas = []\n        newcolumns = []\n        for slot in self._non_errored_predictors():\n            if slot.predictor.domain.class_var.is_discrete:\n                self._add_classification_out_columns(slot, newmetas, newcolumns)\n            else:\n                self._add_regression_out_columns(slot, newmetas, newcolumns)\n\n        attrs = list(self.data.domain.attributes)\n        metas = list(self.data.domain.metas) + newmetas\n        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)\n        predictions = self.data.transform(domain)\n        if newcolumns:\n            newcolumns = numpy.hstack(\n                [numpy.atleast_2d(cols) for cols in newcolumns])\n            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns\n        self.Outputs.predictions.send(predictions)\n\n    @staticmethod\n    def _add_classification_out_columns(slot, newmetas, newcolumns):\n        # Mapped or unmapped predictions?!\n        # Or provide a checkbox so the user decides?\n        pred = slot.predictor\n        name = pred.name\n        values = pred.domain.class_var.values\n        newmetas.append(DiscreteVariable(name=name, values=values))\n        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))\n        newmetas += [ContinuousVariable(name=f\"{name} ({value})\")\n                     for value in values]\n        newcolumns.append(slot.results.unmapped_probabilities)\n\n    @staticmethod\n    def _add_regression_out_columns(slot, newmetas, newcolumns):\n        newmetas.append(ContinuousVariable(name=slot.predictor.name))\n        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))\n\n    def send_report(self):\n        def merge_data_with_predictions():\n            data_model = self.dataview.model()\n            predictions_model = self.predictionsview.model()\n\n            # use ItemDelegate to style prediction values\n            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())\n\n            # iterate only over visible columns of data's QTableView\n            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),\n                                         range(data_model.columnCount())))\n\n            # print header\n            yield [''] + \\\n                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in range(predictions_model.columnCount())] + \\\n                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)\n                   for col in iter_data_cols]\n\n            # print data & predictions\n            for i in range(data_model.rowCount()):\n                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \\\n                      [style(predictions_model.data(predictions_model.index(i, j)))\n                       for j in range(predictions_model.columnCount())] + \\\n                      [data_model.data(data_model.index(i, j))\n                       for j in iter_data_cols]\n\n        if self.data:\n            text = self.infolabel.text().replace('\\n', '<br>')\n            if self.selected_classes:\n                text += '<br>Showing probabilities for: '\n                text += ', '. join([self.class_values[i]\n                                    for i in self.selected_classes])\n            self.report_paragraph('Info', text)\n            self.report_table(\"Data & Predictions\", merge_data_with_predictions(),\n                              header_rows=1, header_columns=1)\n\n    def resizeEvent(self, event):\n        super().resizeEvent(event)\n        self._update_splitter()\n\n    def showEvent(self, event):\n        super().showEvent(event)\n        QTimer.singleShot(0, self._update_splitter)\n\n\nclass PredictionsItemDelegate(QStyledItemDelegate):\n    \"\"\"\n    A Item Delegate for custom formatting of predictions/probabilities\n    \"\"\"\n    def __init__(\n            self, class_values, colors, shown_probabilities=(),\n            target_format=None, parent=None,\n    ):\n        super().__init__(parent)\n        self.class_values = class_values  # will be None for continuous\n        self.colors = [QColor(*c) for c in colors]\n        self.target_format = target_format  # target format for cont. vars\n        self.shown_probabilities = self.fmt = self.tooltip = None  # set below\n        self.setFormat(shown_probabilities)\n\n    def setFormat(self, shown_probabilities=()):\n        self.shown_probabilities = shown_probabilities\n        if self.class_values is None:\n            # is continuous class\n            self.fmt = f\"{{value:{self.target_format[1:]}}}\"\n        else:\n            self.fmt = \" \\N{RIGHTWARDS ARROW} \".join(\n                [\" : \".join(f\"{{dist[{i}]:.2f}}\" if i is not None else \"-\"\n                            for i in shown_probabilities)]\n                * bool(shown_probabilities)\n                + [\"{value!s}\"])\n        self.tooltip = \"\"\n        if shown_probabilities:\n            val = ', '.join(\n                self.class_values[i] if i is not None else \"-\"\n                for i in shown_probabilities if i is not None\n            )\n            self.tooltip = f\"p({val})\"\n\n    def displayText(self, value, _locale):\n        try:\n            value, dist = value\n        except ValueError:\n            return \"\"\n        else:\n            return self.fmt.format(value=value, dist=dist)\n\n    def helpEvent(self, event, view, option, index):\n        if self.tooltip is not None:\n            # ... but can be an empty string, so the current tooltip is removed\n            QToolTip.showText(event.globalPos(), self.tooltip, view)\n            return True\n        else:\n            return super().helpEvent(event, view, option, index)\n\n    def initStyleOption(self, option, index):\n        super().initStyleOption(option, index)\n        if self.class_values is None:\n            option.displayAlignment = \\\n                (option.displayAlignment & Qt.AlignVertical_Mask) | \\\n                Qt.AlignRight\n\n    def sizeHint(self, option, index):\n        # reimplemented\n        sh = super().sizeHint(option, index)\n        if option.widget is not None:\n            style = option.widget.style()\n        else:\n            style = QApplication.style()\n        margin = style.pixelMetric(\n            QStyle.PM_FocusFrameHMargin, option, option.widget) + 1\n        metrics = option.fontMetrics\n        height = sh.height() + metrics.leading() + 2 * margin\n        return QSize(sh.width(), height)\n\n    @staticmethod\n    def distribution(index):\n        value = index.data(Qt.DisplayRole)\n        if isinstance(value, tuple) and len(value) == 2:\n            _, dist = value\n            return dist\n        else:\n            return None\n\n    def paint(self, painter, option, index):\n        dist = self.distribution(index)\n        if dist is None or self.colors is None:\n            super().paint(painter, option, index)\n            return\n\n        if option.widget is not None:\n            style = option.widget.style()\n        else:\n            style = QApplication.style()\n\n        self.initStyleOption(option, index)\n\n        text = option.text\n        metrics = option.fontMetrics\n\n        margin = style.pixelMetric(\n            QStyle.PM_FocusFrameHMargin, option, option.widget) + 1\n        bottommargin = min(margin, 1)\n        rect = option.rect.adjusted(margin, margin, -margin, -bottommargin)\n\n        textrect = style.subElementRect(\n            QStyle.SE_ItemViewItemText, option, option.widget)\n        # Are the margins included in the subElementRect?? -> No!\n        textrect = textrect.adjusted(margin, margin, -margin, -bottommargin)\n\n        text = option.fontMetrics.elidedText(\n            text, option.textElideMode, textrect.width())\n\n        spacing = max(metrics.leading(), 1)\n\n        distheight = rect.height() - metrics.height() - spacing\n        distheight = numpy.clip(distheight, 2, metrics.height())\n\n        painter.save()\n        painter.setClipRect(option.rect)\n        painter.setFont(option.font)\n        painter.setRenderHint(QPainter.Antialiasing)\n\n        style.drawPrimitive(\n            QStyle.PE_PanelItemViewRow, option, painter, option.widget)\n        style.drawPrimitive(\n            QStyle.PE_PanelItemViewItem, option, painter, option.widget)\n\n        if option.state & QStyle.State_Selected:\n            color = option.palette.highlightedText().color()\n        else:\n            color = option.palette.text().color()\n        painter.setPen(QPen(color))\n\n        textrect = textrect.adjusted(0, 0, 0, -distheight - spacing)\n        distrect = QRect(\n            textrect.bottomLeft() + QPoint(0, spacing),\n            QSize(rect.width(), distheight))\n        painter.setPen(QPen(Qt.lightGray, 0.3))\n        self.drawDistBar(painter, distrect, dist)\n        painter.restore()\n        if text:\n            style.drawItemText(\n                painter, textrect, option.displayAlignment, option.palette,\n                option.state & QStyle.State_Enabled, text)\n\n    def drawDistBar(self, painter, rect, distribution):\n        painter.save()\n        painter.translate(rect.topLeft())\n        for i in self.shown_probabilities:\n            if i is None:\n                continue\n            dvalue = distribution[i]\n            if not dvalue > 0:  # This also skips nans\n                continue\n            painter.setBrush(self.colors[i])\n            width = rect.width() * dvalue\n            painter.drawRoundedRect(QRectF(0, 0, width, rect.height()), 1, 2)\n            painter.translate(width, 0.0)\n        painter.restore()\n\n\nclass SortProxyModel(QSortFilterProxyModel):\n    \"\"\"\n    QSortFilter model used in both TableView and PredictionsView\n    \"\"\"\n    list_sorted = pyqtSignal()\n\n    def __init__(self, parent=None):\n        super().__init__(parent)\n        self.__sortInd = None\n\n    def setSortIndices(self, indices):\n        if indices is not None:\n            indices = numpy.array(indices, dtype=numpy.int)\n            if indices.shape != (self.rowCount(),):\n                raise ValueError(\"indices.shape != (self.rowCount(),)\")\n            indices.flags.writeable = False\n\n        self.__sortInd = indices\n\n        if self.__sortInd is not None:\n            self.custom_sort(0)  # need valid order to call lessThan\n\n    def lessThan(self, left, right):\n        if self.__sortInd is None:\n            return super().lessThan(left, right)\n\n        assert not (left.parent().isValid() or right.parent().isValid()), \\\n            \"Not a table model\"\n\n        rleft, rright = left.row(), right.row()\n        try:\n            ileft, iright = self.__sortInd[rleft], self.__sortInd[rright]\n        except IndexError:\n            return False\n        else:\n            return ileft < iright\n\n    def isSorted(self):\n        return self.__sortInd is not None\n\n    def sort(self, n, order=Qt.AscendingOrder):\n        \"\"\"\n        This sort is called only on click, in other cases we manually call\n        custom_sort\n        \"\"\"\n        # reset sort - otherwise when same parameters set by lessThan function\n        # clicking on header would not trigger resort\n        self.__sortInd = None\n        self.custom_sort(n, order=order)\n        self.list_sorted.emit()\n\n    def custom_sort(self, n, order=Qt.AscendingOrder):\n        \"\"\"\n        When sorting is dmanded because of sort change in the other view\n        this sorting is called. It will not reset __sortInd to None.\n        \"\"\"\n        if self.sortColumn() == n and self.sortOrder() == order:\n            self.invalidate()\n        else:\n            super().sort(n, order)  # need some valid sort column\n\n\nclass PredictionsSortProxyModel(SortProxyModel):\n    def __init__(self, parent=None):\n        super().__init__(parent)\n        self.__probInd = None\n\n    def setProbInd(self, indices):\n        self.__probInd = indices\n        self.invalidate()\n        self.list_sorted.emit()\n\n    def lessThan(self, left, right):\n        if self.isSorted():\n            return super().lessThan(left, right)\n\n        role = self.sortRole()\n        left_data = self.sourceModel().data(left, role)\n        right_data = self.sourceModel().data(right, role)\n\n        return self._key(left_data) < self._key(right_data)\n\n    def _key(self, prediction):\n        value, probs = prediction\n        if probs is not None:\n            if self.__probInd is not None:\n                probs = probs[self.__probInd]\n            probs = tuple(probs)\n\n        return probs, value\n\n\nclass PredictionsModel(QAbstractTableModel):\n    def __init__(self, table=None, headers=None, parent=None):\n        super().__init__(parent)\n        self._table = [[]] if table is None else table\n        if headers is None:\n            headers = [None] * len(self._table)\n        self._header = headers\n        self.__columnCount = max([len(row) for row in self._table] or [0])\n\n    def rowCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else len(self._table)\n\n    def columnCount(self, parent=QModelIndex()):\n        return 0 if parent.isValid() else self.__columnCount\n\n    def _value(self, index):\n        return self._table[index.row()][index.column()]\n\n    def data(self, index, role=Qt.DisplayRole):\n        if role in (Qt.DisplayRole, Qt.EditRole):\n            return self._value(index)\n        return None\n\n    def headerData(self, section, orientation, role=Qt.DisplayRole):\n        if orientation == Qt.Vertical and role == Qt.DisplayRole:\n            return str(section + 1)\n        if orientation == Qt.Horizontal and role == Qt.DisplayRole:\n            return (self._header[section] if section < len(self._header)\n                    else str(section))\n        return None\n\n\nclass TableView(QTableView):\n    MaxSizeHintSamples = 1000\n\n    def sizeHintForColumn(self, column):\n        \"\"\"\n        Reimplemented from `QTableView.sizeHintForColumn`\n\n        Note: This does not match the QTableView's implementation,\n        in particular size hints from editor/index widgets are not taken\n        into account.\n\n        Parameters\n        ----------\n        column : int\n        \"\"\"\n        # This is probably not needed in Qt5?\n        if self.model() is None:\n            return -1\n\n        self.ensurePolished()\n        model = self.model()\n        vheader = self.verticalHeader()\n        top = vheader.visualIndexAt(0)\n        bottom = vheader.visualIndexAt(self.viewport().height())\n        if bottom < 0:\n            bottom = self.model().rowCount()\n\n        options = self.viewOptions()\n        options.widget = self\n\n        width = 0\n        sample_count = 0\n\n        for row in range(top, bottom):\n            if not vheader.isSectionHidden(vheader.logicalIndex(row)):\n                index = model.index(row, column)\n                delegate = self.itemDelegate(index)\n                if not delegate:\n                    continue\n                size = delegate.sizeHint(options, index)\n                width = max(size.width(), width)\n                sample_count += 1\n\n            if sample_count >= TableView.MaxSizeHintSamples:\n                break\n\n        return width + 1 if self.showGrid() else width\n\n\ndef tool_tip(value):\n    value, dist = value\n    if dist is not None:\n        return \"{!s} {!s}\".format(value, dist)\n    else:\n        return str(value)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    filename = \"iris.tab\"\n    iris = Orange.data.Table(filename)\n    idom = iris.domain\n    dom = Domain(\n        idom.attributes,\n        DiscreteVariable(idom.class_var.name, idom.class_var.values[1::-1])\n    )\n    iris2 = iris[:100].transform(dom)\n\n    def pred_error(data, *args, **kwargs):\n        raise ValueError\n\n    pred_error.domain = iris.domain\n    pred_error.name = \"To err is human\"\n\n    if iris.domain.has_discrete_class:\n        predictors_ = [\n            Orange.classification.SVMLearner(probability=True)(iris2),\n            Orange.classification.LogisticRegressionLearner()(iris),\n            pred_error\n        ]\n    elif iris.domain.has_continuous_class:\n        predictors_ = [\n            Orange.regression.RidgeRegressionLearner(alpha=1.0)(iris),\n            Orange.regression.LinearRegressionLearner()(iris),\n            pred_error\n        ]\n    else:\n        predictors_ = [pred_error]\n\n    WidgetPreview(OWPredictions).run(\n        set_data=iris2,\n        set_predictor=[(pred, i) for i, pred in enumerate(predictors_)])\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:** `send_report` Method Raises AttributeError Due to Missing `infolabel` in Predictions Widget

**Description:**
When attempting to generate a report using the `send_report` method in the Predictions widget, an `AttributeError` is thrown because the widget lacks the `infolabel` attribute. This prevents the report from being created successfully.

**Example Code:**
```python
widget = OWPredictions()
widget.send_report()
```

**Expected Behavior:**
Calling `send_report` should generate and compile the report without any errors, regardless of whether `infolabel` is present in the widget.

**Actual Behavior:**
An error occurs indicating that the `infolabel` attribute does not exist in the `OWPredictions` object.

**Error Message:**
```
AttributeError: 'OWPredictions' object has no attribute 'infolabel'
```
[/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/evaluate/owpredictions.py
from collections import namedtuple
from functools import partial
from operator import itemgetter

import numpy
from AnyQt.QtWidgets import (
    QTableView, QListWidget, QSplitter, QStyledItemDelegate,
    QToolTip, QStyle, QApplication, QSizePolicy)
from AnyQt.QtGui import QPainter, QStandardItem, QPen, QColor
from AnyQt.QtCore import (
    Qt, QSize, QRect, QRectF, QPoint, QLocale,
    QModelIndex, QAbstractTableModel, QSortFilterProxyModel, pyqtSignal, QTimer)

import Orange
from Orange.evaluation import Results
from Orange.base import Model
from Orange.data import ContinuousVariable, DiscreteVariable, Value, Domain
from Orange.data.table import DomainTransformationError
from Orange.widgets import gui, settings
from Orange.widgets.evaluate.utils import (
    ScoreTable, usable_scorers, learner_name, scorer_caller)
from Orange.widgets.utils.colorpalette import ColorPaletteGenerator
from Orange.widgets.utils.widgetpreview import WidgetPreview
from Orange.widgets.widget import OWWidget, Msg, Input, Output
from Orange.widgets.utils.itemmodels import TableModel
from Orange.widgets.utils.sql import check_sql_input


# Input slot for the Predictors channel
PredictorSlot = namedtuple(
    "PredictorSlot",
    ["predictor",  # The `Model` instance
     "name",       # Predictor name
     "results"]    # Computed prediction results or None.
)


class OWPredictions(OWWidget):
    name = "Predictions"
    icon = "icons/Predictions.svg"
    priority = 200
    description = "Display predictions of models for an input dataset."
    keywords = []

    class Inputs:
        data = Input("Data", Orange.data.Table)
        predictors = Input("Predictors", Model, multiple=True)

    class Outputs:
        predictions = Output("Predictions", Orange.data.Table)
        evaluation_results = Output("Evaluation Results", Results)

    class Warning(OWWidget.Warning):
        empty_data = Msg("Empty dataset")
        wrong_targets = Msg(
            "Some model(s) predict a different target (see more ...)\n{}")

    class Error(OWWidget.Error):
        predictor_failed = Msg("Some predictor(s) failed (see more ...)\n{}")
        scorer_failed = Msg("Some scorer(s) failed (see more ...)\n{}")

    settingsHandler = settings.ClassValuesContextHandler()
    score_table = settings.SettingProvider(ScoreTable)

    #: List of selected class value indices in the `class_values` list
    selected_classes = settings.ContextSetting([])

    def __init__(self):
        super().__init__()

        self.data = None  # type: Optional[Orange.data.Table]
        self.predictors = {}  # type: Dict[object, PredictorSlot]
        self.class_values = []  # type: List[str]
        self._delegates = []
        self.left_width = 10

        gui.listBox(self.controlArea, self, "selected_classes", "class_values",
                    box="Show probabibilities for",
                    callback=self._update_prediction_delegate,
                    selectionMode=QListWidget.ExtendedSelection,
                    addSpace=False,
                    sizePolicy=(QSizePolicy.Preferred, QSizePolicy.Preferred))
        gui.rubber(self.controlArea)
        self.reset_button = gui.button(
            self.controlArea, self, "Restore Original Order",
            callback=self._reset_order,
            tooltip="Show rows in the original order")

        table_opts = dict(horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOn,
                          horizontalScrollMode=QTableView.ScrollPerPixel,
                          selectionMode=QTableView.NoSelection,
                          focusPolicy=Qt.StrongFocus)
        self.dataview = TableView(
            sortingEnabled=True,
            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn,
            **table_opts)
        self.predictionsview = TableView(
            sortingEnabled=True,
            verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
            **table_opts)
        self.dataview.verticalHeader().hide()
        dsbar = self.dataview.verticalScrollBar()
        psbar = self.predictionsview.verticalScrollBar()
        psbar.valueChanged.connect(dsbar.setValue)
        dsbar.valueChanged.connect(psbar.setValue)

        self.dataview.verticalHeader().setDefaultSectionSize(22)
        self.predictionsview.verticalHeader().setDefaultSectionSize(22)
        self.dataview.verticalHeader().sectionResized.connect(
            lambda index, _, size:
            self.predictionsview.verticalHeader().resizeSection(index, size))

        self.splitter = QSplitter(
            orientation=Qt.Horizontal, childrenCollapsible=False, handleWidth=2)
        self.splitter.splitterMoved.connect(self.splitter_resized)
        self.splitter.addWidget(self.predictionsview)
        self.splitter.addWidget(self.dataview)

        self.score_table = ScoreTable(self)
        self.vsplitter = gui.vBox(self.mainArea)
        self.vsplitter.layout().addWidget(self.splitter)
        self.vsplitter.layout().addWidget(self.score_table.view)

    @Inputs.data
    @check_sql_input
    def set_data(self, data):
        self.Warning.empty_data(shown=data is not None and not data)
        self.data = data
        if not data:
            self.dataview.setModel(None)
            self.predictionsview.setModel(None)
        else:
            # force full reset of the view's HeaderView state
            self.dataview.setModel(None)
            model = TableModel(data, parent=None)
            modelproxy = SortProxyModel()
            modelproxy.setSourceModel(model)
            self.dataview.setModel(modelproxy)

            self.dataview.model().list_sorted.connect(
                partial(
                    self._update_data_sort_order, self.dataview,
                    self.predictionsview))

        self._invalidate_predictions()

    @property
    def class_var(self):
        return self.data and self.data.domain.class_var

    # pylint: disable=redefined-builtin
    @Inputs.predictors
    def set_predictor(self, predictor=None, id=None):
        if id in self.predictors:
            if predictor is not None:
                self.predictors[id] = self.predictors[id]._replace(
                    predictor=predictor, name=predictor.name, results=None)
            else:
                del self.predictors[id]
        elif predictor is not None:
            self.predictors[id] = PredictorSlot(predictor, predictor.name, None)

    def _set_class_values(self):
        class_values = []
        for slot in self.predictors.values():
            class_var = slot.predictor.domain.class_var
            if class_var and class_var.is_discrete:
                for value in class_var.values:
                    if value not in class_values:
                        class_values.append(value)

        if self.class_var and self.class_var.is_discrete:
            values = self.class_var.values
            self.class_values = sorted(
                class_values, key=lambda val: val not in values)
            self.selected_classes = [
                i for i, name in enumerate(class_values) if name in values]
        else:
            self.class_values = class_values  # This assignment updates listview
            self.selected_classes = []

    def handleNewSignals(self):
        self._set_class_values()
        self._call_predictors()
        self._update_scores()
        self._update_predictions_model()
        self._update_prediction_delegate()
        self._set_errors()
        self._update_info()
        self.commit()

    def _call_predictors(self):
        if not self.data:
            return
        if self.class_var:
            domain = self.data.domain
            classless_data = self.data.transform(
                Domain(domain.attributes, None, domain.metas))
        else:
            classless_data = self.data

        for inputid, slot in self.predictors.items():
            if isinstance(slot.results, Results):
                continue

            predictor = slot.predictor
            try:
                if predictor.domain.class_var.is_discrete:
                    pred, prob = predictor(classless_data, Model.ValueProbs)
                else:
                    pred = predictor(classless_data, Model.Value)
                    prob = numpy.zeros((len(pred), 0))
            except (ValueError, DomainTransformationError) as err:
                self.predictors[inputid] = \
                    slot._replace(results=f"{predictor.name}: {err}")
                continue

            results = Results()
            results.data = self.data
            results.domain = self.data.domain
            results.row_indices = numpy.arange(len(self.data))
            results.folds = (Ellipsis, )
            results.actual = self.data.Y
            results.unmapped_probabilities = prob
            results.unmapped_predicted = pred
            results.probabilities = results.predicted = None
            self.predictors[inputid] = slot._replace(results=results)

            target = predictor.domain.class_var
            if target != self.class_var:
                continue

            if target is not self.class_var and target.is_discrete:
                backmappers, n_values = predictor.get_backmappers(self.data)
                prob = predictor.backmap_probs(prob, n_values, backmappers)
                pred = predictor.backmap_value(pred, prob, n_values, backmappers)
            results.predicted = pred.reshape((1, len(self.data)))
            results.probabilities = prob.reshape((1,) + prob.shape)

    def _update_scores(self):
        model = self.score_table.model
        model.clear()
        scorers = usable_scorers(self.class_var) if self.class_var else []
        self.score_table.update_header(scorers)
        errors = []
        for inputid, pred in self.predictors.items():
            results = self.predictors[inputid].results
            if not isinstance(results, Results) or results.predicted is None:
                continue
            row = [QStandardItem(learner_name(pred.predictor)),
                   QStandardItem("N/A"), QStandardItem("N/A")]
            for scorer in scorers:
                item = QStandardItem()
                try:
                    score = scorer_caller(scorer, results)()[0]
                    item.setText(f"{score:.3f}")
                except Exception as exc:  # pylint: disable=broad-except
                    item.setToolTip(str(exc))
                    if scorer.name in self.score_table.shown_scores:
                        errors.append(str(exc))
                row.append(item)
            self.score_table.model.appendRow(row)

        view = self.score_table.view
        if model.rowCount():
            view.setVisible(True)
            view.ensurePolished()
            view.setFixedHeight(
                5 + view.horizontalHeader().height() +
                view.verticalHeader().sectionSize(0) * model.rowCount())
        else:
            view.setVisible(False)

        self.Error.scorer_failed("\n".join(errors), shown=bool(errors))

    def _set_errors(self):
        # Not all predictors are run every time, so errors can't be collected
        # in _call_predictors
        errors = "\n".join(
            f"- {p.predictor.name}: {p.results}"
            for p in self.predictors.values()
            if isinstance(p.results, str) and p.results)
        self.Error.predictor_failed(errors, shown=bool(errors))

        if self.class_var:
            inv_targets = "\n".join(
                f"- {pred.name} predicts '{pred.domain.class_var.name}'"
                for pred in (p.predictor for p in self.predictors.values()
                             if isinstance(p.results, Results)
                             and p.results.probabilities is None))
            self.Warning.wrong_targets(inv_targets, shown=bool(inv_targets))
        else:
            self.Warning.wrong_targets.clear()

    def _update_info(self):
        n_predictors = len(self.predictors)
        if not self.data and not n_predictors:
            self.info.set_input_summary(self.info.NoInput)
            return

        n_valid = len(self._non_errored_predictors())
        summary = str(len(self.data)) if self.data else "0"
        details = f"{len(self.data)} instances" if self.data else "No data"
        details += f"\n{n_predictors} models" if n_predictors else "No models"
        if n_valid != n_predictors:
            details += f" ({n_predictors - n_valid} failed)"
        self.info.set_input_summary(summary, details)

    def _invalidate_predictions(self):
        for inputid, pred in list(self.predictors.items()):
            self.predictors[inputid] = pred._replace(results=None)

    def _non_errored_predictors(self):
        return [p for p in self.predictors.values()
                if isinstance(p.results, Results)]

    def _reordered_probabilities(self, prediction):
        cur_values = prediction.predictor.domain.class_var.values
        new_ind = [self.class_values.index(x) for x in cur_values]
        probs = prediction.results.unmapped_probabilities
        new_probs = numpy.full(
            (probs.shape[0], len(self.class_values)), numpy.nan)
        new_probs[:, new_ind] = probs
        return new_probs

    def _update_predictions_model(self):
        results = []
        headers = []
        for p in self._non_errored_predictors():
            values = p.results.unmapped_predicted
            target = p.predictor.domain.class_var
            if target.is_discrete:
                # order probabilities in order from Show prob. for
                prob = self._reordered_probabilities(p)
                values = [Value(target, v) for v in values]
            else:
                prob = numpy.zeros((len(values), 0))
            results.append((values, prob))
            headers.append(p.predictor.name)

        if results:
            results = list(zip(*(zip(*res) for res in results)))
            model = PredictionsModel(results, headers)
        else:
            model = None

        predmodel = PredictionsSortProxyModel()
        predmodel.setSourceModel(model)
        predmodel.setDynamicSortFilter(True)
        self.predictionsview.setModel(predmodel)
        hheader = self.predictionsview.horizontalHeader()
        hheader.setSortIndicatorShown(False)
        # SortFilterProxyModel is slow due to large abstraction overhead
        # (every comparison triggers multiple `model.index(...)`,
        # model.rowCount(...), `model.parent`, ... calls)
        hheader.setSectionsClickable(predmodel.rowCount() < 20000)

        self.predictionsview.model().list_sorted.connect(
            partial(
                self._update_data_sort_order, self.predictionsview,
                self.dataview))

        self.predictionsview.resizeColumnsToContents()

    @staticmethod
    def _update_data_sort_order(sort_source_view, sort_dest_view):
        sort_dest = sort_dest_view.model()
        sort_source = sort_source_view.model()
        sortindicatorshown = False
        if sort_dest is not None:
            assert isinstance(sort_dest, QSortFilterProxyModel)
            n = sort_dest.rowCount()
            if sort_source is not None and sort_source.sortColumn() >= 0:
                sortind = numpy.argsort(
                    [sort_source.mapToSource(sort_source.index(i, 0)).row()
                     for i in range(n)])
                sortind = numpy.array(sortind, numpy.int)
                sortindicatorshown = True
            else:
                sortind = None

            sort_dest.setSortIndices(sortind)

        sort_dest_view.horizontalHeader().setSortIndicatorShown(
            False)
        sort_source_view.horizontalHeader().setSortIndicatorShown(
            sortindicatorshown)

    def _reset_order(self):
        datamodel = self.dataview.model()
        predmodel = self.predictionsview.model()
        if datamodel is not None:
            datamodel.setSortIndices(None)
            datamodel.sort(-1)
        if predmodel is not None:
            predmodel.setSortIndices(None)
            predmodel.sort(-1)
        self.predictionsview.horizontalHeader().setSortIndicatorShown(False)
        self.dataview.horizontalHeader().setSortIndicatorShown(False)

    def _all_color_values(self):
        """
        Return list of colors together with their values from all predictors
        classes. Colors and values are sorted according to the values order
        for simpler comparison.
        """
        predictors = self._non_errored_predictors()
        color_values = [
            list(zip(*sorted(zip(
                p.predictor.domain.class_var.colors,
                p.predictor.domain.class_var.values
            ), key=itemgetter(1))))
            for p in predictors if p.predictor.domain.class_var.is_discrete
        ]
        return color_values if color_values else [([], [])]

    @staticmethod
    def _colors_match(colors1, values1, color2, values2):
        """
        Test whether colors for values match. Colors matches when all
        values match for shorter list and colors match for shorter list.
        It is assumed that values will be sorted together with their colors.
        """
        shorter_length = min(len(colors1), len(color2))
        return (values1[:shorter_length] == values2[:shorter_length]
                and (numpy.array(colors1[:shorter_length]) ==
                     numpy.array(color2[:shorter_length])).all())

    def _get_colors(self):
        """
        Defines colors for values. If colors match in all models use the union
        otherwise use standard colors.
        """
        all_colors_values = self._all_color_values()
        base_color, base_values = all_colors_values[0]
        for c, v in all_colors_values[1:]:
            if not self._colors_match(base_color, base_values, c, v):
                base_color = []
                break
            # replace base_color if longer
            if len(v) > len(base_color):
                base_color = c
                base_values = v

        if len(base_color) != len(self.class_values):
            return ColorPaletteGenerator.palette(len(self.class_values))
        # reorder colors to widgets order
        colors = [None] * len(self.class_values)
        for c, v in zip(base_color, base_values):
            colors[self.class_values.index(v)] = c
        return colors

    def _update_prediction_delegate(self):
        self._delegates.clear()
        colors = self._get_colors()
        for col, slot in enumerate(self.predictors.values()):
            target = slot.predictor.domain.class_var
            shown_probs = (
                () if target.is_continuous else
                [val if self.class_values[val] in target.values else None
                 for val in self.selected_classes]
            )
            delegate = PredictionsItemDelegate(
                None if target.is_continuous else self.class_values,
                colors,
                shown_probs,
                target.format_str if target.is_continuous else None
            )
            # QAbstractItemView does not take ownership of delegates, so we must
            self._delegates.append(delegate)
            self.predictionsview.setItemDelegateForColumn(col, delegate)
            self.predictionsview.setColumnHidden(col, False)

        self.predictionsview.resizeColumnsToContents()
        self._recompute_splitter_sizes()
        if self.predictionsview.model() is not None:
            self.predictionsview.model().setProbInd(self.selected_classes)

    def _recompute_splitter_sizes(self):
        if not self.data:
            return
        view = self.predictionsview
        self.left_width = \
            view.horizontalHeader().length() + view.verticalHeader().width()
        self._update_splitter()

    def _update_splitter(self):
        w1, w2 = self.splitter.sizes()
        self.splitter.setSizes([self.left_width, w1 + w2 - self.left_width])

    def splitter_resized(self):
        self.left_width = self.splitter.sizes()[0]

    def commit(self):
        self._commit_predictions()
        self._commit_evaluation_results()

    def _commit_evaluation_results(self):
        slots = [p for p in self._non_errored_predictors()
                 if p.results.predicted is not None]
        if not slots:
            self.Outputs.evaluation_results.send(None)
            return

        nanmask = numpy.isnan(self.data.get_column_view(self.class_var)[0])
        data = self.data[~nanmask]
        results = Results(data, store_data=True)
        results.folds = None
        results.row_indices = numpy.arange(len(data))
        results.actual = data.Y.ravel()
        results.predicted = numpy.vstack(
            tuple(p.results.predicted[0][~nanmask] for p in slots))
        if self.class_var and self.class_var.is_discrete:
            results.probabilities = numpy.array(
                [p.results.probabilities[0][~nanmask] for p in slots])
        results.learner_names = [p.name for p in slots]
        self.Outputs.evaluation_results.send(results)

    def _commit_predictions(self):
        if not self.data:
            self.Outputs.predictions.send(None)
            return

        newmetas = []
        newcolumns = []
        for slot in self._non_errored_predictors():
            if slot.predictor.domain.class_var.is_discrete:
                self._add_classification_out_columns(slot, newmetas, newcolumns)
            else:
                self._add_regression_out_columns(slot, newmetas, newcolumns)

        attrs = list(self.data.domain.attributes)
        metas = list(self.data.domain.metas) + newmetas
        domain = Orange.data.Domain(attrs, self.class_var, metas=metas)
        predictions = self.data.transform(domain)
        if newcolumns:
            newcolumns = numpy.hstack(
                [numpy.atleast_2d(cols) for cols in newcolumns])
            predictions.metas[:, -newcolumns.shape[1]:] = newcolumns
        self.Outputs.predictions.send(predictions)

    @staticmethod
    def _add_classification_out_columns(slot, newmetas, newcolumns):
        # Mapped or unmapped predictions?!
        # Or provide a checkbox so the user decides?
        pred = slot.predictor
        name = pred.name
        values = pred.domain.class_var.values
        newmetas.append(DiscreteVariable(name=name, values=values))
        newcolumns.append(slot.results.unmapped_predicted.reshape(-1, 1))
        newmetas += [ContinuousVariable(name=f"{name} ({value})")
                     for value in values]
        newcolumns.append(slot.results.unmapped_probabilities)

    @staticmethod
    def _add_regression_out_columns(slot, newmetas, newcolumns):
        newmetas.append(ContinuousVariable(name=slot.predictor.name))
        newcolumns.append(slot.results.unmapped_predicted.reshape((-1, 1)))

    def send_report(self):
        def merge_data_with_predictions():
            data_model = self.dataview.model()
            predictions_model = self.predictionsview.model()

            # use ItemDelegate to style prediction values
            style = lambda x: self.predictionsview.itemDelegate().displayText(x, QLocale())

            # iterate only over visible columns of data's QTableView
            iter_data_cols = list(filter(lambda x: not self.dataview.isColumnHidden(x),
                                         range(data_model.columnCount())))

            # print header
            yield [''] + \
                  [predictions_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)
                   for col in range(predictions_model.columnCount())] + \
                  [data_model.headerData(col, Qt.Horizontal, Qt.DisplayRole)
                   for col in iter_data_cols]

            # print data & predictions
            for i in range(data_model.rowCount()):
                yield [data_model.headerData(i, Qt.Vertical, Qt.DisplayRole)] + \
                      [style(predictions_model.data(predictions_model.index(i, j)))
                       for j in range(predictions_model.columnCount())] + \
                      [data_model.data(data_model.index(i, j))
                       for j in iter_data_cols]

        if self.data:
            text = self.infolabel.text().replace('\n', '<br>')
            if self.selected_classes:
                text += '<br>Showing probabilities for: '
                text += ', '. join([self.class_values[i]
                                    for i in self.selected_classes])
            self.report_paragraph('Info', text)
            self.report_table("Data & Predictions", merge_data_with_predictions(),
                              header_rows=1, header_columns=1)

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self._update_splitter()

    def showEvent(self, event):
        super().showEvent(event)
        QTimer.singleShot(0, self._update_splitter)


class PredictionsItemDelegate(QStyledItemDelegate):
    """
    A Item Delegate for custom formatting of predictions/probabilities
    """
    def __init__(
            self, class_values, colors, shown_probabilities=(),
            target_format=None, parent=None,
    ):
        super().__init__(parent)
        self.class_values = class_values  # will be None for continuous
        self.colors = [QColor(*c) for c in colors]
        self.target_format = target_format  # target format for cont. vars
        self.shown_probabilities = self.fmt = self.tooltip = None  # set below
        self.setFormat(shown_probabilities)

    def setFormat(self, shown_probabilities=()):
        self.shown_probabilities = shown_probabilities
        if self.class_values is None:
            # is continuous class
            self.fmt = f"{{value:{self.target_format[1:]}}}"
        else:
            self.fmt = " \N{RIGHTWARDS ARROW} ".join(
                [" : ".join(f"{{dist[{i}]:.2f}}" if i is not None else "-"
                            for i in shown_probabilities)]
                * bool(shown_probabilities)
                + ["{value!s}"])
        self.tooltip = ""
        if shown_probabilities:
            val = ', '.join(
                self.class_values[i] if i is not None else "-"
                for i in shown_probabilities if i is not None
            )
            self.tooltip = f"p({val})"

    def displayText(self, value, _locale):
        try:
            value, dist = value
        except ValueError:
            return ""
        else:
            return self.fmt.format(value=value, dist=dist)

    def helpEvent(self, event, view, option, index):
        if self.tooltip is not None:
            # ... but can be an empty string, so the current tooltip is removed
            QToolTip.showText(event.globalPos(), self.tooltip, view)
            return True
        else:
            return super().helpEvent(event, view, option, index)

    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        if self.class_values is None:
            option.displayAlignment = \
                (option.displayAlignment & Qt.AlignVertical_Mask) | \
                Qt.AlignRight

    def sizeHint(self, option, index):
        # reimplemented
        sh = super().sizeHint(option, index)
        if option.widget is not None:
            style = option.widget.style()
        else:
            style = QApplication.style()
        margin = style.pixelMetric(
            QStyle.PM_FocusFrameHMargin, option, option.widget) + 1
        metrics = option.fontMetrics
        height = sh.height() + metrics.leading() + 2 * margin
        return QSize(sh.width(), height)

    @staticmethod
    def distribution(index):
        value = index.data(Qt.DisplayRole)
        if isinstance(value, tuple) and len(value) == 2:
            _, dist = value
            return dist
        else:
            return None

    def paint(self, painter, option, index):
        dist = self.distribution(index)
        if dist is None or self.colors is None:
            super().paint(painter, option, index)
            return

        if option.widget is not None:
            style = option.widget.style()
        else:
            style = QApplication.style()

        self.initStyleOption(option, index)

        text = option.text
        metrics = option.fontMetrics

        margin = style.pixelMetric(
            QStyle.PM_FocusFrameHMargin, option, option.widget) + 1
        bottommargin = min(margin, 1)
        rect = option.rect.adjusted(margin, margin, -margin, -bottommargin)

        textrect = style.subElementRect(
            QStyle.SE_ItemViewItemText, option, option.widget)
        # Are the margins included in the subElementRect?? -> No!
        textrect = textrect.adjusted(margin, margin, -margin, -bottommargin)

        text = option.fontMetrics.elidedText(
            text, option.textElideMode, textrect.width())

        spacing = max(metrics.leading(), 1)

        distheight = rect.height() - metrics.height() - spacing
        distheight = numpy.clip(distheight, 2, metrics.height())

        painter.save()
        painter.setClipRect(option.rect)
        painter.setFont(option.font)
        painter.setRenderHint(QPainter.Antialiasing)

        style.drawPrimitive(
            QStyle.PE_PanelItemViewRow, option, painter, option.widget)
        style.drawPrimitive(
            QStyle.PE_PanelItemViewItem, option, painter, option.widget)

        if option.state & QStyle.State_Selected:
            color = option.palette.highlightedText().color()
        else:
            color = option.palette.text().color()
        painter.setPen(QPen(color))

        textrect = textrect.adjusted(0, 0, 0, -distheight - spacing)
        distrect = QRect(
            textrect.bottomLeft() + QPoint(0, spacing),
            QSize(rect.width(), distheight))
        painter.setPen(QPen(Qt.lightGray, 0.3))
        self.drawDistBar(painter, distrect, dist)
        painter.restore()
        if text:
            style.drawItemText(
                painter, textrect, option.displayAlignment, option.palette,
                option.state & QStyle.State_Enabled, text)

    def drawDistBar(self, painter, rect, distribution):
        painter.save()
        painter.translate(rect.topLeft())
        for i in self.shown_probabilities:
            if i is None:
                continue
            dvalue = distribution[i]
            if not dvalue > 0:  # This also skips nans
                continue
            painter.setBrush(self.colors[i])
            width = rect.width() * dvalue
            painter.drawRoundedRect(QRectF(0, 0, width, rect.height()), 1, 2)
            painter.translate(width, 0.0)
        painter.restore()


class SortProxyModel(QSortFilterProxyModel):
    """
    QSortFilter model used in both TableView and PredictionsView
    """
    list_sorted = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.__sortInd = None

    def setSortIndices(self, indices):
        if indices is not None:
            indices = numpy.array(indices, dtype=numpy.int)
            if indices.shape != (self.rowCount(),):
                raise ValueError("indices.shape != (self.rowCount(),)")
            indices.flags.writeable = False

        self.__sortInd = indices

        if self.__sortInd is not None:
            self.custom_sort(0)  # need valid order to call lessThan

    def lessThan(self, left, right):
        if self.__sortInd is None:
            return super().lessThan(left, right)

        assert not (left.parent().isValid() or right.parent().isValid()), \
            "Not a table model"

        rleft, rright = left.row(), right.row()
        try:
            ileft, iright = self.__sortInd[rleft], self.__sortInd[rright]
        except IndexError:
            return False
        else:
            return ileft < iright

    def isSorted(self):
        return self.__sortInd is not None

    def sort(self, n, order=Qt.AscendingOrder):
        """
        This sort is called only on click, in other cases we manually call
        custom_sort
        """
        # reset sort - otherwise when same parameters set by lessThan function
        # clicking on header would not trigger resort
        self.__sortInd = None
        self.custom_sort(n, order=order)
        self.list_sorted.emit()

    def custom_sort(self, n, order=Qt.AscendingOrder):
        """
        When sorting is dmanded because of sort change in the other view
        this sorting is called. It will not reset __sortInd to None.
        """
        if self.sortColumn() == n and self.sortOrder() == order:
            self.invalidate()
        else:
            super().sort(n, order)  # need some valid sort column


class PredictionsSortProxyModel(SortProxyModel):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.__probInd = None

    def setProbInd(self, indices):
        self.__probInd = indices
        self.invalidate()
        self.list_sorted.emit()

    def lessThan(self, left, right):
        if self.isSorted():
            return super().lessThan(left, right)

        role = self.sortRole()
        left_data = self.sourceModel().data(left, role)
        right_data = self.sourceModel().data(right, role)

        return self._key(left_data) < self._key(right_data)

    def _key(self, prediction):
        value, probs = prediction
        if probs is not None:
            if self.__probInd is not None:
                probs = probs[self.__probInd]
            probs = tuple(probs)

        return probs, value


class PredictionsModel(QAbstractTableModel):
    def __init__(self, table=None, headers=None, parent=None):
        super().__init__(parent)
        self._table = [[]] if table is None else table
        if headers is None:
            headers = [None] * len(self._table)
        self._header = headers
        self.__columnCount = max([len(row) for row in self._table] or [0])

    def rowCount(self, parent=QModelIndex()):
        return 0 if parent.isValid() else len(self._table)

    def columnCount(self, parent=QModelIndex()):
        return 0 if parent.isValid() else self.__columnCount

    def _value(self, index):
        return self._table[index.row()][index.column()]

    def data(self, index, role=Qt.DisplayRole):
        if role in (Qt.DisplayRole, Qt.EditRole):
            return self._value(index)
        return None

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if orientation == Qt.Vertical and role == Qt.DisplayRole:
            return str(section + 1)
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return (self._header[section] if section < len(self._header)
                    else str(section))
        return None


class TableView(QTableView):
    MaxSizeHintSamples = 1000

    def sizeHintForColumn(self, column):
        """
        Reimplemented from `QTableView.sizeHintForColumn`

        Note: This does not match the QTableView's implementation,
        in particular size hints from editor/index widgets are not taken
        into account.

        Parameters
        ----------
        column : int
        """
        # This is probably not needed in Qt5?
        if self.model() is None:
            return -1

        self.ensurePolished()
        model = self.model()
        vheader = self.verticalHeader()
        top = vheader.visualIndexAt(0)
        bottom = vheader.visualIndexAt(self.viewport().height())
        if bottom < 0:
            bottom = self.model().rowCount()

        options = self.viewOptions()
        options.widget = self

        width = 0
        sample_count = 0

        for row in range(top, bottom):
            if not vheader.isSectionHidden(vheader.logicalIndex(row)):
                index = model.index(row, column)
                delegate = self.itemDelegate(index)
                if not delegate:
                    continue
                size = delegate.sizeHint(options, index)
                width = max(size.width(), width)
                sample_count += 1

            if sample_count >= TableView.MaxSizeHintSamples:
                break

        return width + 1 if self.showGrid() else width


def tool_tip(value):
    value, dist = value
    if dist is not None:
        return "{!s} {!s}".format(value, dist)
    else:
        return str(value)


if __name__ == "__main__":  # pragma: no cover
    filename = "iris.tab"
    iris = Orange.data.Table(filename)
    idom = iris.domain
    dom = Domain(
        idom.attributes,
        DiscreteVariable(idom.class_var.name, idom.class_var.values[1::-1])
    )
    iris2 = iris[:100].transform(dom)

    def pred_error(data, *args, **kwargs):
        raise ValueError

    pred_error.domain = iris.domain
    pred_error.name = "To err is human"

    if iris.domain.has_discrete_class:
        predictors_ = [
            Orange.classification.SVMLearner(probability=True)(iris2),
            Orange.classification.LogisticRegressionLearner()(iris),
            pred_error
        ]
    elif iris.domain.has_continuous_class:
        predictors_ = [
            Orange.regression.RidgeRegressionLearner(alpha=1.0)(iris),
            Orange.regression.LinearRegressionLearner()(iris),
            pred_error
        ]
    else:
        predictors_ = [pred_error]

    WidgetPreview(OWPredictions).run(
        set_data=iris2,
        set_predictor=[(pred, i) for i, pred in enumerate(predictors_)])

```
--- 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