experimenteditor.py 43.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# vim: set fileencoding=utf-8 :
###############################################################################
#                                                                             #
# Copyright (c) 2019 Idiap Research Institute, http://www.idiap.ch/           #
# Contact: beat.support@idiap.ch                                              #
#                                                                             #
# This file is part of the beat.editor module of the BEAT platform.           #
#                                                                             #
# Commercial License Usage                                                    #
# Licensees holding valid commercial BEAT licenses may use this file in       #
# accordance with the terms contained in a written agreement between you      #
# and Idiap. For further information contact tto@idiap.ch                     #
#                                                                             #
# Alternatively, this file may be used under the terms of the GNU Affero      #
# Public License version 3 as published by the Free Software and appearing    #
# in the file LICENSE.AGPL included in the packaging of this file.            #
# The BEAT platform is distributed in the hope that it will be useful, but    #
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY  #
# or FITNESS FOR A PARTICULAR PURPOSE.                                        #
#                                                                             #
# You should have received a copy of the GNU Affero Public License along      #
# with the BEAT platform. If not, see http://www.gnu.org/licenses/.           #
#                                                                             #
###############################################################################

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
import re
import copy
import simplejson as json
import numpy as np

from PyQt5.QtCore import pyqtProperty
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtCore import QStringListModel
from PyQt5.QtCore import QSortFilterProxyModel

from PyQt5.QtGui import QIcon
from PyQt5.QtGui import QStandardItem
from PyQt5.QtGui import QStandardItemModel

from PyQt5.QtWidgets import QCheckBox
from PyQt5.QtWidgets import QComboBox
from PyQt5.QtWidgets import QDialogButtonBox
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QFormLayout
from PyQt5.QtWidgets import QGroupBox
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QStyle
from PyQt5.QtWidgets import QTabWidget
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QWidget

from beat.core.experiment import PROCESSOR_PREFIX
from beat.core.experiment import EVALUATOR_PREFIX

from ..backend.asset import Asset
60
from ..backend.asset import AssetType
61 62
from ..backend.assetmodel import AssetModel

63
from ..decorators import frozen
Samuel GAIST's avatar
Samuel GAIST committed
64

65 66 67 68 69 70 71
from ..utils import is_Qt_equal_or_higher

from .scrollwidget import ScrollWidget
from .scrollwidget import EditorListWidget

from .spinboxes import NumpySpinBox

72 73 74
from .editor import AbstractAssetEditor


75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
PARAMETER_TYPE_KEY = "parameter_type"
DEFAULT_VALUE_KEY = "default_value"
EDITED_KEY = "edited"


# ------------------------------------------------------------------------------
# Helper methods


def typed_user_property(widget):
    """Returns the user property value properly typed

    :param widget QWidget: widget from which the property value must be retrieved
    """

    user_property = widget.metaObject().userProperty()
    parameter_type = widget.property(PARAMETER_TYPE_KEY)
    return np.array([user_property.read(widget)]).astype(parameter_type)[0]


def write_user_property(widget, value):
    """Write the widget user property value

    :param widget QWidget: widget to which the property value must be written
    :param value: value to write to the user property
    """

    user_property = widget.metaObject().userProperty()
    user_property.write(widget, value)


# ------------------------------------------------------------------------------
# Helper classes


class FieldPresenceFilterProxyModel(QSortFilterProxyModel):
    """Filter proxy model showing asset filtered based on their content"""

    def __init__(self, field, must_have, value=None, parent=None):
        """
        :param field str: field to search
        :param must_have bool: whether the field must be in the declaration
        """

        super().__init__(parent=parent)

        self.setFieldFilter(field, must_have, value)

    def setFieldFilter(self, field, must_have, value=None):
        self.field = field
        self.must_have = must_have
        self.value = value
        self.prog = re.compile(value) if value is not None else None

    def filterAcceptsRow(self, source_row, source_parent):
        """Filter assets based on whether the field configured must or must not
        be found in the declaration.
        """

        asset_model = self.sourceModel()
        index = asset_model.index(source_row, 0, source_parent)
        path = asset_model.json_path(index.data())

        with open(path, "rt") as json_file:
            try:
                json_data = json.load(json_file)
            except json.JSONDecodeError:
                return False
            else:
                has_field = self.field in json_data
                if has_field and self.value is not None:
                    match = self.prog.match(json_data[self.field])
                    if self.must_have:
                        return match is not None
                    else:
                        return match is None
                return has_field == self.must_have


