experimenteditor.py 53.2 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
import os
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
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.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

55 56 57 58
from PyQt5.QtSql import QSqlDatabase
from PyQt5.QtSql import QSqlQuery
from PyQt5.QtSql import QSqlTableModel

59 60 61
from beat.core.experiment import PROCESSOR_PREFIX
from beat.core.experiment import EVALUATOR_PREFIX

62 63
from beat.backend.python.algorithm import Algorithm

64
from ..backend.asset import Asset
65
from ..backend.asset import AssetType
66 67
from ..backend.assetmodel import AssetModel

68
from ..decorators import frozen
Samuel GAIST's avatar
Samuel GAIST committed
69

70 71 72 73 74 75 76
from ..utils import is_Qt_equal_or_higher

from .scrollwidget import ScrollWidget
from .scrollwidget import EditorListWidget

from .spinboxes import NumpySpinBox

77
from .editor import AbstractAssetEditor
78
from .dialogs import AssetCreationDialog
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
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 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:
128 129 130 131 132 133 134 135 136 137 138 139

            def add_row(type_, data):
                visual_name = "{name} ({version})".format(**data)
                icon = QIcon(f":/resources/{type_}")
                self.appendRow(
                    [
                        QStandardItem(icon, visual_name),
                        QStandardItem(data["name"]),
                        QStandardItem(data["version"]),
                    ]
                )

140 141
            with open(self.context.meta["environments"], "rt") as file_:
                json_data = json.load(file_)
142 143 144 145 146 147
                remote_data = json_data.get("remote", {})
                for data in remote_data:
                    add_row("remote", data)

                docker_data = json_data.get("docker", {})
                for _, data in docker_data.items():
148
                    if "databases" not in data:
149
                        add_row("docker", data)
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

    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()
231 232 233 234 235 236


# ------------------------------------------------------------------------------
# Prefix modelization


237
class ExperimentResources:
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
    def __init__(self, context=None):
        self.context = context

        database = QSqlDatabase.addDatabase("QSQLITE")
        database.setDatabaseName(":memory:")

        if not database.open():
            raise RuntimeError(
                f"Failed to open database: {database.lastError().text()}"
            )

        self.refresh()

    def setContext(self, context):
        if self.context == context:
            return

        self.context = context
        self.refresh()

    def refresh(self):
        if self.context is None:
            return

        ALGORITHM_TABLE_CLEANUP = "DROP TABLE IF EXISTS algorithms"
        ALGORITHM_TABLE = "CREATE TABLE algorithms(name varchar, type varchar, inputs integer, outputs integer, is_analyzer boolean)"
        INSERT_ALGORITHM = "INSERT INTO algorithms(name, type, inputs, outputs, is_analyzer) VALUES(?, ?, ?, ?, ?)"

        query = QSqlQuery()

        if not query.exec_(ALGORITHM_TABLE_CLEANUP):
            raise RuntimeError(f"Failed to drop table: {query.lastError().text()}")

        if not query.exec_(ALGORITHM_TABLE):
            raise RuntimeError(f"Failed to create table: {query.lastError().text()}")

        prefix_path = self.context.meta["config"].path
        model = AssetModel()
        model.asset_type = AssetType.ALGORITHM
        model.prefix_path = prefix_path
        model.setLatestOnlyEnabled(False)

        if not query.prepare(INSERT_ALGORITHM):
            raise RuntimeError(f"Failed to prepare query: {query.lastError().text()}")

        for algorithm in model.stringList():
            asset = Asset(prefix_path, AssetType.ALGORITHM, algorithm)
            try:
                declaration = asset.declaration
            except json.JSONDecodeError:
                continue

            inputs = {}
            outputs = {}
            for group in declaration["groups"]:
                inputs.update(group.get("inputs", {}))
                outputs.update(group.get("outputs", {}))

            query.addBindValue(algorithm)
            query.addBindValue(declaration.get("type", "legacy"))
            query.addBindValue(len(inputs))
            query.addBindValue(len(outputs))
            query.addBindValue("results" in declaration)

            if not query.exec_():
                raise RuntimeError(
                    f"Failed to insert algorithm: {query.lastError().text()}"
                )


