{"head_branch": "vizrank-2.0", "contributor": "janezd", "sha_fail": "1fef7bf674f2441de7fec54c3b6017d622722c48", "sha_success": "e8f13f71dd1bd19ae107057f850e8f1195478297", "language": "Python", "repo_owner": "biolab", "repo_name": "orange3", "workflow_name": "Documentation workflow", "workflow_filename": "doc.yml", "workflow_path": ".github/workflows/doc.yml", "workflow": "name: Documentation workflow\n\non:\n push:\n branches:\n - master\n pull_request:\n branches:\n - master\n\njobs:\n build:\n runs-on: ${{ matrix.os }}\n strategy:\n fail-fast: False\n matrix:\n python: [3.9]\n os: [ubuntu-22.04]\n\n steps:\n - uses: actions/checkout@v2\n - name: Setup Python\n uses: actions/setup-python@v1\n with:\n python-version: ${{ matrix.python }}\n\n - name: Install linux system dependencies\n run: sudo apt-get install -y libxkbcommon-x11-0\n\n - name: Install Tox\n run: pip install tox\n\n - name: Build documentation\n run: tox -e build_doc\n env:\n QT_QPA_PLATFORM: offscreen\n", "logs": "- \"keywords\": [\n- \"sieve\",\n- \"diagram\"\n- ]\n- },\n- {\n- \"text\": \"Mosaic Display\",\n- \"doc\": \"visual-programming/source/widgets/visualize/mosaicdisplay.md\",\n- \"icon\": \"../Orange/widgets/visualize/icons/MosaicDisplay.svg\",\n- \"background\": \"#FFB7B1\",\n- \"keywords\": [\n- \"mosaic\",\n- \"display\"\n- ]\n- },\n {\n \"text\": \"FreeViz\",\n \"doc\": \"visual-programming/source/widgets/visualize/freeviz.md\",\n@@ -492,26 +462,6 @@\n \"viz\"\n ]\n },\n- {\n- \"text\": \"Linear Projection\",\n- \"doc\": \"visual-programming/source/widgets/visualize/linearprojection.md\",\n- \"icon\": \"../Orange/widgets/visualize/icons/LinearProjection.svg\",\n- \"background\": \"#FFB7B1\",\n- \"keywords\": [\n- \"linear\",\n- \"projection\"\n- ]\n- },\n- {\n- \"text\": \"Radviz\",\n- \"doc\": \"visual-programming/source/widgets/visualize/radviz.md\",\n- \"icon\": \"../Orange/widgets/visualize/icons/Radviz.svg\",\n- \"background\": \"#FFB7B1\",\n- \"keywords\": [\n- \"radviz\",\n- \"viz\"\n- ]\n- },\n {\n \"text\": \"Heat Map\",\n \"doc\": \"visual-programming/source/widgets/visualize/heatmap.md\",\nbuild_doc: exit 1 (24.95 seconds) /home/runner/work/orange3/orange3> bash doc/build_doc.sh pid=2358\n.pkg: _exit> python /opt/hostedtoolcache/Python/3.9.18/x64/lib/python3.9/site-packages/pyproject_api/_backend.py True setuptools.build_meta\n build_doc: FAIL code 1 (140.40=setup[113.93]+cmd[1.12,0.41,24.95] seconds)\n evaluation failed :( (140.58 seconds)\n##[error]Process completed with exit code 1.\n", "diff": "diff --git a/Orange/widgets/visualize/utils/tests/test_vizrank.py b/Orange/widgets/visualize/utils/tests/test_vizrank.py\nnew file mode 100644\nindex 000000000..ae0fda3d3\n--- /dev/null\n+++ b/Orange/widgets/visualize/utils/tests/test_vizrank.py\n@@ -0,0 +1,304 @@\n+import unittest\n+from AnyQt.QtTest import QSignalSpy\n+from unittest.mock import patch, Mock\n+\n+from AnyQt.QtCore import Qt, pyqtSignal as Signal\n+from AnyQt.QtWidgets import QDialog\n+\n+from orangewidget.tests.base import GuiTest\n+from Orange.data import Table, Domain, ContinuousVariable\n+from Orange.widgets.visualize.utils.vizrank import (\n+ RunState, VizRankMixin,\n+ VizRankDialog, VizRankDialogAttrs, VizRankDialogAttrPair,\n+ VizRankDialogNAttrs\n+)\n+\n+\n+class MockDialog(VizRankDialog):\n+ class Task:\n+ interrupt = False\n+ set_partial_result = Mock()\n+\n+ def is_interruption_requested(self):\n+ return self.interrupt\n+\n+ task = Task()\n+\n+ def __init__(self, parent=None):\n+ super().__init__(parent)\n+\n+ def start(self, func, *args):\n+ func(*args, self.task)\n+\n+ def state_generator(self):\n+ return range(10)\n+\n+ def state_count(self):\n+ return 10\n+\n+ def compute_score(self, state):\n+ return 10 * (state % 2) + state // 2 if state != 3 else None\n+\n+ row_for_state = Mock()\n+\n+\n+class TestVizRankDialog(GuiTest):\n+\n+ @patch.object(VizRankDialog, \"start\")\n+ @patch.object(VizRankDialog, \"prepare_run\",\n+ new=lambda self: setattr(self.run_state,\n+ \"state\", RunState.Ready))\n+ def test_init_and_button(self, run_vizrank):\n+ dialog = VizRankDialog(None)\n+ self.assertEqual(dialog.run_state.state, RunState.Initialized)\n+ self.assertEqual(dialog.button.text(), dialog.button_labels[RunState.Initialized])\n+ dialog.button.click()\n+ run_vizrank.assert_called_once()\n+ self.assertEqual(dialog.run_state.state, RunState.Running)\n+ self.assertEqual(dialog.button.text(), dialog.button_labels[RunState.Running])\n+\n+ dialog.button.click()\n+ run_vizrank.assert_called_once()\n+ self.assertEqual(dialog.run_state.state, RunState.Paused)\n+ self.assertEqual(dialog.button.text(), dialog.button_labels[RunState.Paused])\n+\n+ dialog.button.click()\n+ self.assertEqual(run_vizrank.call_count, 2)\n+ self.assertEqual(dialog.run_state.state, RunState.Running)\n+ self.assertEqual(dialog.button.text(), dialog.button_labels[RunState.Running])\n+\n+ def test_running(self):\n+ dialog = MockDialog()\n+ dialog.start_computation()\n+ result = dialog.task.set_partial_result.call_args[0][0]\n+ self.assertEqual(result.scores, [0, 1, 2, 3, 4, 10, 12, 13, 14])\n+ self.assertEqual(result.completed_states, 10)\n+\n+ dialog.on_done(result)\n+ self.assertEqual(dialog.run_state.state, RunState.Done)\n+ self.assertEqual(dialog.button.text(), dialog.button_labels[RunState.Done])\n+ self.assertFalse(dialog.button.isEnabled())\n+\n+\n+ def test_running(self):\n+ dialog = MockDialog()\n+ dialog.task.interrupt = True\n+ dialog.start_computation()\n+ result = dialog.task.set_partial_result.call_args[0][0]\n+ self.assertEqual(result.scores, [0])\n+ self.assertEqual(result.completed_states, 1)\n+\n+\n+class TestVizRankMixin(GuiTest):\n+ def setUp(self):\n+ self.mock_dialog = Mock()\n+ self.mock_dialog.__name__ = \"foo\"\n+\n+ class Widget(QDialog, VizRankMixin(self.mock_dialog)):\n+ pass\n+\n+ self.widget = Widget()\n+\n+ def test_button(self):\n+ widget, dialog = self.widget, self.mock_dialog\n+\n+ widget.start_vizrank = Mock()\n+ widget.raise_vizrank = Mock()\n+\n+ button = widget.vizrank_button(\"Let's Vizrank\")\n+ self.assertEqual(button.text(), \"Let's Vizrank\")\n+ self.assertFalse(button.isEnabled())\n+\n+ widget.disable_vizrank(\"Too lazy to rank to-day.\")\n+ self.assertEqual(button.text(), \"Let's Vizrank\")\n+ self.assertEqual(button.toolTip(), \"Too lazy to rank to-day.\")\n+ self.assertFalse(button.isEnabled())\n+ dialog.assert_not_called()\n+\n+ widget.init_vizrank()\n+ dialog.assert_called_once()\n+ dialog.reset_mock()\n+ self.assertEqual(button.text(), \"Let's Vizrank\")\n+ self.assertEqual(button.toolTip(), \"\")\n+ self.assertTrue(button.isEnabled())\n+\n+ widget.disable_vizrank(\"Too lazy to rank to-day.\")\n+ self.assertEqual(button.text(), \"Let's Vizrank\")\n+ self.assertEqual(button.toolTip(), \"Too lazy to rank to-day.\")\n+ self.assertFalse(button.isEnabled())\n+ dialog.assert_not_called()\n+\n+ widget.init_vizrank()\n+ dialog.assert_called_once() # new data, new dialog!\n+ dialog.reset_mock()\n+\n+ button.click()\n+ widget.start_vizrank.assert_called_once()\n+ widget.raise_vizrank.assert_called_once()\n+\n+ def test_no_button(self):\n+ widget, dialog = self.widget, self.mock_dialog\n+\n+ widget.disable_vizrank(\"Too lazy to rank to-day.\")\n+ dialog.assert_not_called()\n+\n+ widget.init_vizrank()\n+ dialog.assert_called_once()\n+ dialog.reset_mock()\n+ widget.disable_vizrank(\"Too lazy to rank to-day.\")\n+\n+ widget.disable_vizrank(\"Too lazy to rank to-day.\")\n+ dialog.assert_not_called()\n+\n+ widget.init_vizrank()\n+ dialog.assert_called_once()\n+ dialog.reset_mock()\n+ widget.disable_vizrank(\"Too lazy to rank to-day.\")\n+\n+ def test_init_vizrank(self):\n+ widget, dialog = self.widget, self.mock_dialog\n+ a, b = Mock(), Mock()\n+ widget.init_vizrank(a, b)\n+ dialog.assert_called_with(widget, a, b)\n+\n+\n+class TestVizRankDialogWithData(GuiTest):\n+ def setUp(self):\n+ self.attrs = tuple(ContinuousVariable(n) for n in \"abcdef\")\n+ self.class_var = ContinuousVariable(\"y\")\n+ self.variables = (*self.attrs, self.class_var)\n+ self.metas = tuple(ContinuousVariable(n) for n in \"mn\")\n+ self.data = Table.from_list(\n+ Domain(self.attrs, self.class_var, self.metas),\n+ [[0] * 9])\n+\n+\n+class TestVizRankDialogAttrs(TestVizRankDialogWithData):\n+ def test_init(self):\n+ dialog = VizRankDialogAttrs(None, self.data)\n+ self.assertIs(dialog.data, self.data)\n+ self.assertEqual(dialog.attrs, self.variables)\n+ self.assertIsNone(dialog.attr_color)\n+\n+ dialog = VizRankDialogAttrs(None, self.data, self.attrs[1:])\n+ self.assertIs(dialog.data, self.data)\n+ self.assertEqual(dialog.attrs, self.attrs[1:])\n+ self.assertIsNone(dialog.attr_color)\n+\n+ dialog = VizRankDialogAttrs(None, self.data, self.attrs[1:], self.attrs[3])\n+ self.assertIs(dialog.data, self.data)\n+ self.assertEqual(dialog.attrs, self.attrs[1:])\n+ self.assertIs(dialog.attr_color, self.attrs[3])\n+\n+ def test_attr_order(self):\n+ dialog = VizRankDialogAttrs(None, self.data)\n+ self.assertEqual(dialog.attr_order, self.variables)\n+\n+ class OrderedAttr(VizRankDialogAttrs):\n+ call_count = 0\n+\n+ def score_attributes(self):\n+ self.call_count += 1\n+ return self.attrs[::-1]\n+\n+ dialog = OrderedAttr(None, self.data)\n+ self.assertEqual(dialog.attr_order, self.variables[::-1])\n+ self.assertEqual(dialog.attr_order, self.variables[::-1])\n+ self.assertEqual(dialog.call_count, 1)\n+\n+ def test_row_for_state(self):\n+ dialog = VizRankDialogAttrs(None, self.data)\n+ item = dialog.row_for_state(0, [3, 1])[0]\n+ self.assertEqual(item.data(Qt.DisplayRole), \"d, b\")\n+ self.assertEqual(item.data(dialog._AttrRole), [self.attrs[3], self.attrs[1]])\n+\n+ dialog.sort_names_in_row = True\n+ item = dialog.row_for_state(0, [3, 1])[0]\n+ self.assertEqual(item.data(Qt.DisplayRole), \"b, d\")\n+ self.assertEqual(item.data(dialog._AttrRole), [self.attrs[3], self.attrs[1]])\n+\n+ def test_autoselect(self):\n+ widget = VizRankMixin()\n+ dialog = VizRankDialogAttrs(widget, self.data)\n+ for state in ([0, 1], [0, 3], [1, 3], [3, 1]):\n+ dialog.rank_model.appendRow(dialog.row_for_state(0, state))\n+\n+ widget.vizrankAutoSelect.emit([self.attrs[1], self.attrs[3]])\n+ selection = dialog.rank_table.selectedIndexes()\n+ self.assertEqual(len(selection), 1)\n+ self.assertEqual(selection[0].row(), 2)\n+\n+ widget.vizrankAutoSelect.emit([self.attrs[3], self.attrs[1]])\n+ selection = dialog.rank_table.selectedIndexes()\n+ self.assertEqual(len(selection), 1)\n+ self.assertEqual(selection[0].row(), 3)\n+\n+ widget.vizrankAutoSelect.emit([self.attrs[3], self.attrs[0]])\n+ selection = dialog.rank_table.selectedIndexes()\n+ self.assertEqual(len(selection), 0)\n+\n+\n+class TestVizRankDialogAttrPair(TestVizRankDialogWithData):\n+ def test_count_and_generator(self):\n+ dialog = VizRankDialogAttrPair(None, self.data, self.attrs[:5])\n+ self.assertEqual(dialog.state_count(), 5 * 4 / 2)\n+ self.assertEqual(\n+ list(dialog.state_generator()),\n+ [(0, 1), (0, 2), (1, 2), (0, 3), (1, 3), (2, 3),\n+ (0, 4), (1, 4), (2, 4), (3, 4)])\n+\n+\n+class TestVizRankDialogNAttrs(TestVizRankDialogWithData):\n+ def test_spin_interaction(self):\n+ dialog = VizRankDialogNAttrs(None,\n+ self.data, self.attrs[:5], None, 4)\n+ spy = QSignalSpy(dialog.runStateChanged)\n+\n+ with patch.object(\n+ VizRankDialog, \"pause_computation\",\n+ side_effect=lambda: dialog.set_run_state(RunState.Paused)):\n+ with patch.object(\n+ VizRankDialog, \"start_computation\",\n+ side_effect=lambda: dialog.set_run_state(RunState.Running)):\n+ spin = dialog.n_attrs_spin\n+ self.assertEqual(spin.value(), 4)\n+ self.assertEqual(spin.maximum(), 5)\n+\n+ dialog.start_computation()\n+ self.assertEqual(dialog.run_state.state, RunState.Running)\n+ self.assertEqual(spy[-1][1][\"n_attrs\"], 4)\n+\n+ spin.setValue(3)\n+ # Ranking must be paused\n+ self.assertEqual(dialog.run_state.state, RunState.Paused)\n+ # Label should be changed to \"restart with ...\"\n+ self.assertNotEqual(dialog.button.text(),\n+ dialog.button_labels[RunState.Paused])\n+\n+ spin.setValue(4)\n+ self.assertEqual(dialog.run_state.state, RunState.Paused)\n+ # Label should be reset to \"Continue\"\n+ self.assertEqual(dialog.button.text(),\n+ dialog.button_labels[RunState.Paused])\n+\n+ # Remove the side-effect so that we see that start_computation\n+ # resets the state to Initialized before calling super\n+ with patch.object(VizRankDialog, \"start_computation\"):\n+ dialog.start_computation()\n+ self.assertEqual(spy[-1][1][\"n_attrs\"], 4)\n+ # Here, the state must not be reset to Initialized\n+ self.assertEqual(dialog.run_state.state, RunState.Paused)\n+ # But now manually set it to appropriate state\n+ dialog.set_run_state(RunState.Running)\n+\n+ spin.setValue(3)\n+ self.assertEqual(dialog.run_state.state, RunState.Paused)\n+ self.assertNotEqual(dialog.button.text(), dialog.button_labels[RunState.Paused])\n+\n+ dialog.start_computation()\n+ self.assertEqual(dialog.run_state.state, RunState.Initialized)\n+ self.assertEqual(spy[-1][1][\"n_attrs\"], 3)\n+\n+\n+if __name__ == \"__main__\":\n+ unittest.main()\n\\ No newline at end of file\ndiff --git a/Orange/widgets/visualize/utils/vizrank.py b/Orange/widgets/visualize/utils/vizrank.py\nnew file mode 100644\nindex 000000000..bbdaff0af\n--- /dev/null\n+++ b/Orange/widgets/visualize/utils/vizrank.py\n@@ -0,0 +1,743 @@\n+from bisect import bisect_left\n+from queue import Queue, Empty\n+from types import SimpleNamespace as namespace\n+from typing import Optional, Iterable, List, Callable, Iterator, Any, Type\n+from threading import Timer\n+\n+from AnyQt.QtCore import Qt, QSize, QSortFilterProxyModel, pyqtSignal as Signal\n+from AnyQt.QtGui import (\n+ QStandardItemModel, QStandardItem, QShowEvent, QCloseEvent, QHideEvent)\n+from AnyQt.QtWidgets import (\n+ QTableView, QDialog, QVBoxLayout, QLineEdit, QPushButton)\n+\n+from Orange.widgets import gui\n+from Orange.widgets.gui import HorizontalGridDelegate, TableBarItem\n+from Orange.widgets.utils.concurrent import ConcurrentMixin, TaskState\n+from Orange.widgets.utils.progressbar import ProgressBarMixin\n+\n+\n+class Result(namespace):\n+ queue = None # type: Queue[QueuedScore, ...]\n+ scores = None # type: Optional[List[float, ...]]\n+\n+\n+class QueuedScore(namespace):\n+ position = None # type: int\n+ score = None # type: float\n+ state = None # type: Iterable\n+\n+\n+class RunState(namespace):\n+ Invalid = 0 # Used only as default, changed to Initialized when instantiated\n+ Initialized = 1 # Has data; prepare_run must be called before starting computation\n+ Ready = 2 # Has data, iterator is initialized, but never used\n+ Running = 3 # Scoring thread is running\n+ Paused = 4 # Scoring thread is inactive, but can continue (without prepare_run)\n+ Done = 5 # Scoring is done\n+\n+ state: int = Invalid\n+ iterator: Iterable = None\n+ completed: int = 0\n+\n+ def can_run(self):\n+ return self.state in (self.Ready, self.Paused)\n+\n+\n+class VizRankDialog(QDialog, ProgressBarMixin, ConcurrentMixin):\n+ \"\"\"\n+ Base class for VizRank dialogs, providing a GUI with a table and a button,\n+ and the skeleton for managing the evaluation of visualizations.\n+\n+ A new instance of this class is used for new data or any change made in\n+ the widget (e.g. color attribute in the scatter plot).\n+\n+ The attribute run_state (and the related signal runStateChanged) can be\n+ used for tracking the work flow of the widget. run_state.state can be\n+\n+ - RunState.Initialized (after __init__): the widget has the data, but\n+ the state generator is not constructed, total statecount is not known\n+ yet. The dialog may reenter this state after, for instance, changing\n+ the number of attributes per combination in radviz.\n+ - RunState.Ready (after prepare_run): the iterator is ready, state count\n+ is known: the ranking can commence.\n+ - RunState.Running (after start_computation): ranking is in progress.\n+ This state is entered by start_computation. If start_computation is\n+ called when the state is Initialized, start computation will call\n+ prepare_run.\n+ - RunState.Paused (after pause_computation): ranking is paused. This may\n+ continue (with start_computation) or be reset when parameters of VizRank\n+ are changed (by calling `set_run_state(RunState.Initialized)` and then\n+ start_computation, which will first call prepare_run to go to Ready)\n+ - RunState.Done: ranking is done. The only allowed next state is\n+ Initialized (with the procedure described in the previous point).\n+\n+ State should be changed through set_run_state, which also changes the button\n+ label and disables the button when Done.\n+\n+ Derived classes must provide methods\n+\n+ - `__init__(parent, *args, **kwargs)`: stores the data to run vizrank,\n+ - `state_generator()`: generates combinations (e.g. of attributes),\n+ - `compute_score(state)`: computes the score for the combination,\n+ - `row_for_state(state)`: returns a list of items inserted into the\n+ table for the given state.\n+\n+ and, probably,\n+\n+ - emit `selectionChanged` when the user changes the selection in the table,\n+\n+ and, optionally,\n+\n+ - `state_count`: return the number of combinations (used for progress bar)\n+ - `bar_length`: return the length of the bar corresponding to the score,\n+ - `auto_select`: selects the row corresponding to the given data.\n+\n+ Derived classes are also responsible for connecting to\n+ rank_table.selectionModel().selectionChanged and emitting something useful\n+ via selectionChanged\n+\n+ The constructor shouldn't do anything but store the necessary data (as is)\n+ because instances of this object are created on any new data. The actual\n+ work can only start in `prepare_run`. `prepare_run` usually won't be\n+ overriden, so the first computation in derived classes will usually happen\n+ in `compute_score` or, in classes derived from`VizRankAttributes`, in\n+ `score_attributes`.\n+\n+ Args:\n+ parent (Orange.widget.OWWidget): widget to which the dialog belongs\n+\n+ Attributes:\n+ captionTitle (str): the caption for the dialog. This can be a class\n+ attribute. `captionTitle` is used by the `ProgressBarMixin`.\n+ show_bars (True): if True (default), table with scores contains bars\n+ of length -score. For a different length, override `bar_lenght`.\n+ To hide bars (e.g. because scores can't be normalized) set this to\n+ `False`.\n+\n+ Signal:\n+ selectionChanged(object): emitted when selection in the table is\n+ changed. The data type depends on the derived class (e.g. a list\n+ of attributes)\n+ runStateChanged(int, dict): emitted when the run state changes\n+ (e.g. start, pause...). Derived classes can fill the dictionary\n+ with additional data, e.g. the state of the user interface\n+ \"\"\"\n+ captionTitle = \"Score Plots\"\n+ show_bars = True\n+\n+ selectionChanged = Signal(object)\n+ runStateChanged = Signal(int, dict)\n+\n+ button_labels = {RunState.Initialized: \"Start\",\n+ RunState.Ready: \"Start\",\n+ RunState.Running: \"Pause\",\n+ RunState.Paused: \"Continue\",\n+ RunState.Done: \"Finished\",\n+ RunState.Invalid: \"Start\"}\n+\n+ def __init__(self, parent):\n+ QDialog.__init__(self, parent, windowTitle=self.captionTitle)\n+ ConcurrentMixin.__init__(self)\n+ ProgressBarMixin.__init__(self)\n+ self.setLayout(QVBoxLayout())\n+\n+ self.scores = []\n+ self.add_to_model = Queue()\n+ self.run_state = RunState()\n+ self.total_states = 1\n+\n+ self.filter = QLineEdit()\n+ self.filter.setPlaceholderText(\"Filter ...\")\n+ self.layout().addWidget(self.filter)\n+\n+ self.rank_model = QStandardItemModel(self)\n+ self.model_proxy = QSortFilterProxyModel(\n+ self, filterCaseSensitivity=Qt.CaseInsensitive)\n+ self.model_proxy.setSourceModel(self.rank_model)\n+ self.filter.textChanged.connect(self.model_proxy.setFilterFixedString)\n+\n+ self.rank_table = view = QTableView(\n+ selectionBehavior=QTableView.SelectRows,\n+ selectionMode=QTableView.SingleSelection,\n+ showGrid=False,\n+ editTriggers=gui.TableView.NoEditTriggers)\n+ view.setItemDelegate(TableBarItem() if self.show_bars\n+ else HorizontalGridDelegate())\n+ view.setModel(self.model_proxy)\n+ view.horizontalHeader().setStretchLastSection(True)\n+ view.horizontalHeader().hide()\n+ self.layout().addWidget(view)\n+\n+ self.button = gui.button(self, self, \"Start\", default=True)\n+\n+ @self.button.pressed.connect\n+ def on_button_pressed():\n+ if self.run_state.state == RunState.Running:\n+ self.pause_computation()\n+ else:\n+ self.start_computation()\n+\n+ self.set_run_state(RunState.Initialized)\n+\n+ def prepare_run(self) -> None:\n+ \"\"\"\n+ Called by start_computation before running for the first time or with\n+ new parameters within the vizrank gui, e.g. a different number of\n+ attributes in combinations.\n+\n+ Derived classes may override this method to add other preparation steps,\n+ but shouldn't need to call it.\n+ \"\"\"\n+ self.progressBarInit()\n+ self.scores = []\n+ self._update_model() # empty queue\n+ self.rank_model.clear()\n+ self.run_state.iterator = self.state_generator()\n+ self.total_states = self.state_count() or 1\n+ self.set_run_state(RunState.Ready)\n+\n+ def start_computation(self) -> None:\n+ if self.run_state.state == RunState.Initialized:\n+ self.prepare_run()\n+ if not self.run_state.can_run():\n+ return\n+ self.set_run_state(RunState.Running)\n+ self.start(\n+ self.run_vizrank,\n+ self.compute_score, self.scores,\n+ self.run_state.iterator, self.run_state.completed)\n+\n+ def pause_computation(self) -> None:\n+ if not self.run_state.state == RunState.Running:\n+ return\n+ self.set_run_state(RunState.Paused)\n+ self.cancel()\n+ self._update_model()\n+\n+ @staticmethod\n+ def run_vizrank(compute_score: Callable, scores: List,\n+ state_iterator: Iterator, completed: int, task: TaskState):\n+ res = Result(queue=Queue(), scores=None, completed_states=completed)\n+ scores = scores.copy()\n+ can_set_partial_result = True\n+\n+ def do_work(st: Any):\n+ score = compute_score(st)\n+ if score is not None:\n+ pos = bisect_left(scores, score)\n+ res.queue.put_nowait(QueuedScore(position=pos, score=score,\n+ state=st))\n+ scores.insert(pos, score)\n+ res.scores = scores.copy()\n+ res.completed_states += 1\n+\n+ def reset_flag():\n+ nonlocal can_set_partial_result\n+ can_set_partial_result = True\n+\n+ for state in state_iterator:\n+ do_work(state)\n+ # Prevent simple scores from invoking 'task.set_partial_result')\n+ # too frequently and making the widget unresponsive\n+ if can_set_partial_result:\n+ task.set_partial_result(res)\n+ can_set_partial_result = False\n+ Timer(0.01, reset_flag).start()\n+ if task.is_interruption_requested():\n+ return res\n+ task.set_partial_result(res)\n+ return res\n+\n+ def on_partial_result(self, result: Result) -> None:\n+ try:\n+ while True:\n+ queued = result.queue.get_nowait()\n+ self.add_to_model.put_nowait(queued)\n+ except Empty:\n+ pass\n+ self.scores = result.scores\n+ self._update_model()\n+ self.run_state.completed = result.completed_states\n+ self.progressBarSet(self._progress)\n+\n+ @property\n+ def _progress(self) -> int:\n+ return int(round(self.run_state.completed * 100 / self.total_states))\n+\n+ def on_done(self, result: Result) -> None:\n+ self.progressBarFinished()\n+ self.set_run_state(RunState.Done)\n+ self._update_model()\n+\n+ def set_run_state(self, state: Any) -> None:\n+ if state != self.run_state.state:\n+ self.run_state.state = state\n+ self.emit_run_state_changed()\n+ if state == RunState.Paused:\n+ self.setWindowTitle(\n+ f\"{self.captionTitle} (paused at {self._progress}%)\")\n+ self.set_button_state()\n+\n+ def emit_run_state_changed(self):\n+ self.runStateChanged.emit(self.run_state.state, {})\n+\n+ def set_button_state(self,\n+ label: Optional[str] = None,\n+ enabled: Optional[bool]=None) -> None:\n+ state = self.run_state.state\n+ self.button.setText(\n+ label if label is not None\n+ else self.button_labels[state])\n+ self.button.setEnabled(\n+ enabled if enabled is not None\n+ else state not in [RunState.Done, RunState.Invalid])\n+\n+ def _update_model(self) -> None:\n+ try:\n+ while True:\n+ queued = self.add_to_model.get_nowait()\n+ row_items = self.row_for_state(queued.score, queued.state)\n+ bar_length = self.bar_length(queued.score)\n+ if bar_length is not None:\n+ row_items[0].setData(bar_length,\n+ gui.TableBarItem.BarRole)\n+ self.rank_model.insertRow(queued.position, row_items)\n+ except Empty:\n+ pass\n+\n+ def showEvent(self, event: QShowEvent) -> None:\n+ self.parent()._restore_vizrank_geometry()\n+ super().showEvent(event)\n+\n+ def closeEvent(self, event: QCloseEvent) -> None:\n+ self.pause_computation()\n+ self.parent()._save_vizrank_geometry()\n+ super().closeEvent(event)\n+\n+ def state_generator(self) -> Iterable:\n+ \"\"\"\n+ Generate all possible states (e.g. attribute combinations) for the\n+ given data. The content of the generated states is specific to the\n+ visualization.\n+ \"\"\"\n+ raise NotImplementedError\n+\n+ def compute_score(self, state: Any) -> Optional[float]:\n+ \"\"\"\n+ Abstract method for computing the score for the given state. Smaller\n+ scores are better.\n+\n+ Args:\n+ state: the state, e.g. the combination of attributes as generated\n+ by :obj:`state_count`.\n+ \"\"\"\n+ raise NotImplementedError\n+\n+ def row_for_state(self, score: float, state: Any) -> List[QStandardItem]:\n+ \"\"\"\n+ Return a list of items that are inserted into the table.\n+\n+ Args:\n+ score: score, computed by :obj:`compute_score`\n+ state: the state, e.g. combination of attributes\n+ \"\"\"\n+ raise NotImplementedError\n+\n+ def auto_select(self, arg: Any) -> None:\n+ \"\"\"\n+ Select the row corresponding to the give data.\n+ \"\"\"\n+ pass\n+\n+ def state_count(self) -> int:\n+ \"\"\"\n+ Return the total number of states, needed for the progress bar.\n+ \"\"\"\n+ return 1\n+\n+ def bar_length(self, score: float) -> float:\n+ \"\"\"\n+ Return the bar length (between 0 and 1) corresponding to the score.\n+ Return `None` if the score cannot be normalized.\n+ \"\"\"\n+ return max(0., -score)\n+\n+\n+def VizRankMixin(vizrank_class) -> Type[type]:\n+ \"\"\"\n+ A mixin that serves as an interface between the vizrank dialog and the widget.\n+\n+ Widget should avoid directly access the vizrank dialog.\n+\n+ This mixin takes care of constructing the vizrank dialog, raising it,\n+ and for closing and shutting the vizrank down when necessary. Data for\n+ vizrank is passed to the vizrank through the mixin, and the mixin forwards\n+ the signals from vizrank dialog (e.g. when the user selects rows in vizrank)\n+ to the widget.\n+\n+ The mixin is parametrized: it must be given the VizRank class to open,\n+ as in\n+\n+ ```\n+ class OWMosaicDisplay(OWWidget, VizRankMixin(MosaicVizRank)):\n+ ```\n+\n+ There should therefore be no need to subclass this class.\n+\n+ Method `vizrank_button` returns a button to be placed into the widget.\n+\n+ Signals:\n+ - `vizrankSelectionChanged` is connected to VizRank's selectionChanged.\n+ E.g. MosaicVizRank.selectionChanged is forwarded to selectionChanged,\n+ and contains the data sent by the former.\n+ - `virankRunStateChanged` is connected to VizRank's runStateChanged.\n+ This can be used to retrieve the settings from the dialog at appropriate\n+ times.\n+ - If the widget emits a signal `vizrankAutoSelect` when\n+ the user manually changes the variables shown in the plot (e.g. x or y\n+ attribute in the scatter plot), the vizrank will also select this\n+ combination in the list, if found.\n+\"\"\"\n+ class __VizRankMixin:\n+ __button: Optional[QPushButton] = None\n+ __vizrank: Optional[VizRankDialog] = None\n+ __vizrank_geometry: Optional[bytes] = None\n+\n+ vizrankSelectionChanged = Signal(object)\n+ vizrankRunStateChanged = Signal(int, dict)\n+ vizrankAutoSelect = Signal(object)\n+\n+ @property\n+ def vizrank_dialog(self) -> Optional[VizRankDialog]:\n+ \"\"\"\n+ The vizrank dialog. This should be used only in tests.\n+ \"\"\"\n+ return self.__vizrank\n+\n+ def vizrank_button(self, button_label: Optional[str] = None) -> QPushButton:\n+ \"\"\"\n+ A button that opens/starts the vizrank.\n+\n+ The label is optional because this function is used for\n+ constructing the button as well as for retrieving it later.\n+ \"\"\"\n+ if self.__button is None:\n+ self.__button = QPushButton()\n+ self.__button.pressed.connect(self.start_vizrank)\n+ self.__button.pressed.connect(self.raise_vizrank)\n+ # It's implausible that vizrank_button will be called after\n+ # init_vizrank, we could just disable the button. But let's\n+ # play it safe.\n+ self.__button.setDisabled(self.__vizrank is None)\n+ if button_label is not None:\n+ self.__button.setText(button_label)\n+ return self.__button\n+\n+ def init_vizrank(self, *args, **kwargs) -> None:\n+ \"\"\"\n+ Construct the vizrank dialog\n+\n+ Any data is given to the constructor. This also enables the button\n+ if it exists.\n+ \"\"\"\n+ self.shutdown_vizrank()\n+ self.__vizrank = vizrank_class(self, *args, **kwargs)\n+ self.__vizrank.selectionChanged.connect(self.vizrankSelectionChanged)\n+ self.__vizrank.runStateChanged.connect(self.vizrankRunStateChanged)\n+ self.vizrankAutoSelect.connect(self.__vizrank.auto_select)\n+ # There may be Vizrank without a button ... perhaps.\n+ if self.__button is not None:\n+ self.__button.setEnabled(True)\n+ self.__button.setToolTip(\"\")\n+\n+ def disable_vizrank(self, reason: str = \"\") -> None:\n+ \"\"\"\n+ Shut down the vizrank thread, closes it, disables the button.\n+\n+ The method should be called when the widget has no data or cannot\n+ run vizrank on it. The optional `reason` is set as tool tip.\n+ \"\"\"\n+ self.shutdown_vizrank()\n+ if self.__button is not None:\n+ self.__button.setEnabled(False)\n+ self.__button.setToolTip(reason)\n+\n+ def start_vizrank(self) -> None:\n+ \"\"\"\n+ Start the ranking.\n+\n+ There should be no reason to call this directly,\n+ unless the widget has no vizrank button.\n+ \"\"\"\n+ self.__vizrank.start_computation()\n+\n+ def raise_vizrank(self) -> None:\n+ \"\"\"\n+ Start the ranking.\n+\n+ There should be no reason to call this directly,\n+ unless the widget has no vizrank button.\n+ \"\"\"\n+ if self.__vizrank is None:\n+ return\n+ self.__vizrank.show()\n+ self.__vizrank.activateWindow()\n+ self.__vizrank.raise_()\n+\n+ def shutdown_vizrank(self) -> None:\n+ \"\"\"\n+ Start the ranking.\n+\n+ There should be no reason to call this directly:\n+ the method is called\n+ - from init_vizrank (the widget received new data),\n+ - from disable_vizrank (the widget lost data, or data is unsuitable),\n+ - when the widget is deleted.\n+ \"\"\"\n+ if self.__vizrank is None:\n+ return\n+ self.__vizrank.cancel()\n+ self.__vizrank.close()\n+ self.__vizrank.deleteLater()\n+ self.__vizrank = None\n+\n+ # The following methods ensure that the vizrank dialog is\n+ # closed/hidden/destroyed together with its parent widget.\n+ def closeEvent(self, event: QCloseEvent) -> None:\n+ if self.__vizrank:\n+ self.__vizrank.close()\n+ super().closeEvent(event)\n+\n+ def hideEvent(self, event: QHideEvent) -> None:\n+ if self.__vizrank:\n+ self.__vizrank.hide()\n+ super().hideEvent(event)\n+\n+ def onDeleteWidget(self) -> None:\n+ self.shutdown_vizrank()\n+ super().onDeleteWidget()\n+\n+ def _save_vizrank_geometry(self) -> None:\n+ assert self.__vizrank\n+ self.__vizrank_geometry = self.__vizrank.saveGeometry()\n+\n+ def _restore_vizrank_geometry(self) -> None:\n+ assert self.__vizrank\n+ if self.__vizrank_geometry is not None:\n+ self.__vizrank.restoreGeometry(self.__vizrank_geometry)\n+\n+ # Give the returned class a proper name, like MosaicVizRankMixin\n+ return type(f\"{vizrank_class.__name__}Mixin\", (__VizRankMixin, ), {})\n+\n+\n+class VizRankDialogAttrs(VizRankDialog):\n+ \"\"\"\n+ Base class for VizRank classes that work over combinations of attributes.\n+\n+ Constructor accepts\n+ - data (Table),\n+ - attributes (list[Variable]; if omitted, data.domain.variables is used),\n+ - attr_color (Optional[Variable]): the \"color\" attribute, if applicable.\n+\n+ The class assumes that `state` is a sequence of indices into a list of\n+ attributes. On this basis, it provides\n+\n+ - `row_for_state`, that constructs a list containing a single QStandardItem\n+ with names of attributes and with `_AttrRole` data set to a list of\n+ attributes for the given state.\n+ - `on_selection_changed` that emits a `selectionChanged` signal with the\n+ above list.\n+\n+ Derived classes must still provide\n+\n+ - `state_generator()`: generates combinations of attribute indices\n+ - `compute_score(state)`: computes the score for the combination\n+\n+ Derived classes will usually provide\n+ - `score_attribute` that will returned a list of attributes, such as found\n+ in self.attrs, but sorted by importance according to some heuristic.\n+\n+ Attributes:\n+ - data (Table): data used in ranking\n+ - attrs (list[Variable]): applicable variables\n+ - attr_color (Variable or None): the target attribute\n+\n+ Class attributes:\n+ - sort_names_in_row (bool): if set to True (default is False),\n+ variables in the view will be sorted alphabetically.\n+ \"\"\"\n+ _AttrRole = next(gui.OrangeUserRole)\n+ sort_names_in_row = False\n+\n+ # Ideally, the only argument would be `data`, with attributes used for\n+ # ranking and class_var would be the \"color\". This would however require\n+ # that widgets prepare such data when initializing vizrank even though\n+ # vizrank wouldn't necessarily be called at all. We will be able to afford\n+ # that after we migrate Table to pandas.\n+ def __init__(self, parent,\n+ data: \"Orange.data.Table\",\n+ attributes: Optional[List[\"Orange.data.Variable\"]] = None,\n+ attr_color: Optional[\"Orange.data.Variable\"] = None):\n+ super().__init__(parent)\n+ self.data = data or None\n+ self.attrs = attributes or (\n+ self.data and self.data.domain.variables)\n+ self.attr_color = attr_color\n+ self._attr_order = None\n+\n+ self.rank_table.selectionModel().selectionChanged.connect(\n+ self.on_selection_changed)\n+\n+ @property\n+ def attr_order(self) -> List[\"Orange.data.Variable\"]:\n+ \"\"\"\n+ Attributes, sorted according to some heuristic.\n+\n+ The property is computed by score_attributes when neceessary, and\n+ cached.\n+ \"\"\"\n+ if self._attr_order is None:\n+ self._attr_order = self.score_attributes()\n+ return self._attr_order\n+\n+ def score_attributes(self) -> None:\n+ \"\"\"\n+ Return a list of attributes ordered according by some heuristic.\n+\n+ Default implementation returns the original list `self.attrs`.\n+ \"\"\"\n+ return self.attrs\n+\n+ def on_selection_changed(self, selected, deselected) -> None:\n+ \"\"\"\n+ Emit the currently selected combination of variables.\n+ \"\"\"\n+ selection = selected.indexes()\n+ if not selection:\n+ return\n+ attrs = selected.indexes()[0].data(self._AttrRole)\n+ self.selectionChanged.emit(attrs)\n+\n+ def row_for_state(self, score: float, state: List[int]\n+ ) -> List[QStandardItem]:\n+ \"\"\"\n+ Return the QStandardItem for the given combination of attributes.\n+ \"\"\"\n+ attrs = [self.attr_order[s] for s in state]\n+ if self.sort_names_in_row:\n+ attrs.sort(key=lambda attr: attr.name.lower())\n+ attr_names = (a.name for a in attrs)\n+ item = QStandardItem(', '.join(attr_names))\n+ item.setData(attrs, self._AttrRole)\n+ return [item]\n+\n+ def auto_select(self, attrs: List[\"Orange.data.Variable\"]) -> None:\n+ \"\"\"\n+ Find the given combination of variables and select it (if it exists)\n+ \"\"\"\n+ model = self.rank_model\n+ self.rank_table.selectionModel().clear()\n+ for row in range(model.rowCount()):\n+ index = model.index(row, 0)\n+ row_attrs = model.data(index, self._AttrRole)\n+ if all(x is y for x, y in zip(row_attrs, attrs)):\n+ self.rank_table.selectRow(row)\n+ self.rank_table.scrollTo(index)\n+ return\n+\n+\n+class VizRankDialogAttrPair(VizRankDialogAttrs):\n+ \"\"\"\n+ Base class for VizRanks with combinations of two variables.\n+\n+ Provides state_generator and state_count; derived classes must provide\n+ compute_score and, possibly, score_attributes.\n+ \"\"\"\n+ def __init__(self, parent, data, attributes=None, attr_color=None):\n+ super().__init__(parent, data, attributes, attr_color)\n+ self.resize(320, 512)\n+\n+ def sizeHint(self) -> QSize:\n+ return QSize(320, 512)\n+\n+ def state_count(self) -> int:\n+ n_attrs = len(self.attrs)\n+ return n_attrs * (n_attrs - 1) // 2\n+\n+ def state_generator(self) -> Iterable:\n+ return ((j, i) for i in range(len(self.attr_order)) for j in range(i))\n+\n+\n+class VizRankDialogNAttrs(VizRankDialogAttrs):\n+ \"\"\"\n+ Base class for VizRanks with a spin for selecting the number of attributes.\n+\n+ Constructor requires data, attributes, attr_color and, also, the initial\n+ number of attributes in the spin box.\n+\n+ - Ranking is stopped if the user interacts with the spin.\n+ - The button label is changed to \"Restart with {...} variables\" if the\n+ number selected in the spin doesn't match the number of varialbes in the\n+ paused ranking, and reset back to \"Continue\" when it matches.\n+ - start_computation is overriden to lower the state to Initialized before\n+ calling super, if the number of selected in the spin doesn't match the\n+ previous run.\n+ - The dictionary passed by the signal runStateChanged contains n_attrs\n+ with the number of attributes used in the current/last ranking.\n+ - When closing the dialog, the spin is reset to the number of attributes\n+ used in the last run.\n+ \"\"\"\n+ attrsSelected = Signal([])\n+\n+ def __init__(self, parent,\n+ data: \"Orange.data.Table\",\n+ attributes: List[\"Orange.data.Variable\"],\n+ color: \"Orange.data.Variable\",\n+ n_attrs: int,\n+ *, spin_label: str = \"Number of variables: \"):\n+ # Add the spin box for a number of attributes to take into account.\n+ self.n_attrs = n_attrs\n+ super().__init__(parent, data, attributes, color)\n+ self._attr_order = None\n+\n+ box = gui.hBox(self)\n+ self.n_attrs_spin = gui.spin(\n+ box, self, None, 3, 8, label=spin_label,\n+ controlWidth=50, alignment=Qt.AlignRight,\n+ callback=self.on_n_attrs_changed)\n+\n+ n_cont = self.max_attrs()\n+ self.n_attrs_spin.setValue(min(self.n_attrs, n_cont))\n+ self.n_attrs_spin.setMaximum(n_cont)\n+ self.n_attrs_spin.parent().setDisabled(not n_cont)\n+\n+ def max_attrs(self) -> int:\n+ return sum(v is not self.attr_color for v in self.attrs)\n+\n+ def start_computation(self) -> None:\n+ if self.n_attrs != self.n_attrs_spin.value():\n+ self.n_attrs = self.n_attrs_spin.value()\n+ self.set_run_state(RunState.Initialized)\n+ self.n_attrs_spin.lineEdit().deselect()\n+ self.rank_table.setFocus(Qt.FocusReason.OtherFocusReason)\n+ super().start_computation()\n+\n+ def on_n_attrs_changed(self) -> None:\n+ if self.run_state.state == RunState.Running:\n+ self.pause_computation()\n+\n+ new_attrs = self.n_attrs_spin.value()\n+ if new_attrs == self.n_attrs:\n+ self.set_button_state()\n+ else:\n+ self.set_button_state(label=f\"Restart with {new_attrs} variables\",\n+ enabled=True)\n+\n+ def emit_run_state_changed(self) -> None:\n+ self.runStateChanged.emit(self.run_state.state,\n+ dict(n_attrs=self.n_attrs))\n+\n+ def closeEvent(self, event) -> None:\n+ self.n_attrs_spin.setValue(self.n_attrs)\n+ super().closeEvent(event)\n+\n"} |