class EnvironmentModel(QStandardItemModel):
    """Model wrapping the processing environment available"""

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

        self.context = None

    @pyqtSlot()
    def refreshContent(self):
        self.clear()
        if self.context is not None:
            with open(self.context.meta["environments"], "rt") as file_:
                json_data = json.load(file_)
                for docker_name, data in json_data.items():
                    if "databases" not in data:
                        visual_name = "{name} ({version})".format(**data)
                        self.appendRow(
                            [
                                QStandardItem(visual_name),
                                QStandardItem(data["name"]),
                                QStandardItem(data["version"]),
                            ]
                        )

    def setContext(self, context):
        self.context = context
        self.refreshContent()

    def environment(self, index):
        """Returns the (name, version) tuple representing an environment

        :param index QModelIndex: index from the model
        """

        if is_Qt_equal_or_higher("5.11"):
            name = index.siblingAtColumn(1)
            version = index.siblingAtColumn(2)
        else:
            name = index.sibling(index.row(), 1)
            version = index.sibling(index.row(), 2)

        name = self.data(name)
        version = self.data(version)
        return {"name": name, "version": version}


class ContainerWidget(ScrollWidget):
    """Container widget to show block editors"""

    def dump(self):
        return {widget.block_name: widget.dump() for widget in self.widget_list}


class AbstractBaseEditor(QWidget):

    dataChanged = pyqtSignal()
    prefixPathChanged = pyqtSignal(str)

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

    @pyqtSlot(str)
    def setPrefixPath(self, prefix_path):
        if self.prefix_path == prefix_path:
            return

        self.prefix_path = prefix_path
        self.prefixPathChanged.emit(self.prefix_path)

    def load(self, json_object):
        raise NotImplementedError

    def dump(self):
        raise NotImplementedError


class DatasetModel(QStringListModel):
    def __init__(self, parent=None):
        super().__init__(parent)

    def update(self):
        asset_model = AssetModel()
        asset_model.asset_type = AssetType.DATABASE
        asset_model.prefix_path = self.prefix_path
        asset_model.setLatestOnlyEnabled(False)

        available_databases = asset_model.stringList()
        available_set_names = []

        for database in available_databases:
            db = AssetType.DATABASE.klass(self.prefix_path, database)
            if not db.valid:
                continue
            for protocol in db.protocol_names:
                for set_name in db.set_names(protocol):
                    available_set_names.append(
                        "{}/{}/{}".format(database, protocol, set_name)
                    )
        self.setStringList(available_set_names)

    def setPrefixPath(self, prefix_path):
        self.prefix_path = prefix_path
        self.update()


# ------------------------------------------------------------------------------
# Editors


class IOMapperDialog(QDialog):
    """Dialog that allows to remap inputs and outputs of an algorithm to fit on
    a block of the toolchain
    """

    def __init__(self, algorithm, block_data, parent=None):
        super().__init__(parent)
        alg_inputs = []
        alg_outputs = []
        for group in algorithm["groups"]:
            alg_inputs += group["inputs"].keys()
            outputs = group.get("outputs")
            if outputs:
                alg_outputs += outputs.keys()

        self.inputs_layout = QFormLayout()
        for alg_input, input_ in block_data["inputs"].items():
            combobox = QComboBox()
            combobox.addItems(alg_inputs)
            combobox.setCurrentText(alg_input)
            self.inputs_layout.addRow(input_, combobox)

        inputs_groupbox = QGroupBox(self.tr("Inputs"))
        inputs_groupbox.setLayout(self.inputs_layout)
        groupboxes_layout = QHBoxLayout()
        groupboxes_layout.addWidget(inputs_groupbox)

        self.outputs_layout = QFormLayout()

        outputs = block_data.get("outputs")
        if outputs:
            for alg_output, output in block_data["outputs"].items():
                combobox = QComboBox()
                combobox.addItems(alg_outputs)
                combobox.setCurrentText(alg_output)
                self.outputs_layout.addRow(output, combobox)

            outputs_groupbox = QGroupBox(self.tr("Outputs"))
            outputs_groupbox.setLayout(self.outputs_layout)
            groupboxes_layout.addWidget(outputs_groupbox)

        buttonbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)

        layout = QVBoxLayout(self)
        layout.addLayout(groupboxes_layout)
        layout.addWidget(buttonbox)

        buttonbox.accepted.connect(self.accept)
        buttonbox.rejected.connect(self.reject)

    def ioMapping(self):
        data = {"inputs": {}}

        for i in range(self.inputs_layout.count() - 1):
            label = self.inputs_layout.itemAt(i, QFormLayout.LabelRole).widget()
            combobox = self.inputs_layout.itemAt(i, QFormLayout.FieldRole).widget()
            data["inputs"][combobox.currentText()] = label.text()

        for i in range(self.outputs_layout.count() - 1):
            if "outputs" not in data:
                data["outputs"] = {}
            label = self.outputs_layout.itemAt(i, QFormLayout.LabelRole).widget()
            combobox = self.outputs_layout.itemAt(i, QFormLayout.FieldRole).widget()
            data["outputs"][combobox.currentText()] = label.text()

        return data

    @staticmethod
    def getIOMapping(prefix, block_data):
        algorithm = Asset(prefix, AssetType.ALGORITHM, block_data["algorithm"])

        dialog = IOMapperDialog(algorithm.declaration, block_data)
        status = dialog.exec_()
        if status == QDialog.Rejected:
            return False, None

        return True, dialog.ioMapping()