308
class AlgorithmResourceModel(QSqlTableModel):
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
    def __init__(self, parent=None):
        super().__init__(parent=parent)

        self._analyzer_enabled = False
        self._input_count = None
        self._output_count = None
        self._types = []

        self.setTable("algorithms")
        self.select()
        self.update()

    def update(self):
        filter_str = f"is_analyzer={self._analyzer_enabled}"
        if self._input_count is not None:
            filter_str += f" AND inputs={self._input_count}"
        if self._output_count is not None:
            filter_str += f" AND outputs={self._output_count}"

        if self._types:
            filter_str += " AND type in ({})".format(
                ",".join([f"'{type_}'" for type_ in self._types])
            )

        self.setFilter(filter_str)

    def setAnalyzerEnabled(self, enabled):
        if self._analyzer_enabled == enabled:
            return

        self._analyzer_enabled = enabled
        self.update()

    def setInputCount(self, count):
        if self._input_count == count:
            return

        self._input_count = count
        self.update()

    def setOutputCount(self, count):
        if self._output_count == count:
            return

        self._output_count = count
        self.update()

    def setTypes(self, type_list):
        if self._types == type_list:
            return

        self._types = type_list
        self.update()
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


# ------------------------------------------------------------------------------
# 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):
472 473 474 475
        dataset_name = "{}/{}/{}".format(
            self.json_object["database"],
            self.json_object["protocol"],
            self.json_object["set"],
476
        )
477 478 479 480
        self.dataset_combobox.setCurrentText(dataset_name)

        if self.dataset_combobox.currentText() != dataset_name:
            self.dataset_combobox.setCurrentIndex(-1)
481 482 483 484 485 486 487 488 489 490 491 492 493

    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):
494 495 496 497 498 499 500 501 502
        current_dataset = self.dataset_combobox.currentText()
        try:
            database, db_version, protocol, set_ = current_dataset.split("/")
        except ValueError:
            database = None
            db_version = None
            protocol = None
            set_ = None

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

574 575 576 577
        if not algorithm_name:
            self.parameterCountChanged.emit(0)
            return

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
        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
685
        self.algorithm_model = None
686 687 688 689 690 691 692
        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)

693
        self.remap_button = QPushButton(QIcon(":/resources/remap"), "")
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
        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)
722
        self.algorithm_combobox.currentTextChanged.connect(self.__onAlgorithmChanged)
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
        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
        )

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
    @pyqtSlot(str)
    def __onAlgorithmChanged(self, algorithm_name):

        if not algorithm_name or not self.json_object:
            return

        # redo the io mapping

        asset = Asset(self.prefix_path, AssetType.ALGORITHM, algorithm_name)
        declaration = asset.declaration

        inputs = []
        outputs = []
        for group in declaration["groups"]:
            inputs += group.get("inputs", [])
            outputs += group.get("outputs", [])

        #  The key is the algorithm IO name and the value is toolchain IO name
        io_mapping = {}
        if sorted(inputs) != sorted(self.io_mapping["inputs"].keys()):
            io_mapping = {"inputs": {}}
            for key, value in zip(inputs, self.io_mapping["inputs"].values()):
                io_mapping["inputs"][key] = value

        if outputs and sorted(outputs) != sorted(self.io_mapping["outputs"].keys()):
            io_mapping["outputs"] = {}
            for key, value in zip(outputs, self.io_mapping["outputs"].values()):
                io_mapping["outputs"][key] = value

        if io_mapping:
            self.io_mapping = io_mapping

        self.algorithmChanged.emit(algorithm_name)

802 803 804 805 806
    def algorithm(self):
        return self.algorithm_combobox.currentText()

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

807
    def setAlgorithmResourceModel(self, model):
808 809
        self.algorithm_model = model
        self.algorithm_combobox.setModel(self.algorithm_model)
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825

    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)
826
        inputs = json_object.get("inputs", {})
827

828 829 830
        self.io_mapping = {"inputs": inputs}

        outputs = json_object.get("outputs", {})
831 832 833
        if outputs:
            self.io_mapping["outputs"] = outputs