class DatasetEditor(AbstractBaseEditor):
    """Widget allowing the setup of the various datasets used"""

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

        self.json_object = {}
        self.block_name = block_name
        self.dataset_combobox = QComboBox()
        self.reset_button = QPushButton(
            self.style().standardIcon(QStyle.SP_DialogResetButton), ""
        )
        self.reset_button.setToolTip(self.tr("Reset values"))

        row_layout = QHBoxLayout()
        row_layout.addWidget(self.dataset_combobox, 1)
        row_layout.addWidget(self.reset_button)

        layout = QFormLayout(self)
        layout.addRow(self.block_name, row_layout)

        self.dataset_combobox.currentTextChanged.connect(self.dataChanged)
        self.reset_button.clicked.connect(self.reset)

    def reset(self):
        self.dataset_combobox.setCurrentText(
            "{}/{}/{}".format(
                self.json_object["database"],
                self.json_object["protocol"],
                self.json_object["set"],
            )
        )

    def setDatasetModel(self, dataset_model):
        self.dataset_combobox.setModel(dataset_model)

    def currentSet(self):
        _, _, _, set_ = self.dataset_combobox.currentText().split("/")
        return set_

    def load(self, json_object):
        self.json_object = copy.deepcopy(json_object)
        self.reset()

    def dump(self):
        database, db_version, protocol, set_ = self.dataset_combobox.currentText().split(
            "/"
        )
        return {
            "database": "{}/{}".format(database, db_version),
            "protocol": protocol,
            "set": set_,
        }


class AlgorithmParametersEditor(AbstractBaseEditor):

    dataChanged = pyqtSignal()
    parameterCountChanged = pyqtSignal(int)

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

        self.algorithm_name = None
        self.json_data = {}
        self.edited = {}
        self.dump_edited_only = True
        self.form_layout = QFormLayout(self)

    def setDumpEditOnlyEnabled(self, enabled):
        """Sets whether the dump will contain all or only the modified fields"""

        self.dump_edited_only = enabled

    def isEmpty(self):
        """Returns whether this editor is empty"""

        return self.form_layout.rowCount() == 0

    def parameterCount(self):
        """Returns the number of parameters to edit"""

        return self.form_layout.rowCount()

    def editorForRow(self, row):
        """Returns the editor widget matching the give row"""

        if row < 0 or row >= self.form_layout.rowCount():
            return None

        return self.form_layout.itemAt(row, QFormLayout.FieldRole).widget()

    def labelForRow(self, row):
        """Returns the label widget matching the give row"""

        if row < 0 or row >= self.form_layout.rowCount():
            return None

        return self.form_layout.itemAt(row, QFormLayout.LabelRole).widget().text()

    def editorForLabel(self, label):
        """Returns the editor matching the given label"""

        for i in range(self.form_layout.rowCount()):
            if self.labelForRow(i) == label:
                return self.editorForRow(i)

    def setup(self, algorithm_name):
        """Setup the editor for the give algorithm"""

        if self.algorithm_name == algorithm_name:
            return

        self.algorithm_name = algorithm_name
        old_count = self.parameterCount()

        while self.form_layout.rowCount():
            self.form_layout.removeRow(0)

        algorithm = AssetType.ALGORITHM.klass(self.prefix_path, self.algorithm_name)
        parameters = algorithm.parameters
        if parameters is not None:
            for name, info in parameters.items():
                type_ = np.dtype(info["type"])
                default = info.get("default")

                if np.issubdtype(type_, np.number):
                    if "choice" in info:
                        editor = QComboBox()
                        signal = editor.currentTextChanged
                        editor.addItems([str(value) for value in info["choice"]])
                        editor.setCurrentText(str(default))
                    else:
                        editor = NumpySpinBox(type_.type)
                        signal = editor.valueChanged
                        if "range" in info:
                            range_ = info["range"]
                            editor.setRange(range_[0], range_[1])
                        editor.setValue(default)
                elif np.issubdtype(type_, np.dtype(str).type):
                    if "choice" in info:
                        editor = QComboBox()
                        signal = editor.currentTextChanged
                        editor.addItems(info["choice"])
                        editor.setCurrentText(str(default))
                    else:
                        editor = QLineEdit()
                        signal = editor.textChanged
                        editor.setText(default)

                elif np.issubdtype(type_, np.dtype(bool).type):
                    editor = QCheckBox()
                    signal = editor.toggled
                    editor.setChecked(bool(default))
                else:
                    raise RuntimeError("Unsupported type: {}".format(type_))

                signal.connect(self.dataChanged)
                signal.connect(lambda: self.sender().setProperty(EDITED_KEY, True))
                editor.setProperty(PARAMETER_TYPE_KEY, type_)
                editor.setProperty(DEFAULT_VALUE_KEY, default)
                editor.setProperty(EDITED_KEY, False)

                self.form_layout.addRow(name, editor)

        new_count = self.parameterCount()
        if new_count != old_count:
            self.parameterCountChanged.emit(new_count)

    def reset(self):
        """Reset the state of the editor all default values"""

        for i in range(self.form_layout.rowCount()):
            widget = self.form_layout.itemAt(i, QFormLayout.FieldRole).widget()
            widget.setProperty(EDITED_KEY, False)
            default = widget.property(DEFAULT_VALUE_KEY)
            write_user_property(widget, default)

    def load(self, json_data):
        """Setup the content of the editor with the given JSON data"""

        self.json_data = copy.deepcopy(json_data)

        for name, value in json_data.items():
            for i in range(self.form_layout.rowCount()):
                label = self.form_layout.itemAt(i, QFormLayout.LabelRole).widget()
                if label.text() == name:
                    widget = self.form_layout.itemAt(i, QFormLayout.FieldRole).widget()
                    write_user_property(widget, value)
                    break

    def dump(self):
        """Dump only the parameters that have changed unless dump edited only
        is set.
        """

        data = {}
        for i in range(0, self.form_layout.rowCount()):
            label = self.form_layout.itemAt(i, QFormLayout.LabelRole).widget()
            name = label.text()

            widget = self.form_layout.itemAt(i, QFormLayout.FieldRole).widget()
            value = typed_user_property(widget)
            if self.dump_edited_only:
                default_value = widget.property(DEFAULT_VALUE_KEY)
                if widget.property(EDITED_KEY) and value != default_value:
                    data[name] = value
            else:
                data[name] = value
        return data


class ExecutionPropertiesEditor(AbstractBaseEditor):
    """Widget showing the execution parameters related to an execution unit"""

    algorithmChanged = pyqtSignal(str)

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

        self.json_object = {}
        self.io_mapping = {}
        self.environment_changed = False
        self.queue_changed = False
        self._queue_enabled = True
        self.parameter_item = None
        self.algorithm_combobox = QComboBox()
        self.algorithm_combobox.setObjectName("algorithms")
        self.environment_combobox = QComboBox()
        self.environment_combobox.setObjectName("environments")
        self.queue_combobox = QComboBox()
        self.parameters_editor = AlgorithmParametersEditor(prefix_path)

        self.remap_button = QPushButton(QIcon(":/resources/remap.png"), "")
        self.remap_button.setObjectName("remap")
        self.remap_button.setToolTip(self.tr("Remap input and outputs"))
        reset_button = QPushButton(
            self.style().standardIcon(QStyle.SP_DialogResetButton), ""
        )
        reset_button.setToolTip(self.tr("Reset values"))
        self.parameters_button = QPushButton(self.tr("Parameters"))
        self.parameters_button.setCheckable(True)

        button_layout = QHBoxLayout()
        button_layout.addWidget(self.parameters_button)
        button_layout.addStretch(1)
        button_layout.addWidget(self.remap_button)
        button_layout.addWidget(reset_button)

        groupbox = QGroupBox()
        groupbox.setVisible(False)
        self.parameters_layout = QFormLayout(groupbox)
        self.parameters_layout.addRow(self.tr("Environment"), self.environment_combobox)
        self.parameters_layout.addRow(self.tr("Queue"), self.queue_combobox)
        self.parameters_layout.addRow(self.tr("Parameters"), self.parameters_editor)

        layout = QVBoxLayout(self)
        layout.addWidget(self.algorithm_combobox)
        layout.addLayout(button_layout)
        layout.addWidget(groupbox)

        self.algorithm_combobox.currentIndexChanged.connect(self.dataChanged)
        self.algorithm_combobox.currentTextChanged.connect(self.algorithmChanged)
        self.algorithm_combobox.currentTextChanged.connect(
            lambda algorithm_name: self.parameters_editor.setup(algorithm_name)
        )
        self.environment_combobox.currentIndexChanged.connect(self.dataChanged)
        self.environment_combobox.currentIndexChanged.connect(
            lambda *args: setattr(self, "environment_changed", True)
        )
        self.queue_combobox.currentIndexChanged.connect(self.dataChanged)
        self.queue_combobox.currentIndexChanged.connect(
            lambda *args: setattr(self, "queue_changed", True)
        )
        self.parameters_editor.dataChanged.connect(self.dataChanged)
        self.parameters_editor.parameterCountChanged.connect(self.__updateUi)
        self.remap_button.clicked.connect(self.__remapIO)
        reset_button.clicked.connect(lambda: self.load(self.json_object))
        self.parameters_button.toggled.connect(self.__updateUi)
        self.parameters_button.toggled.connect(groupbox.setVisible)

        self.__updateUi()

    @pyqtSlot()
    def __remapIO(self):

        status, mapping = IOMapperDialog.getIOMapping(self.prefix_path, self.dump())

        if status and self.io_mapping != mapping:
            self.io_mapping = mapping
            self.dataChanged.emit()

    @pyqtSlot()
    def __updateUi(self):
        icon = (
            QStyle.SP_TitleBarShadeButton
            if self.parameters_button.isChecked()
            else QStyle.SP_TitleBarUnshadeButton
        )
        self.parameters_button.setIcon(self.style().standardIcon(icon))

        self.parameters_editor.setVisible(not self.parameters_editor.isEmpty())
        self.parameters_layout.labelForField(self.parameters_editor).setVisible(
            not self.parameters_editor.isEmpty()
        )

        self.queue_combobox.setVisible(self._queue_enabled)
        self.parameters_layout.labelForField(self.queue_combobox).setVisible(
            self._queue_enabled
        )

    def algorithm(self):
        return self.algorithm_combobox.currentText()

    algorithm = pyqtProperty(str, fget=algorithm, notify=algorithmChanged)

    def setAlgorithmModel(self, model):
        self.algorithm_combobox.setModel(model)

    def setEnvironmentModel(self, model):
        self.environment_combobox.setModel(model)

    def environmentModel(self):
        return self.environment_combobox.model()

    def setQueueModel(self, model):
        self.queue_combobox.setModel(model)

    def setQueueEnabled(self, enabled):
        self._queue_enabled = enabled
        self.__updateUi()

    def load(self, json_object):
        self.json_object = copy.deepcopy(json_object)
        self.io_mapping = {"inputs": json_object["inputs"]}

        outputs = json_object.get("outputs")
        if outputs:
            self.io_mapping["outputs"] = outputs

        algorithm_name = json_object["algorithm"]
        environment = json_object.get("environment")
        parameters = json_object.get("parameters")

        self.algorithm_combobox.setCurrentText(algorithm_name)
        if self.algorithm_combobox.currentText() != algorithm_name:
            raise RuntimeError(
                "Algorithm {} not found in prefix".format(algorithm_name)
            )
        self.parameters_editor.setup(algorithm_name)

        if environment:
            env_text = "{} ({})".format(environment["name"], environment["version"])
            self.environment_combobox.setCurrentText(env_text)
        else:
            self.environment_combobox.setCurrentIndex(0)

        if parameters:
            self.parameters_editor.load(parameters)

        self.environment_changed = False
        self.queue_changed = False
        self.parameters_changed = False

    def dump(self):
        data = copy.deepcopy(self.json_object)
        data["algorithm"] = self.algorithm_combobox.currentText()

        if self.environment_changed:
            model = self.environment_combobox.model()
            index = model.index(self.environment_combobox.currentIndex(), 0)
            data["environment"] = model.environment(index)

        if self._queue_enabled and self.queue_changed:
            data["queue"] = self.queue_combobox.currentText()

        parameters = self.parameters_editor.dump()
        if parameters:
            data["parameters"] = parameters

        data.update(self.io_mapping)
        return data