834 835 836
        self.algorithm_model.setInputCount(len(inputs))
        self.algorithm_model.setOutputCount(len(outputs))

837 838 839 840
        algorithm_name = json_object["algorithm"]
        environment = json_object.get("environment")
        parameters = json_object.get("parameters")

841 842 843 844 845 846 847 848 849 850 851 852 853
        if algorithm_name:
            self.algorithm_combobox.setCurrentText(algorithm_name)
            if self.algorithm_combobox.currentText() != algorithm_name:
                available_algorithms = "\n".join(
                    self.algorithm_model.index(i, 0).data()
                    for i in range(self.algorithm_model.rowCount())
                )
                raise RuntimeError(
                    "Algorithm {} not available in list:\n {}".format(
                        algorithm_name, available_algorithms
                    )
                )
            self.parameters_editor.setup(algorithm_name)
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

        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

898
    def setAlgorithmResourceModel(self, model):
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
        """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)

918
        self.algorithm_model = AlgorithmResourceModel()
919 920 921 922 923
        self.algorithm_model.setAnalyzerEnabled(False)
        self.algorithm_model.setTypes(
            [Algorithm.LEGACY, Algorithm.SEQUENTIAL, Algorithm.AUTONOMOUS]
        )

924
        self.properties_editor = ExecutionPropertiesEditor(prefix_path)
925
        self.properties_editor.setAlgorithmResourceModel(self.algorithm_model)
926 927 928 929 930 931 932 933

        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)

934
        self.prefixPathChanged.connect(self.algorithm_model.update)
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958

    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)

959
        self.algorithm_model.setAnalyzerEnabled(True)
960 961 962 963 964 965


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

966
        self.processor_model = AlgorithmResourceModel()
967 968 969
        self.processor_model.setAnalyzerEnabled(False)
        self.processor_model.setTypes(
            [Algorithm.AUTONOMOUS_LOOP_PROCESSOR, Algorithm.SEQUENTIAL_LOOP_PROCESSOR]
970
        )
971

972
        self.evaluator_model = AlgorithmResourceModel()
973 974 975
        self.evaluator_model.setAnalyzerEnabled(False)
        self.evaluator_model.setTypes(
            [Algorithm.AUTONOMOUS_LOOP_EVALUATOR, Algorithm.SEQUENTIAL_LOOP_EVALUATOR]
976 977 978
        )

        self.processor_properties_editor = ExecutionPropertiesEditor(prefix_path)
979
        self.processor_properties_editor.setAlgorithmResourceModel(self.processor_model)
980
        self.evaluator_properties_editor = ExecutionPropertiesEditor(prefix_path)
981
        self.evaluator_properties_editor.setAlgorithmResourceModel(self.evaluator_model)
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
        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)

1003 1004
        self.prefixPathChanged.connect(self.processor_model.update)
        self.prefixPathChanged.connect(self.evaluator_model.update)
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 1034 1035 1036 1037 1038 1039 1040 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 1111 1112 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

    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:
1141 1142
            if not algorithm_name:
                continue
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
            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)

1157 1158 1159 1160
        environment = self.json_object.get("environment")
        if environment:
            env_text = "{} ({})".format(environment["name"], environment["version"])
            self.environment_combobox.setCurrentText(env_text)
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185

        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)

1186
        if self.environment_changed or "environment" not in data:
1187 1188 1189
            model = self.environment_combobox.model()
            index = model.index(self.environment_combobox.currentIndex(), 0)
            data["environment"] = model.environment(index)
1190
        if self.queue_changed or "queue" not in data:
1191 1192 1193 1194 1195 1196 1197 1198 1199
            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
1200
@frozen
1201 1202
class ExperimentEditor(AbstractAssetEditor):
    def __init__(self, parent=None):
1203
        super().__init__(AssetType.EXPERIMENT, parent)
Samuel GAIST's avatar
Samuel GAIST committed
1204
        self.setObjectName(self.__class__.__name__)
1205 1206
        self.set_title(self.tr("Experiment"))

1207
        self.prefix_model = ExperimentResources()
1208

1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
        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):
1253 1254
        self.prefix_model.setContext(self.context)

1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
        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)

1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
    def _createNewAsset(self, creation_type, asset_info):
        """Re-implement"""

        if creation_type == AssetCreationDialog.NEW:
            toolchain_name, experiment_name = asset_info
            toolchain = Asset(self.prefix_path, AssetType.TOOLCHAIN, toolchain_name)
            toolchain_declaration = toolchain.declaration
            experiment_declaration = {
                "schema_version": 1,
                "datasets": {},
                "blocks": {},
                "analyzers": {},
                "globals": {
                    "environment": {"name": "dummy", "version": "0.0.0"},
                    "queue": "queue",
                },
            }

            # databases

            database_model = AssetModel()
            database_model.asset_type = AssetType.DATABASE
            database_model.prefix_path = self.prefix_path

            for dataset in toolchain_declaration["datasets"]:
                dataset_data = {"database": None, "protocol": None, "set": None}
                name = dataset["name"]
                experiment_declaration["datasets"][name] = dataset_data

            # blocks

1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
            def build_block_data(block):
                block_data = {"algorithm": None}
                block_data["inputs"] = {
                    f"{input_}_tbr": input_ for input_ in block["inputs"]
                }
                outputs = block.get("outputs", [])
                if outputs:
                    block_data["outputs"] = {
                        f"{output}_tbr": output for output in outputs
                    }
1322 1323 1324 1325 1326

                return block_data

            for block in toolchain_declaration["blocks"]:
                name = block["name"]
1327
                experiment_declaration["blocks"][name] = build_block_data(block)
1328 1329 1330 1331

            # analyzers
            for analyzer in toolchain_declaration["analyzers"]:
                name = analyzer["name"]
1332
                experiment_declaration["analyzers"][name] = build_block_data(analyzer)
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362

            # loops
            if "loops" in toolchain_declaration:
                experiment_declaration["schema_version"] = 2
                experiment_declaration["loops"] = {}

                for loop in toolchain_declaration["loops"]:
                    loop_data = {}

                    processor_block = {
                        key[len(PROCESSOR_PREFIX) :]: value
                        for key, value in loop.items()
                        if key
                        in [
                            f"{PROCESSOR_PREFIX}inputs",
                            f"{PROCESSOR_PREFIX}outputs",
                            f"{PROCESSOR_PREFIX}algorithm",
                        ]
                    }
                    loop_block = {
                        key[len(EVALUATOR_PREFIX) :]: value
                        for key, value in loop.items()
                        if key
                        in [
                            f"{EVALUATOR_PREFIX}inputs",
                            f"{EVALUATOR_PREFIX}outputs",
                            f"{EVALUATOR_PREFIX}algorithm",
                        ]
                    }

1363 1364
                    processor_data = build_block_data(processor_block)
                    evaluator_data = build_block_data(loop_block)
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
                    loop_data.update(
                        {
                            f"{PROCESSOR_PREFIX}{key}": value
                            for key, value in processor_data.items()
                        }
                    )
                    loop_data.update(
                        {
                            f"{EVALUATOR_PREFIX}{key}": value
                            for key, value in evaluator_data.items()
                        }
                    )

                    name = loop["name"]
                    experiment_declaration["loops"][name] = loop_data

            user = self.context.meta["config"].user
            asset = Asset(
                self.prefix_path,
                AssetType.EXPERIMENT,
                os.path.join(user, toolchain_name, experiment_name),
            )
1387 1388
            os.makedirs(os.path.dirname(asset.declaration_path), exist_ok=True)
            asset.declaration = experiment_declaration
1389 1390 1391 1392 1393 1394 1395
            return asset, experiment_declaration

        else:
            return super(ExperimentEditor, self)._createNewAsset(
                creation_type, asset_info
            )

1396 1397
    def _load_json(self, json_object):
        """Load the json object passed as parameter"""
1398

1399 1400
        self.prefix_model.refresh()

1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
        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.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
        )
1444 1445 1446

        globals_ = json_object.get("globals", {})
        self.globalparameters_widget.load(globals_)
1447 1448 1449

    def _dump_json(self):
        """Returns the json representation of the asset"""
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510

        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