class AbstractBlockEditor(AbstractBaseEditor):
    """Common elements for editing a block"""

    algorithmChanged = pyqtSignal(str)

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

        self.block_name = block_name

    def setAlgorithmModel(self, model):
        """Set algorithm model"""

        raise NotImplementedError

    def setEnvironmentModel(self, model):
        """Set environment model"""

        raise NotImplementedError

    def setQueueModel(self, model):
        """Setup queue model"""

        raise NotImplementedError


class BlockEditor(AbstractBlockEditor):
    def __init__(self, block_name, prefix_path, parent=None):
        super().__init__(block_name, prefix_path, parent)

        self.proxy_model = FieldPresenceFilterProxyModel("results", False)
        self.properties_editor = ExecutionPropertiesEditor(prefix_path)
        self.properties_editor.setAlgorithmModel(self.proxy_model)

        layout = QVBoxLayout(self)
        layout.addWidget(QLabel(self.block_name))
        layout.addWidget(self.properties_editor)

        self.properties_editor.algorithmChanged.connect(self.algorithmChanged)
        self.properties_editor.dataChanged.connect(self.dataChanged)

        self.prefixPathChanged.connect(self.proxy_model.invalidate)

    def setAlgorithmModel(self, model):
        self.proxy_model.setSourceModel(model)

    def selectedAlgorithm(self):
        return self.properties_editor.algorithm

    def setEnvironmentModel(self, model):
        self.properties_editor.setEnvironmentModel(model)

    def environmentModel(self):
        return self.properties_editor.environmentModel()

    def setQueueModel(self, model):
        self.properties_editor.setQueueModel(model)

    def load(self, json_object):
        self.properties_editor.load(json_object)

    def dump(self):
        return self.properties_editor.dump()


class AnalyzerBlockEditor(BlockEditor):
    def __init__(self, block_name, prefix_path, parent=None):
        super().__init__(block_name, prefix_path, parent)

        self.proxy_model.setFieldFilter("results", True)


class LoopBlockEditor(AbstractBlockEditor):
    def __init__(self, block_name, prefix_path, parent=None):
        super().__init__(block_name, prefix_path, parent)

        self.processor_model = FieldPresenceFilterProxyModel(
            "type", True, ".*loop_processor"
        )
        self.evaluator_model = FieldPresenceFilterProxyModel(
            "type", True, ".*loop_evaluator"
        )

        self.processor_properties_editor = ExecutionPropertiesEditor(prefix_path)
        self.processor_properties_editor.setAlgorithmModel(self.processor_model)
        self.evaluator_properties_editor = ExecutionPropertiesEditor(prefix_path)
        self.evaluator_properties_editor.setAlgorithmModel(self.evaluator_model)
        self.evaluator_properties_editor.setQueueEnabled(False)

        processor_groupbox = QGroupBox(self.tr("Processor"))
        evaluator_groupbox = QGroupBox(self.tr("Evaluator"))

        processor_layout = QVBoxLayout(processor_groupbox)
        processor_layout.addWidget(self.processor_properties_editor)

        evaluator_layout = QVBoxLayout(evaluator_groupbox)
        evaluator_layout.addWidget(self.evaluator_properties_editor)

        layout = QVBoxLayout(self)
        layout.addWidget(QLabel(self.block_name))
        layout.addWidget(processor_groupbox)
        layout.addWidget(evaluator_groupbox)

        self.processor_properties_editor.algorithmChanged.connect(self.algorithmChanged)
        self.processor_properties_editor.dataChanged.connect(self.dataChanged)
        self.evaluator_properties_editor.algorithmChanged.connect(self.algorithmChanged)
        self.evaluator_properties_editor.dataChanged.connect(self.dataChanged)

        self.prefixPathChanged.connect(self.processor_model.invalidate)
        self.prefixPathChanged.connect(self.evaluator_model.invalidate)

    def setAlgorithmModel(self, model):
        self.processor_model.setSourceModel(model)
        self.evaluator_model.setSourceModel(model)

    def selectedAlgorithms(self):
        return {
            self.processor_properties_editor.algorithm,
            self.evaluator_properties_editor.algorithm,
        }

    def setEnvironmentModel(self, model):
        for editor in [
            self.processor_properties_editor,
            self.evaluator_properties_editor,
        ]:
            editor.setEnvironmentModel(model)

    def environmentModel(self):
        return self.processor_properties_editor.environmentModel()

    def setQueueModel(self, model):
        self.processor_properties_editor.setQueueModel(model)

    def load(self, json_object):
        processor_data = {
            key[len(PROCESSOR_PREFIX) :]: value
            for key, value in json_object.items()
            if key.startswith(PROCESSOR_PREFIX)
        }
        evaluator_data = {
            key[len(EVALUATOR_PREFIX) :]: value
            for key, value in json_object.items()
            if key.startswith(EVALUATOR_PREFIX)
        }

        self.processor_properties_editor.load(processor_data)
        self.evaluator_properties_editor.load(evaluator_data)

    def dump(self):
        data = {}
        processor_data = self.processor_properties_editor.dump()
        data.update(
            {f"{PROCESSOR_PREFIX}{key}": value for key, value in processor_data.items()}
        )
        evaluator_data = self.evaluator_properties_editor.dump()
        data.update(
            {f"{EVALUATOR_PREFIX}{key}": value for key, value in evaluator_data.items()}
        )
        return data


class EditorGroupBox(QGroupBox):
    """Container widget for the GlobalParametersEditor"""

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

        self.editor = editor

        name_label = QLabel(name)
        reset_button = QPushButton(
            self.style().standardIcon(QStyle.SP_DialogResetButton), ""
        )
        reset_button.setToolTip(self.tr("Reset values"))

        title_layout = QHBoxLayout()
        title_layout.addWidget(name_label)
        title_layout.addWidget(reset_button)
        title_layout.addStretch(1)

        layout = QVBoxLayout(self)
        layout.addLayout(title_layout)
        layout.addWidget(editor)

        reset_button.clicked.connect(editor.reset)


class GlobalParametersEditor(AbstractBaseEditor):
    """Widget showing all the parameters that can be set"""

    dataChanged = pyqtSignal()

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

        self.json_object = {}
        self.environment_changed = False
        self.queue_changed = False

        self.environment_combobox = QComboBox()
        self.queue_combobox = QComboBox()
        self.parameters_editor_listwidget = EditorListWidget()

        form_layout = QFormLayout()
        form_layout.addRow(self.tr("Environment"), self.environment_combobox)
        form_layout.addRow(self.tr("Queue"), self.queue_combobox)

        layout = QVBoxLayout(self)
        layout.addLayout(form_layout)
        layout.addWidget(self.parameters_editor_listwidget)
        layout.addStretch(1)

        self.environment_combobox.currentIndexChanged.connect(self.dataChanged)
        self.environment_combobox.currentIndexChanged.connect(
            lambda *args: setattr(self, "environment_changed", True)
        )
        self.queue_combobox.currentIndexChanged.connect(self.dataChanged)
        self.queue_combobox.currentIndexChanged.connect(
            lambda *args: setattr(self, "queue_changed", True)
        )
        self.parameters_editor_listwidget.dataChanged.connect(self.dataChanged)

    def setEnvironmentModel(self, model):
        self.environment_combobox.setModel(model)

    def setQueueModel(self, model):
        self.queue_combobox.setModel(model)

    def clear(self):
        self.environment_combobox.setCurrentIndex(0)
        self.parameters_editor_listwidget.clear()

    def setup(self, algorithms):
        current_algorithm_widgets = {
            widget.editor.algorithm_name: widget
            for widget in self.parameters_editor_listwidget.widget_list
        }
        current_algorithms = set(current_algorithm_widgets.keys())

        to_add = algorithms.difference(current_algorithms)
        to_remove = current_algorithms.difference(algorithms)

        for algorithm_name in to_remove:
            self.parameters_editor_listwidget.removeWidget(
                current_algorithm_widgets[algorithm_name]
            )
            self.json_object.pop(algorithm_name, None)

        for algorithm_name in to_add:
            algorithm = AssetType.ALGORITHM.klass(self.prefix_path, algorithm_name)
            if algorithm.valid and algorithm.parameters:
                editor = AlgorithmParametersEditor(self.prefix_path)
                editor.setDumpEditOnlyEnabled(False)
                editor.setup(algorithm_name)
                editor.dataChanged.connect(self.dataChanged)

                global_parameter_editor = EditorGroupBox(algorithm_name, editor)

                self.parameters_editor_listwidget.addWidget(global_parameter_editor)

    def load(self, json_object):
        self.json_object = copy.deepcopy(json_object)

        environment = self.json_object["environment"]
        env_text = "{} ({})".format(environment["name"], environment["version"])
        self.environment_combobox.setCurrentText(env_text)

        parameters = [
            item
            for item in self.json_object.items()
            if item[0] not in ["queue", "environment"]
        ]

        for data in parameters:
            name, data = data
            editor = None
            for widget in self.parameters_editor_listwidget.widget_list:
                if widget.editor.algorithm_name == name:
                    editor = widget.editor
                    break
            if editor is None:
                raise RuntimeError("Mismatch between globals data and block data")
            editor.load(data)

        self.environment_changed = False
        self.queue_changed = False
        self.parameters_changed = False

    def dump(self):
        data = copy.deepcopy(self.json_object)

        if self.environment_changed:
            model = self.environment_combobox.model()
            index = model.index(self.environment_combobox.currentIndex(), 0)
            data["environment"] = model.environment(index)
        if self.queue_changed:
            data["queue"] = self.queue_combobox.currentText()

        for widget in self.parameters_editor_listwidget.widget_list:
            editor = widget.editor
            data[editor.algorithm_name] = editor.dump()

        return data


Samuel GAIST's avatar
Samuel GAIST committed
1034
@frozen
1035 1036
class ExperimentEditor(AbstractAssetEditor):
    def __init__(self, parent=None):
1037
        super().__init__(AssetType.EXPERIMENT, parent)
Samuel GAIST's avatar
Samuel GAIST committed
1038
        self.setObjectName(self.__class__.__name__)
1039 1040
        self.set_title(self.tr("Experiment"))

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
        self.processing_env_model = EnvironmentModel()
        self.queue_model = QStringListModel()
        self.queue_model.setStringList(["Local"])

        self.dataset_model = DatasetModel()

        self.algorithm_model = AssetModel()
        self.algorithm_model.setLatestOnlyEnabled(False)
        self.algorithm_model.asset_type = AssetType.ALGORITHM

        self.datasets_widget = ContainerWidget()
        self.blocks_widget = ContainerWidget()
        self.loops_widget = ContainerWidget()
        self.analyzers_widget = ContainerWidget()
        self.globalparameters_widget = GlobalParametersEditor(self.prefixPath())
        self.globalparameters_widget.setEnvironmentModel(self.processing_env_model)
        self.globalparameters_widget.setQueueModel(self.queue_model)

        self.tabwidget = QTabWidget()
        self.tabwidget.addTab(self.datasets_widget, self.tr("Datasets"))
        self.tabwidget.addTab(self.blocks_widget, self.tr("Blocks"))
        self.loops_widget_index = self.tabwidget.addTab(
            self.loops_widget, self.tr("Loops")
        )
        self.tabwidget.addTab(self.analyzers_widget, self.tr("Analyzers"))
        self.tabwidget.addTab(
            self.globalparameters_widget, self.tr("Global parameters")
        )

        self.layout().addWidget(self.tabwidget)

        self.contextChanged.connect(self.__update)

        for widget in [
            self.datasets_widget,
            self.blocks_widget,
            self.loops_widget,
            self.analyzers_widget,
            self.globalparameters_widget,
        ]:
            widget.dataChanged.connect(self.dataChanged)

    @pyqtSlot()
    def __update(self):
        for object_ in [
            self.algorithm_model,
            self.dataset_model,
            self.datasets_widget,
            self.blocks_widget,
            self.loops_widget,
            self.analyzers_widget,
            self.globalparameters_widget,
        ]:
            object_.setPrefixPath(self.prefix_path)

        self.processing_env_model.setContext(self.context)

    @pyqtSlot()
    def __onAlgorithmChanged(self):
        algorithms = {
            editor.properties_editor.algorithm
            for editor in self.blocks_widget.widget_list
            + self.analyzers_widget.widget_list
        }

        for editor in self.loops_widget.widget_list:
            algorithms.add(editor.processor_properties_editor.algorithm)
            algorithms.add(editor.evaluator_properties_editor.algorithm)
        self.globalparameters_widget.setup(algorithms)

1111 1112
    def _load_json(self, json_object):
        """Load the json object passed as parameter"""
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160

        for widget in [
            self.datasets_widget,
            self.blocks_widget,
            self.loops_widget,
            self.analyzers_widget,
            self.globalparameters_widget,
        ]:
            widget.clear()

        datasets = json_object.get("datasets")
        if datasets:
            for name, dataset in datasets.items():
                editor = DatasetEditor(name, self.prefix_path)
                editor.setDatasetModel(self.dataset_model)
                editor.load(dataset)
                self.datasets_widget.addWidget(editor)

        used_algorithms = set()

        for type_, container, editor_klass in [
            ("blocks", self.blocks_widget, BlockEditor),
            ("loops", self.loops_widget, LoopBlockEditor),
            ("analyzers", self.analyzers_widget, AnalyzerBlockEditor),
        ]:
            items = json_object.get(type_)
            if items:
                for name, data in items.items():
                    editor = editor_klass(name, self.prefix_path)
                    editor.setAlgorithmModel(self.algorithm_model)
                    editor.setEnvironmentModel(self.processing_env_model)
                    editor.setQueueModel(self.queue_model)
                    editor.load(data)
                    editor.algorithmChanged.connect(self.__onAlgorithmChanged)
                    container.addWidget(editor)

                    if type_ == "loops":
                        used_algorithms |= editor.selectedAlgorithms()
                    else:
                        used_algorithms.add(editor.selectedAlgorithm())

        self.globalparameters_widget.setup(used_algorithms)
        self.tabwidget.tabBar().setTabEnabled(
            self.loops_widget_index, "loops" in json_object
        )
        globals_ = json_object.get("globals")
        if globals_:
            self.globalparameters_widget.load(globals_)
1161 1162 1163

    def _dump_json(self):
        """Returns the json representation of the asset"""
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224

        def __filter_parameters(blocks, globals_):
            """If algorithm parameters matches globals keep only the globals version"""

            algorithms = [
                key for key in globals_.keys() if key not in ["environment", "queue"]
            ]
            for block_name, block_data in blocks.items():
                for prefix in ["", PROCESSOR_PREFIX, EVALUATOR_PREFIX]:
                    algorithm_field = f"{prefix}algorithm"
                    parameter_field = f"{prefix}parameters"
                    if algorithm_field in block_data:
                        algorithm_name = block_data[algorithm_field]

                        if algorithm_name in algorithms:
                            block_parameters = block_data.get(parameter_field)
                            if block_parameters:
                                global_parameters = globals_[algorithm_name]
                                for (
                                    parameter_name,
                                    parameter_value,
                                ) in global_parameters.items():
                                    if (
                                        block_parameters[parameter_name]
                                        == parameter_value
                                    ):
                                        block_parameters.pop(parameter_name)
                                if not block_parameters:
                                    block_data.pop(parameter_field)

        def __filter_environment(blocks, globals_):
            globals_environment = globals_["environment"]

            for block_name, block_data in blocks.items():
                for prefix in ["", PROCESSOR_PREFIX, EVALUATOR_PREFIX]:
                    environment_key = f"{prefix}environment"

                    block_environment = block_data.get(environment_key)
                    if block_environment and block_environment == globals_environment:
                        block_data.pop(environment_key)

        analyzers = self.analyzers_widget.dump()
        blocks = self.blocks_widget.dump()
        loops = self.loops_widget.dump()
        globals_ = self.globalparameters_widget.dump()

        for item in [analyzers, blocks, loops]:
            __filter_parameters(item, globals_)
            __filter_environment(item, globals_)

        data = {
            "analyzers": analyzers,
            "blocks": blocks,
            "datasets": self.datasets_widget.dump(),
            "globals": globals_,
        }

        if loops:
            data["loops"] = loops

        return data