Example #1
0
 def addList(self, key, predefs, editable=False):
     if len(predefs) > 0 and not self.overwriteKeys(key):
         # Check if value list has the same type
         if type(key) == types.StringType:
             w = QComboBox()
             self.connect(w, SIGNAL("currentIndexChanged(QString)"),
                          self.argumentChanged)
             w.setEditable(editable)
             w.setValidator(QIntValidator())
             w.setMinimumContentsLength(20)
             for value in predefs:
                 if type(value).__name__ == 'str':
                     if w.findText(value) == -1:
                         w.addItem(value)
                 elif type(value).__name__ == 'int':
                     if w.findText(str(value)) == -1:
                         w.addItem(str(value))
                 else:
                     return -1
             if not self.displaykey:
                 self.layout.addRow(w)
             else:
                 self.layout.addRow(key, w)
             self.widgets[key] = w
             return 1
         else:
             return -1
     else:
         return -1
Example #2
0
class LoadResultsPanel(QWidget):

    def __init__(self):
        QWidget.__init__(self)

        self.setMinimumWidth(500)
        self.setMinimumHeight(200)
        self.__dynamic = False

        self.setWindowTitle("Load results manually")
        self.activateWindow()

        layout = QFormLayout()
        current_case = CaseSelectorModel().getCurrentChoice()

        self.__case_model = AllCasesModel()
        self.__case_combo = QComboBox()
        self.__case_combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
        self.__case_combo.setMinimumContentsLength(20)
        self.__case_combo.setModel(self.__case_model)
        self.__case_combo.setCurrentIndex(self.__case_model.indexOf(current_case))
        layout.addRow("Select case:",self.__case_combo)


        self.__active_realizations_model = LoadResultsRealizationsModel(EnsembleSizeModel().getValue())
        self.__active_realizations_field = StringBox(self.__active_realizations_model, "Realizations to load", "load_results_manually/Realizations")
        self.__active_realizations_field.setValidator(RangeStringArgument())
        layout.addRow(self.__active_realizations_field.getLabel(), self.__active_realizations_field)

        self.__iterations_count = LoadResultsModel().getIterationCount()

        self._iterations_model = LoadResultsIterationsModel(self.__iterations_count)
        self._iterations_field = StringBox(self._iterations_model, "Iteration to load", "load_results_manually/iterations")
        self._iterations_field.setValidator(RangeStringArgument())
        layout.addRow(self._iterations_field.getLabel(), self._iterations_field)

        self.setLayout(layout)

    def load(self):
        all_cases = self.__case_model.getAllItems()
        selected_case  = all_cases[self.__case_combo.currentIndex()]
        realizations = self.__active_realizations_model.getActiveRealizationsMask()
        iterations = self._iterations_model.getActiveRealizationsMask()

        LoadResultsModel().loadResults(selected_case, realizations, iterations)
    def addCaseSelector(self, disabled=False, current_case=None):
        if len(self.__case_selectors_order) == 5:
            return

        widget = QWidget()

        layout = QHBoxLayout()
        layout.setMargin(0)
        widget.setLayout(layout)

        combo = QComboBox()
        combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
        combo.setMinimumContentsLength(20)
        combo.setModel(self.__model)

        if current_case is not None:
            index = 0
            for item in self.__model:
                if item == current_case:
                    combo.setCurrentIndex(index)
                    break
                index += 1

        combo.currentIndexChanged.connect(self.caseSelectionChanged.emit)



        layout.addWidget(combo, 1)

        button = QToolButton()
        button.setAutoRaise(True)
        button.setDisabled(disabled)
        button.setIcon(util.resourceIcon("ide/small/delete"))
        button.clicked.connect(self.__signal_mapper.map)

        layout.addWidget(button)

        self.__case_selectors[widget] = combo
        self.__case_selectors_order.append(widget)
        self.__signal_mapper.setMapping(button, widget)

        self.__case_layout.addWidget(widget)

        self.caseSelectionChanged.emit()
    def addCaseSelector(self, disabled=False, current_case=None):
        widget = QWidget()

        layout = QHBoxLayout()
        layout.setMargin(0)
        widget.setLayout(layout)

        combo = QComboBox()
        combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
        combo.setMinimumContentsLength(20)
        combo.setModel(self.__model)

        if current_case is not None:
            index = 0
            for item in self.__model:
                if item == current_case:
                    combo.setCurrentIndex(index)
                    break
                index += 1

        combo.currentIndexChanged.connect(self.caseSelectionChanged.emit)



        layout.addWidget(combo, 1)

        button = QToolButton()
        button.setAutoRaise(True)
        button.setDisabled(disabled)
        button.setIcon(util.resourceIcon("ide/small/delete"))
        button.clicked.connect(self.__signal_mapper.map)

        layout.addWidget(button)

        self.__case_selectors[widget] = combo
        self.__case_selectors_order.append(widget)
        self.__signal_mapper.setMapping(button, widget)

        self.__case_layout.addWidget(widget)

        self.checkCaseCount()
        self.caseSelectionChanged.emit()
        def __init__(self, type, parent=None):
            QWidget.__init__(self,parent)
            self.ui = gui.entityAdderUi()
            self.ui.setupUi(self)
            # only show 'cancel' button until valid name has been given
            self.ui.buttonBox.setStandardButtons(\
                    QDialogButtonBox.Cancel|QDialogButtonBox.NoButton)                
            self.ui.formLayout.setHorizontalSpacing(120)
            self.ui.formLayout.setFieldGrowthPolicy(0)
            self.parent = parent
            self.type = type
            self.setWindowTitle("Add "+type)
            self.parent = parent  
            self.names = ['']              

            # dynamically add buttons depending on type and defined attributes
            if self.type == 'subject':
                self.attributes = parent.settings.subjectAttributes
                self.ui.openButton.hide()
                QObject.connect(self.ui.lineEdit, SIGNAL("returnPressed()"), self.submitSubject)
                QObject.connect(self.ui.lineEdit, SIGNAL("returnPressed()"), self.parent.refreshEntities)
            if self.type == 'stimulus':
                self.attributes = parent.settings.stimulusAttributes
                self.ui.label.hide()
                QObject.connect(self.ui.openButton, SIGNAL("clicked()"), self.selectStimulus)

            for (name,vals) in self.attributes:
                combobox = QComboBox(self)
                combobox.addItems(vals)
                combobox.setMinimumContentsLength(9)
                if name in self.parent.adderSettings:
                    i = combobox.findText(self.parent.adderSettings[name])
                    combobox.setCurrentIndex(i)
                self.ui.formLayout.addRow(name, combobox)

            # connect buttons
            QObject.connect(self.ui.lineEdit, SIGNAL("textChanged(QString)"), self.enableOK)
            QObject.connect(self.ui.buttonBox, SIGNAL("accepted()"), self.submitEntity)
            QObject.connect(self.ui.buttonBox, SIGNAL("accepted()"), self.parent.refreshEntities)
Example #6
0
 def addPathList(self, key, predefs):
     if not self.overwriteKeys(key) and type(key).__name__ == 'str':
         layout = QVBoxLayout()
         pathList = ListItem()  ##XXX
         pathList.setDragDropMode(QAbstractItemView.InternalMove)
         if len(predefs) > 0:
             if not self.checkUnifiedTypes(predefs):
                 return -1
             for predef in predefs:
                 pathList.addSingleItem(str(predef))
         hbox = QHBoxLayout()
         buttonbox = QDialogButtonBox()
         combo = QComboBox()
         combo.setMinimumContentsLength(20)
         self.connect(combo, SIGNAL("editTextChanged(QString)"),
                      self.argumentChanged)
         self.connect(combo, SIGNAL("currentIndexChanged(QString)"),
                      self.argumentChanged)
         combo.addItem(self.inputFile)
         combo.addItem(self.inputDirectory)
         add = PathSelectionButton(self, key, pathList, combo)
         buttonbox.addButton(add, QDialogButtonBox.ActionRole)
         rm = rmLocalPathButton(self, pathList)
         buttonbox.addButton(rm, QDialogButtonBox.ActionRole)
         self.connect(add, SIGNAL("clicked()"), self.argumentChanged)
         self.connect(rm, SIGNAL("clicked()"), self.argumentChanged)
         hbox.addWidget(buttonbox, 3, Qt.AlignLeft)
         hbox.addWidget(combo, 1, Qt.AlignRight)
         layout.addLayout(hbox, 0)
         layout.addWidget(pathList, 2)
         if not self.displaykey:
             self.layout.addRow(layout)
         else:
             self.layout.addRow(key, layout)
         self.widgets[key] = pathList
         return 1
     else:
         return -1
Example #7
0
class LoadResultsPanel(QWidget):

    def __init__(self):
        QWidget.__init__(self)

        self.setMinimumWidth(500)
        self.setMinimumHeight(200)
        self._dynamic = False

        self.setWindowTitle("Load results manually")
        self.activateWindow()

        layout = QFormLayout()
        current_case = getCurrentCaseName()

        run_path_text = QTextEdit()
        run_path_text.setText(self.readCurrentRunPath())
        run_path_text.setDisabled(True)
        run_path_text.setFixedHeight(80)

        layout.addRow("Load data from current run path: ",run_path_text)

        self._case_model = AllCasesModel()
        self._case_combo = QComboBox()
        self._case_combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
        self._case_combo.setMinimumContentsLength(20)
        self._case_combo.setModel(self._case_model)
        self._case_combo.setCurrentIndex(self._case_model.indexOf(current_case))
        layout.addRow("Load into case:", self._case_combo)


        self._active_realizations_model = ActiveRealizationsModel()
        self._active_realizations_field = StringBox(self._active_realizations_model, "load_results_manually/Realizations")
        self._active_realizations_field.setValidator(RangeStringArgument())
        layout.addRow("Realizations to load:", self._active_realizations_field)

        iterations_count = LoadResultsModel.getIterationCount()

        self._iterations_model = ValueModel(iterations_count)
        self._iterations_field = StringBox(self._iterations_model, "load_results_manually/iterations")
        self._iterations_field.setValidator(IntegerArgument())
        layout.addRow("Iteration to load:", self._iterations_field)

        self.setLayout(layout)

    def readCurrentRunPath(self):
        current_case = getCurrentCaseName()
        run_path = LoadResultsModel.getCurrentRunPath()
        run_path = run_path.replace("<ERTCASE>",current_case)
        run_path = run_path.replace("<ERT-CASE>",current_case)
        return run_path


    def load(self):
        all_cases = self._case_model.getAllItems()
        selected_case  = all_cases[self._case_combo.currentIndex()]
        realizations = self._active_realizations_model.getActiveRealizationsMask()
        iteration = self._iterations_model.getValue()
        try:
            if iteration is None:
                iteration = ''
            iteration = int(iteration)
        except ValueError as e:
            print('Expected a (whole) number in iteration field, got "%s". Error message: %s.'  % (iteration, e))
            return False
        loaded = LoadResultsModel.loadResults(selected_case, realizations, iteration)
        if loaded > 0:
            print('Successfully loaded %d realisations.' % loaded)
        else:
            print('No realisations loaded.')
        return loaded

    def setCurrectCase(self):
        current_case = getCurrentCaseName()
        self._case_combo.setCurrentIndex(self._case_model.indexOf(current_case))
Example #8
0
class ExportPanel(QWidget):
    updateExportButton = pyqtSignal(str, bool)
    runExport = pyqtSignal(dict)

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setMinimumWidth(500)
        self.setMinimumHeight(200)
        self._dynamic = False

        self.setWindowTitle("Export data")
        self.activateWindow()

        layout = QFormLayout()
        current_case = getCurrentCaseName()

        self._case_model = AllCasesModel()
        self._case_combo = QComboBox()
        self._case_combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
        self._case_combo.setMinimumContentsLength(20)
        self._case_combo.setModel(self._case_model)
        self._case_combo.setCurrentIndex(self._case_model.indexOf(current_case))
        layout.addRow("Select case:", self._case_combo)

        self._export_keyword_model = ExportKeywordModel()

        self._kw_model = self._export_keyword_model.getKeyWords()
        self._keywords = QComboBox()
        self._keywords.addItems(self._kw_model)
        layout.addRow("Select keyword:", self._keywords)

        self._active_realizations_model = ActiveRealizationsModel()
        self._active_realizations_field = StringBox(self._active_realizations_model, "config/simulation/active_realizations")
        self._active_realizations_field.setValidator(RangeStringArgument())
        self._active_realizations_field.getValidationSupport().validationChanged.connect(self.validateExportDialog)
        layout.addRow("Active realizations:", self._active_realizations_field)

        file_name_button = QToolButton()
        file_name_button.setText("Browse")
        file_name_button.clicked.connect(self.selectFileDirectory)

        self._defaultPath = QDir.currentPath() + "/export"
        self._file_name = QLineEdit()
        self._file_name.setEnabled(False)
        self._file_name.setText(self._defaultPath)
        self._file_name.textChanged.connect(self.validateExportDialog)
        self._file_name.setMinimumWidth(250)

        file_name_layout = QHBoxLayout()
        file_name_layout.addWidget(self._file_name)
        file_name_layout.addWidget(file_name_button)
        layout.addRow("Select directory to save files to:", file_name_layout)

        self._gen_kw_file_types = ["Parameter list", "Template based"]
        self._field_kw_file_types = ["Eclipse GRDECL", "RMS roff"]
        self._gen_data_file_types = ["Gen data"]

        self._file_type_model = self._field_kw_file_types
        self._file_type_combo = QComboBox()
        self._file_type_combo.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self._file_type_combo.addItems(self._file_type_model)
        layout.addRow("Select file format:", self._file_type_combo)

        self._report_step = QLineEdit()
        layout.addRow("Report step:", self._report_step)

        self._gen_data_report_step_model = []
        self._gen_data_report_step = QComboBox()
        layout.addRow("Report step:", self._gen_data_report_step)

        self.setLayout(layout)
        self._keywords.currentIndexChanged.connect(self.keywordSelected)
        self.keywordSelected()

    def selectFileDirectory(self):
        directory = QFileDialog().getExistingDirectory(self, "Directory", self._file_name.text(), QFileDialog.ShowDirsOnly)
        if str(directory).__len__() > 0:
            self._file_name.setText(str(directory))

    def updateFileExportType(self, keyword):
        self._file_type_combo.clear()
        if self._export_keyword_model.isGenKw(keyword):
            self._file_type_model = self._gen_kw_file_types
        elif self._export_keyword_model.isGenParamKw(keyword):
            self._file_type_model = self._gen_data_file_types
        elif self._export_keyword_model.isGenDataKw(keyword):
            self._file_type_model = self._gen_data_file_types
        else:
            self._file_type_model = self._field_kw_file_types

        self._file_type_combo.addItems(self._file_type_model)

    def export(self):
        keyword = self._kw_model[self._keywords.currentIndex()]
        try:
           report_step = self.getReportStep(keyword)
        except IndexError as e:
           QMessageBox.question(self, 'Error', e.args[0], QMessageBox.NoButton)
           return

        all_cases = self._case_model.getAllItems()
        selected_case = all_cases[self._case_combo.currentIndex()]
        path = self._file_name.text()
        iactive = self._active_realizations_model.getActiveRealizationsMask()
        file_type_key = self._file_type_model[self._file_type_combo.currentIndex()]
        values = {"keyword": keyword,
                  "report_step": report_step,
                  "iactive": iactive,
                  "file_type_key": file_type_key,
                  "path": path,
                  "selected_case": selected_case}
        self.runExport.emit(values)

    def getReportStep(self, key):
        report_step = 0
        if self._dynamic:
            report_step = self._report_step.text()

        if self._export_keyword_model.isGenParamKw(key):
            return report_step

        if self._export_keyword_model.isGenDataKw(key):
            lst = self._gen_data_report_step_model
            idx = self._gen_data_report_step.currentIndex()
            if lst and len(lst) > idx:
                report_step = lst[idx]
            else:
                raise IndexError('No such model step: %d.  Valid range: [0, %d)' % (idx, len(lst)))

        return report_step

    def keywordSelected(self):
        key = self._kw_model[self._keywords.currentIndex()]
        self.updateFileExportType(key)
        self._dynamic = False
        if self._export_keyword_model.isFieldKw(key):
            self._dynamic = self._export_keyword_model.isDynamicField(key)

        self._report_step.setVisible(self._dynamic)
        self.layout().labelForField(self._report_step).setVisible(self._dynamic)

        self._gen_data_report_step.setVisible(self._export_keyword_model.isGenDataKw(key))
        self.layout().labelForField(self._gen_data_report_step).setVisible(self._export_keyword_model.isGenDataKw(key))

        if self._export_keyword_model.isGenDataKw(key):
            data = self._export_keyword_model.getGenDataReportSteps(key)
            self._gen_data_report_step_model = data
            self._gen_data_report_step.clear()
            self._gen_data_report_step.addItems(self._gen_data_report_step_model)

    def setSelectedCase(self, selected_case):
        self._case_combo.setCurrentIndex(self._case_model.indexOf(selected_case))

    def validateExportDialog(self):
        validRealizations = False
        if self._active_realizations_field.isValid():
            validRealizations = True

        path = str(self._file_name.text())
        validPath = len(path) > 0

        if validRealizations and validPath:
            self.updateExportButton.emit("export", True)
        else:
            self.updateExportButton.emit("export", False)
Example #9
0
class ExportPanel(QWidget):
    updateExportButton = pyqtSignal(str, bool)
    runExport = pyqtSignal(dict)

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setMinimumWidth(500)
        self.setMinimumHeight(200)
        self._dynamic = False

        self.setWindowTitle("Export data")
        self.activateWindow()

        layout = QFormLayout()
        current_case = getCurrentCaseName()

        self._case_model = AllCasesModel()
        self._case_combo = QComboBox()
        self._case_combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
        self._case_combo.setMinimumContentsLength(20)
        self._case_combo.setModel(self._case_model)
        self._case_combo.setCurrentIndex(self._case_model.indexOf(current_case))
        layout.addRow("Select case:", self._case_combo)

        self._export_keyword_model = ExportKeywordModel()

        self._kw_model = self._export_keyword_model.getKeyWords()
        self._keywords = QComboBox()
        self._keywords.addItems(self._kw_model)
        layout.addRow("Select keyword:", self._keywords)

        self._active_realizations_model = ActiveRealizationsModel()
        self._active_realizations_field = StringBox(self._active_realizations_model, "config/simulation/active_realizations")
        self._active_realizations_field.setValidator(RangeStringArgument())
        self._active_realizations_field.getValidationSupport().validationChanged.connect(self.validateExportDialog)
        layout.addRow("Active realizations:", self._active_realizations_field)

        file_name_button = QToolButton()
        file_name_button.setText("Browse")
        file_name_button.clicked.connect(self.selectFileDirectory)

        self._defaultPath = QDir.currentPath() + "/export"
        self._file_name = QLineEdit()
        self._file_name.setEnabled(False)
        self._file_name.setText(self._defaultPath)
        self._file_name.textChanged.connect(self.validateExportDialog)
        self._file_name.setMinimumWidth(250)

        file_name_layout = QHBoxLayout()
        file_name_layout.addWidget(self._file_name)
        file_name_layout.addWidget(file_name_button)
        layout.addRow("Select directory to save files to:", file_name_layout)

        self._gen_kw_file_types = ["Parameter list", "Template based"]
        self._field_kw_file_types = ["Eclipse GRDECL", "RMS roff"]
        self._gen_data_file_types = ["Gen data"]

        self._file_type_model = self._field_kw_file_types
        self._file_type_combo = QComboBox()
        self._file_type_combo.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self._file_type_combo.addItems(self._file_type_model)
        layout.addRow("Select file format:", self._file_type_combo)

        self._report_step = QLineEdit()
        layout.addRow("Report step:", self._report_step)

        self._gen_data_report_step_model = []
        self._gen_data_report_step = QComboBox()
        layout.addRow("Report step:", self._gen_data_report_step)

        self.setLayout(layout)
        self._keywords.currentIndexChanged.connect(self.keywordSelected)
        self.keywordSelected()

    def selectFileDirectory(self):
        directory = QFileDialog().getExistingDirectory(self, "Directory", self._file_name.text(), QFileDialog.ShowDirsOnly)
        if str(directory).__len__() > 0:
            self._file_name.setText(str(directory))

    def updateFileExportType(self, keyword):
        self._file_type_combo.clear()
        if self._export_keyword_model.isGenKw(keyword):
            self._file_type_model = self._gen_kw_file_types
        elif self._export_keyword_model.isGenParamKw(keyword):
            self._file_type_model = self._gen_data_file_types
        elif self._export_keyword_model.isGenDataKw(keyword):
            self._file_type_model = self._gen_data_file_types
        else:
            self._file_type_model = self._field_kw_file_types

        self._file_type_combo.addItems(self._file_type_model)

    def export(self):
        keyword = self._kw_model[self._keywords.currentIndex()]
        report_step = self.getReportStep(keyword)
        all_cases = self._case_model.getAllItems()
        selected_case = all_cases[self._case_combo.currentIndex()]
        path = self._file_name.text()
        iactive = self._active_realizations_model.getActiveRealizationsMask()
        file_type_key = self._file_type_model[self._file_type_combo.currentIndex()]
        values = {"keyword": keyword,
                  "report_step": report_step,
                  "iactive": iactive,
                  "file_type_key": file_type_key,
                  "path": path,
                  "selected_case": selected_case}
        self.runExport.emit(values)

    def getReportStep(self, key):
        report_step = 0
        if self._dynamic:
            report_step = self._report_step.text()

        if self._export_keyword_model.isGenParamKw(key):
            return report_step

        if self._export_keyword_model.isGenDataKw(key):
            lst = self._gen_data_report_step_model
            idx = self._gen_data_report_step.currentIndex()
            if lst and len(lst) > idx:
                report_step = lst[idx]
            else:
                raise IndexError('No such model step: %d.  Valid range: [0, %d)' % (idx, len(lst)))

        return report_step

    def keywordSelected(self):
        key = self._kw_model[self._keywords.currentIndex()]
        self.updateFileExportType(key)
        self._dynamic = False
        if self._export_keyword_model.isFieldKw(key):
            self._dynamic = self._export_keyword_model.isDynamicField(key)

        self._report_step.setVisible(self._dynamic)
        self.layout().labelForField(self._report_step).setVisible(self._dynamic)

        self._gen_data_report_step.setVisible(self._export_keyword_model.isGenDataKw(key))
        self.layout().labelForField(self._gen_data_report_step).setVisible(self._export_keyword_model.isGenDataKw(key))

        if self._export_keyword_model.isGenDataKw(key):
            data = self._export_keyword_model.getGenDataReportSteps(key)
            self._gen_data_report_step_model = data
            self._gen_data_report_step.clear()
            self._gen_data_report_step.addItems(self._gen_data_report_step_model)

    def setSelectedCase(self, selected_case):
        self._case_combo.setCurrentIndex(self._case_model.indexOf(selected_case))

    def validateExportDialog(self):
        validRealizations = False
        if self._active_realizations_field.isValid():
            validRealizations = True

        path = str(self._file_name.text())
        validPath = len(path) > 0

        if validRealizations and validPath:
            self.updateExportButton.emit("export", True)
        else:
            self.updateExportButton.emit("export", False)
Example #10
0
class LoadResultsPanel(QWidget):

    def __init__(self):
        QWidget.__init__(self)

        self.setMinimumWidth(500)
        self.setMinimumHeight(200)
        self.__dynamic = False

        self.setWindowTitle("Load results manually")
        self.activateWindow()

        layout = QFormLayout()
        current_case = CaseSelectorModel().getCurrentChoice()

        run_path_text = QTextEdit()
        run_path_text.setText(self.readCurrentRunPath())
        run_path_text.setDisabled(True)
        run_path_text.setFixedHeight(80)

        layout.addRow("Load data from current run path: ",run_path_text)

        self.__case_model = AllCasesModel()
        self.__case_combo = QComboBox()
        self.__case_combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
        self.__case_combo.setMinimumContentsLength(20)
        self.__case_combo.setModel(self.__case_model)
        self.__case_combo.setCurrentIndex(self.__case_model.indexOf(current_case))
        layout.addRow("Load into case:",self.__case_combo)


        self.__active_realizations_model = LoadResultsRealizationsModel(EnsembleSizeModel().getValue())
        self.__active_realizations_field = StringBox(self.__active_realizations_model, "Realizations to load", "load_results_manually/Realizations")
        self.__active_realizations_field.setValidator(RangeStringArgument())
        layout.addRow(self.__active_realizations_field.getLabel(), self.__active_realizations_field)

        self.__iterations_count = LoadResultsModel().getIterationCount()

        self._iterations_model = LoadResultsIterationsModel(self.__iterations_count)
        self._iterations_field = StringBox(self._iterations_model, "Iteration to load", "load_results_manually/iterations")
        self._iterations_field.setValidator(IntegerArgument())
        layout.addRow(self._iterations_field.getLabel(), self._iterations_field)

        self.setLayout(layout)

    def readCurrentRunPath(self):
        current_case = CaseSelectorModel().getCurrentChoice()
        run_path = LoadResultsModel().getCurrentRunPath()
        run_path = run_path.replace("<ERTCASE>",current_case)
        run_path = run_path.replace("<ERT-CASE>",current_case)
        return run_path


    def load(self):
        all_cases = self.__case_model.getAllItems()
        selected_case  = all_cases[self.__case_combo.currentIndex()]
        realizations = self.__active_realizations_model.getActiveRealizationsMask()
        iteration = self._iterations_model.getActiveIteration()

        LoadResultsModel().loadResults(selected_case, realizations, iteration)

    def setCurrectCase(self):
        current_case = CaseSelectorModel().getCurrentChoice()
        self.__case_combo.setCurrentIndex(self.__case_model.indexOf(current_case))
class CaseInitializationConfigurationPanel(RowPanel):

    @may_take_a_long_time
    def __init__(self):
        RowPanel.__init__(self, "Case Management")
        self.setMinimumWidth(600)

        self.addCreateNewCaseTab()
        self.addInitializeFromScratchTab()
        self.addInitializeFromExistingTab()
        self.addShowCaseInfo()

        self.endTabs()

    def newValidatedKeywordPopup(self, existing_keywords):
        dialog = ValidatedDialog("New case", "Enter name of new case:", existing_keywords)
        return dialog.showAndTell()

    def addCreateNewCaseTab(self):
        self.startTabs("Create new case")

        case_list = KeywordList(CaseList(), "Available cases", "init/case_list")
        case_list.setMaximumWidth(250)
        case_list.newKeywordPopup = self.newValidatedKeywordPopup
        case_list.setSelectable(False)

        self.addRow(case_list)


    def addInitializeFromScratchTab(self):
        self.addTab("Initialize from scratch")

        case_model = CaseSelectorModel()
        case_selector = ComboChoice(case_model, "Target case", "init/current_case_selection")
        self.addRow(case_selector)

        row_group = RowGroup()


        parameter_model = InitializationParametersModel()
        parameter_check_list = CheckList(parameter_model, "Parameters", "init/select_parameters")
        parameter_check_list.setMaximumWidth(300)
        row_group.addWidget(parameter_check_list)

        member_model = InitializationMembersModel()
        member_check_list = CheckList(member_model, "Members", "init/select_members")
        member_check_list.setMaximumWidth(150)
        row_group.addWidget(member_check_list)

        self.addRow(row_group)

        self.addSpace(10)

        initialize_from_scratch = InitializeFromScratchModel()
        self.addRow(Button(initialize_from_scratch, help_link="init/initialize_from_scratch"))

        self.addSpace(10)


    def addInitializeFromExistingTab(self):
        self.addTab("Initialize from existing")

        case_model = CaseSelectorModel()
        target_case_selector = ComboChoice(case_model, "Target case", "init/current_case_selection")
        self.addRow(target_case_selector)

        initialized_cases = ComboChoice(InitializedCaseSelectorModel(), "Source case", "init/source_case")
        self.addRow(initialized_cases)

        #self.addRow("State", "Analyzed/Forecast")

        timestep_group = RowGroup("Timestep")
        history_length = HistoryLengthModel()
        history_length_spinner = IntegerSpinner(history_length, "Timestep", "config/init/history_length")
        timestep_group.addWidget(history_length_spinner)

        initial = QToolButton()
        initial.setText("Initial")
        initial.clicked.connect(history_length.setToMin)
        timestep_group.addWidget(initial)

        end_of_time = QToolButton()
        end_of_time.setText("End of time")
        end_of_time.clicked.connect(history_length.setToMax)
        timestep_group.addWidget(end_of_time)

        timestep_group.addGroupStretch()

        self.addRow(timestep_group)

        self.addSpace(10)

        row_group = RowGroup()
        parameter_model = InitializationParametersModel()
        parameter_check_list = CheckList(parameter_model, "Parameters", "init/select_parameters")
        parameter_check_list.setMaximumWidth(300)
        row_group.addWidget(parameter_check_list)

        member_model = InitializationMembersModel()
        member_check_list = CheckList(member_model, "Members", "init/select_members")
        member_check_list.setMaximumWidth(150)
        row_group.addWidget(member_check_list)

        self.addRow(row_group)

        self.addSpace(10)

        initialize_from_existing = InitializeFromExistingCaseModel()
        self.addRow(Button(initialize_from_existing, help_link="init/initialize_from_existing"))

        self.addSpace(10)

    def addShowCaseInfo(self):
        self.addTab("Case Info")

        case_widget = HelpedWidget("Select case", "init/select_case_for_info")

        model = AllCasesModel()
        self.combo = QComboBox()
        self.combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
        self.combo.setMinimumContentsLength(20)
        self.combo.setModel(model)
        self.combo.currentIndexChanged.connect(self.showInfoForCase)

        case_widget.addWidget(self.combo)
        case_widget.addStretch()
        self.addRow(case_widget)


        area_widget = HelpedWidget("Case info", "init/selected_case_info")

        self.text_area = QTextEdit()
        self.text_area.setReadOnly(True)
        self.text_area.setMinimumHeight(300)

        area_widget.addWidget(self.text_area)
        area_widget.addStretch()
        self.addRow(area_widget)

        choice = CaseSelectorModel().getCurrentChoice()
        self.combo.setCurrentIndex(model.indexOf(choice))


    def showInfoForCase(self):
        case = self.combo.currentText()

        states = CaseList().getCaseRealizationStates(str(case))

        html = "<table>"
        for index in range(len(states)):
            html += "<tr><td width=30>%d.</td><td>%s</td></tr>" % (index, str(states[index]))

        html += "</table>"


        self.text_area.setHtml(html)
Example #12
0
class LoadResultsPanel(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.setMinimumWidth(500)
        self.setMinimumHeight(200)
        self._dynamic = False

        self.setWindowTitle("Load results manually")
        self.activateWindow()

        layout = QFormLayout()
        current_case = getCurrentCaseName()

        run_path_text = QTextEdit()
        run_path_text.setText(self.readCurrentRunPath())
        run_path_text.setDisabled(True)
        run_path_text.setFixedHeight(80)

        layout.addRow("Load data from current run path: ", run_path_text)

        self._case_model = AllCasesModel()
        self._case_combo = QComboBox()
        self._case_combo.setSizeAdjustPolicy(
            QComboBox.AdjustToMinimumContentsLength)
        self._case_combo.setMinimumContentsLength(20)
        self._case_combo.setModel(self._case_model)
        self._case_combo.setCurrentIndex(
            self._case_model.indexOf(current_case))
        layout.addRow("Load into case:", self._case_combo)

        self._active_realizations_model = ActiveRealizationsModel()
        self._active_realizations_field = StringBox(
            self._active_realizations_model,
            "load_results_manually/Realizations")
        self._active_realizations_field.setValidator(RangeStringArgument())
        layout.addRow("Realizations to load:", self._active_realizations_field)

        iterations_count = LoadResultsModel.getIterationCount()

        self._iterations_model = ValueModel(iterations_count)
        self._iterations_field = StringBox(self._iterations_model,
                                           "load_results_manually/iterations")
        self._iterations_field.setValidator(IntegerArgument())
        layout.addRow("Iteration to load:", self._iterations_field)

        self.setLayout(layout)

    def readCurrentRunPath(self):
        current_case = getCurrentCaseName()
        run_path = LoadResultsModel.getCurrentRunPath()
        run_path = run_path.replace("<ERTCASE>", current_case)
        run_path = run_path.replace("<ERT-CASE>", current_case)
        return run_path

    def load(self):
        all_cases = self._case_model.getAllItems()
        selected_case = all_cases[self._case_combo.currentIndex()]
        realizations = self._active_realizations_model.getActiveRealizationsMask(
        )
        iteration = self._iterations_model.getValue()
        try:
            if iteration is None:
                iteration = ''
            iteration = int(iteration)
        except ValueError as e:
            print(
                'Expected a (whole) number in iteration field, got "%s". Error message: %s.'
                % (iteration, e))
            return False
        loaded = LoadResultsModel.loadResults(selected_case, realizations,
                                              iteration)
        if loaded > 0:
            print('Successfully loaded %d realisations.' % loaded)
        else:
            print('No realisations loaded.')
        return loaded

    def setCurrectCase(self):
        current_case = getCurrentCaseName()
        self._case_combo.setCurrentIndex(
            self._case_model.indexOf(current_case))
Example #13
0
class ExportPanel(QWidget):

    def __init__(self):
        QWidget.__init__(self)

        self.setMinimumWidth(500)
        self.setMinimumHeight(200)
        self.__dynamic = False

        self.setWindowTitle("Export data")
        self.activateWindow()

        layout = QFormLayout()
        current_case = CaseSelectorModel().getCurrentChoice()

        self.__case_model = AllCasesModel()
        self.__case_combo = QComboBox()
        self.__case_combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
        self.__case_combo.setMinimumContentsLength(20)
        self.__case_combo.setModel(self.__case_model)
        self.__case_combo.setCurrentIndex(self.__case_model.indexOf(current_case))
        layout.addRow("Select case:",self.__case_combo)

        self.__export_keyword_model = ExportKeywordModel()

        self.__kw_model = self.__export_keyword_model.getKeyWords()
        self.__keywords = QComboBox()
        self.__keywords.addItems(self.__kw_model)
        layout.addRow("Select keyword:",self.__keywords)

        self.__active_realizations_model = ExportRealizationsModel(EnsembleSizeModel().getValue())
        self.__active_realizations_field = StringBox(self.__active_realizations_model, "Active realizations", "config/simulation/active_realizations")
        self.__active_realizations_field.setValidator(RangeStringArgument())
        layout.addRow(self.__active_realizations_field.getLabel(), self.__active_realizations_field)

        file_name_button= QToolButton()
        file_name_button.setText("Browse")
        file_name_button.clicked.connect(self.selectFileDirectory)

        self.__file_name = QLineEdit()
        self.__file_name.setEnabled(False)
        self.__file_name.setText(QDir.currentPath()+"/export")
        self.__file_name.setMinimumWidth(250)

        file_name_layout = QHBoxLayout()
        file_name_layout.addWidget(self.__file_name)
        file_name_layout.addWidget(file_name_button)
        layout.addRow("Select directory to save files to:", file_name_layout)

        self.__gen_kw_file_types = ["Parameter list", "Template based"]
        self.__field_kw_file_types = ["Eclipse GRDECL", "RMS roff"]

        self.__file_type_model = self.__field_kw_file_types
        self.__file_type_combo = QComboBox()
        self.__file_type_combo.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self.__file_type_combo.addItems(self.__file_type_model)
        layout.addRow("Select file format:",self.__file_type_combo)

        self.__report_step = QLineEdit()
        layout.addRow("Report step:", self.__report_step)

        self.setLayout(layout)
        self.__keywords.currentIndexChanged.connect(self.keywordSelected)
        self.keywordSelected()

    def selectFileDirectory(self):
        directory = QFileDialog().getExistingDirectory(self, "Directory", QDir.currentPath(), QFileDialog.ShowDirsOnly)
        self.__file_name.setText(str(directory))

    def updateFileExportType(self):
        keyword = self.__kw_model[self.__keywords.currentIndex()]
        self.__file_type_combo.clear()
        if self.__export_keyword_model.isGenKw(keyword):
            self.__file_type_model = self.__gen_kw_file_types
        else:
            self.__file_type_model = self.__field_kw_file_types

        self.__file_type_combo.addItems(self.__file_type_model)

    def export(self):
        report_step = 0
        if self.__dynamic:
            report_step = self.__report_step.text()
        keyword = self.__kw_model[self.__keywords.currentIndex()]
        all_cases = self.__case_model.getAllItems()
        selected_case  = all_cases[self.__case_combo.currentIndex()]

        file_name = self.createExportFilNameMask(keyword, selected_case)

        iactive = self.__active_realizations_model.getActiveRealizationsMask()

        file_type_key = self.__file_type_model[self.__file_type_combo.currentIndex()]
        state = EnkfStateType.FORECAST

        if self.__export_keyword_model.isFieldKw(keyword):
            self.exportField(keyword, file_name, iactive, file_type_key, report_step, state, selected_case)
        elif self.__export_keyword_model.isGenKw(keyword):
            self.exportGenKw(keyword, file_name, iactive, file_type_key, report_step, state, selected_case)


    def exportGenKw(self, keyword, file_name, iactive, file_type_key, report_step, state, selected_case):
        ExportModel().exportGenKw(keyword, file_name, iactive, file_type_key, report_step, state, selected_case)


    def exportField(self, keyword, file_name, iactive, file_type_key, report_step, state, selected_case):
        if file_type_key == "Eclipse GRDECL":
            file_type = EnkfFieldFileFormatEnum.ECL_GRDECL_FILE
        else:
            file_type = EnkfFieldFileFormatEnum.RMS_ROFF_FILE

        result = ExportModel().exportField(keyword, file_name, iactive, file_type, report_step, state, selected_case)
        if not result:
            QMessageBox.warning(self, "Warning",'''Something did not work!''',QMessageBox.Ok);

    def createExportFilNameMask(self, keyword, current_case):
        path = self.__file_name.text()
        impl_type = None

        if self.__export_keyword_model.isFieldKw(keyword):
            impl_type = ExportKeywordModel().getImplementationType(keyword)
        elif self.__export_keyword_model.isGenKw(keyword):
            impl_type = "Gen_Kw"

        path = str(path) + "/" + str(current_case) + "/" + str(impl_type) + "/" + str(keyword)

        if not QDir(path).exists():
            os.makedirs(path);

        return path

    def keywordSelected(self):
        self.updateFileExportType()
        key = self.__kw_model[self.__keywords.currentIndex()]
        if self.__export_keyword_model.isFieldKw(key):
            self.__dynamic = ExportKeywordModel().isDynamicField(key)
        else:
            self.__dynamic = False

        self.__report_step.setVisible(self.__dynamic)
        self.layout().labelForField(self.__report_step).setVisible(self.__dynamic)
Example #14
0
class LoadResultsPanel(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.setMinimumWidth(500)
        self.setMinimumHeight(200)
        self._dynamic = False

        self.setWindowTitle("Load results manually")
        self.activateWindow()

        layout = QFormLayout()
        current_case = getCurrentCaseName()

        run_path_text = QTextEdit()
        run_path_text.setText(self.readCurrentRunPath())
        run_path_text.setDisabled(True)
        run_path_text.setFixedHeight(80)

        layout.addRow("Load data from current run path: ", run_path_text)

        self._case_model = AllCasesModel()
        self._case_combo = QComboBox()
        self._case_combo.setSizeAdjustPolicy(
            QComboBox.AdjustToMinimumContentsLength)
        self._case_combo.setMinimumContentsLength(20)
        self._case_combo.setModel(self._case_model)
        self._case_combo.setCurrentIndex(
            self._case_model.indexOf(current_case))
        layout.addRow("Load into case:", self._case_combo)

        self._active_realizations_model = ActiveRealizationsModel()
        self._active_realizations_field = StringBox(
            self._active_realizations_model,
            "load_results_manually/Realizations")
        self._active_realizations_field.setValidator(RangeStringArgument())
        layout.addRow("Realizations to load:", self._active_realizations_field)

        iterations_count = LoadResultsModel.getIterationCount()

        self._iterations_model = ValueModel(iterations_count)
        self._iterations_field = StringBox(self._iterations_model,
                                           "load_results_manually/iterations")
        self._iterations_field.setValidator(IntegerArgument(from_value=1))
        layout.addRow("Iteration to load:", self._iterations_field)

        self.setLayout(layout)

    def readCurrentRunPath(self):
        current_case = getCurrentCaseName()
        run_path = LoadResultsModel.getCurrentRunPath()
        run_path = run_path.replace("<ERTCASE>", current_case)
        run_path = run_path.replace("<ERT-CASE>", current_case)
        return run_path

    def load(self):
        all_cases = self._case_model.getAllItems()
        selected_case = all_cases[self._case_combo.currentIndex()]
        realizations = self._active_realizations_model.getActiveRealizationsMask(
        )
        iteration = self._iterations_model.getActiveIteration()

        LoadResultsModel.loadResults(selected_case, realizations, iteration)

    def setCurrectCase(self):
        current_case = getCurrentCaseName()
        self._case_combo.setCurrentIndex(
            self._case_model.indexOf(current_case))
Example #15
0
class ScoringDialog(QWidget):
    """a dialog for entering the scores"""
    # pylint: disable=R0902
    # pylint we need more than 10 instance attributes

    scoringClosed = pyqtSignal()

    def __init__(self, game):
        QWidget.__init__(self, None)
        self.game = None
        self.setWindowTitle(m18n('Scoring for this Hand') + ' - Kajongg')
        self.nameLabels = [None] * 4
        self.spValues = [None] * 4
        self.windLabels = [None] * 4
        self.wonBoxes = [None] * 4
        self.detailsLayout = [None] * 4
        self.details = [None] * 4
        self.__tilePixMaps = []
        self.__meldPixMaps = []
        grid = QGridLayout(self)
        pGrid = QGridLayout()
        grid.addLayout(pGrid, 0, 0, 2, 1)
        pGrid.addWidget(QLabel(m18nc('kajongg', "Player")), 0, 0)
        pGrid.addWidget(QLabel(m18nc('kajongg', "Wind")), 0, 1)
        pGrid.addWidget(QLabel(m18nc('kajongg', 'Score')), 0, 2)
        pGrid.addWidget(QLabel(m18n("Winner")), 0, 3)
        self.detailTabs = QTabWidget()
        self.detailTabs.setDocumentMode(True)
        pGrid.addWidget(self.detailTabs, 0, 4, 8, 1)
        for idx in range(4):
            self.setupUiForPlayer(pGrid, idx)
        self.draw = QCheckBox(m18nc('kajongg','Draw'))
        self.draw.clicked.connect(self.wonChanged)
        btnPenalties = QPushButton(m18n("&Penalties"))
        btnPenalties.clicked.connect(self.penalty)
        self.btnSave = QPushButton(m18n('&Save Hand'))
        self.btnSave.setEnabled(False)
        self.setupUILastTileMeld(pGrid)
        pGrid.setRowStretch(87, 10)
        pGrid.addWidget(self.draw, 7, 3)
        self.cbLastTile.currentIndexChanged.connect(self.slotLastTile)
        self.cbLastMeld.currentIndexChanged.connect(self.slotInputChanged)
        btnBox = QHBoxLayout()
        btnBox.addWidget(btnPenalties)
        btnBox.addWidget(self.btnSave)
        pGrid.addLayout(btnBox, 8, 4)
        StateSaver(self)
        self.refresh(game)

    def setupUILastTileMeld(self, pGrid):
        """setup UI elements for last tile and last meld"""
        self.lblLastTile = QLabel(m18n('&Last Tile:'))
        self.cbLastTile = QComboBox()
        self.cbLastTile.setMinimumContentsLength(1)
        vpol = QSizePolicy()
        vpol.setHorizontalPolicy(QSizePolicy.Fixed)
        self.cbLastTile.setSizePolicy(vpol)
        self.cbLastTile.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
        self.lblLastTile.setBuddy(self.cbLastTile)
        self.lblLastMeld = QLabel(m18n('L&ast Meld:'))
        self.prevLastTile = None
        self.cbLastMeld = QComboBox()
        self.cbLastMeld.setMinimumContentsLength(1)
        self.cbLastMeld.setSizePolicy(vpol)
        self.cbLastMeld.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
        self.lblLastMeld.setBuddy(self.cbLastMeld)
        self.comboTilePairs = set()
        pGrid.setRowStretch(6, 5)
        pGrid.addWidget(self.lblLastTile, 7, 0, 1, 2)
        pGrid.addWidget(self.cbLastTile, 7, 2, 1, 1)
        pGrid.addWidget(self.lblLastMeld, 8, 0, 1, 2)
        pGrid.addWidget(self.cbLastMeld, 8, 2, 1, 2)

    def setupUiForPlayer(self, pGrid, idx):
        """setup UI elements for a player"""
        self.spValues[idx] = QSpinBox()
        self.nameLabels[idx] = QLabel()
        self.nameLabels[idx].setBuddy(self.spValues[idx])
        self.windLabels[idx] = WindLabel()
        pGrid.addWidget(self.nameLabels[idx], idx+2, 0)
        pGrid.addWidget(self.windLabels[idx], idx+2, 1)
        pGrid.addWidget(self.spValues[idx], idx+2, 2)
        self.wonBoxes[idx] = QCheckBox("")
        pGrid.addWidget(self.wonBoxes[idx], idx+2, 3)
        self.wonBoxes[idx].clicked.connect(self.wonChanged)
        self.spValues[idx].valueChanged.connect(self.slotInputChanged)
        detailTab = QWidget()
        self.detailTabs.addTab(detailTab,'')
        self.details[idx] = QWidget()
        detailTabLayout = QVBoxLayout(detailTab)
        detailTabLayout.addWidget(self.details[idx])
        detailTabLayout.addStretch()
        self.detailsLayout[idx] = QVBoxLayout(self.details[idx])


    def refresh(self, game):
        """reload game"""
        if game and not game.isScoringGame():
            return
        self.game = game
        self.clear()
        self.setVisible(game is not None and not game.finished())
        if game:
            for idx, player in enumerate(game.players):
                for child in self.details[idx].children():
                    if isinstance(child, RuleBox):
                        child.hide()
                        self.detailsLayout[idx].removeWidget(child)
                        del child
                if game:
                    self.spValues[idx].setRange(0, game.ruleset.limit or 99999)
                    self.nameLabels[idx].setText(player.localName)
                    self.windLabels[idx].wind = player.wind
                    self.windLabels[idx].roundsFinished = game.roundsFinished
                    self.detailTabs.setTabText(idx, player.localName)
                    player.manualRuleBoxes = [RuleBox(x) for x in game.ruleset.allRules if x.hasSelectable]
                    for ruleBox in player.manualRuleBoxes:
                        self.detailsLayout[idx].addWidget(ruleBox)
                        ruleBox.clicked.connect(self.slotInputChanged)
                player.refreshManualRules()

    def show(self):
        """only now compute content"""
        if self.game and not self.game.finished():
            self.slotInputChanged()
            QWidget.show(self)

    def penalty(self):
        """penalty button clicked"""
        dlg = PenaltyDialog(self.game)
        dlg.exec_()

    def slotLastTile(self):
        """called when the last tile changes"""
        newLastTile = self.computeLastTile()
        if not newLastTile:
            return
        prevLower, newLower = self.prevLastTile.islower(), newLastTile.islower()
        if prevLower != newLower:
            # state of last tile (concealed/exposed) changed:
            # for all checked boxes check if they still are applicable
            winner = self.game.winner
            if winner:
                for box in winner.manualRuleBoxes:
                    if box.isChecked():
                        box.setChecked(False)
                        if winner.hand.manualRuleMayApply(box.rule):
                            box.setChecked(True)
        self.prevLastTile = newLastTile
        self.fillLastMeldCombo()
        self.slotInputChanged()

    def computeLastTile(self):
        """returns the currently selected last tile"""
        idx = self.cbLastTile.currentIndex()
        if idx >= 0:
            return str(self.cbLastTile.itemData(idx).toString())

    def closeEvent(self, event):
        """the user pressed ALT-F4"""
        self.hide()
        event.ignore()
        self.scoringClosed.emit()

    def clickedPlayerIdx(self, checkbox):
        """the player whose box has been clicked"""
        for idx in range(4):
            if checkbox == self.wonBoxes[idx]:
                return idx
        assert False

    def wonChanged(self):
        """if a new winner has been defined, uncheck any previous winner"""
        newWinner = None
        if self.sender() != self.draw:
            clicked = self.clickedPlayerIdx(self.sender())
            if self.wonBoxes[clicked].isChecked():
                newWinner = self.game.players[clicked]
            else:
                newWinner = None
        self.game.winner = newWinner
        for idx in range(4):
            if newWinner != self.game.players[idx]:
                self.wonBoxes[idx].setChecked(False)
        if newWinner:
            self.draw.setChecked(False)
        self.fillLastTileCombo()
        self.slotInputChanged()

    def updateManualRules(self):
        """enable/disable them"""
        # if an exclusive rule has been activated, deactivate it for
        # all other players
        if isinstance(self.sender(), RuleBox):
            ruleBox = self.sender()
            if ruleBox.isChecked() and ruleBox.rule.exclusive():
                for idx, player in enumerate(self.game.players):
                    if ruleBox.parentWidget() != self.details[idx]:
                        for pBox in player.manualRuleBoxes:
                            if pBox.rule.name == ruleBox.rule.name:
                                pBox.setChecked(False)
        try:
            newState = bool(self.game.winner.handBoard.tiles)
        except AttributeError:
            newState = False
        self.lblLastTile.setEnabled(newState)
        self.cbLastTile.setEnabled(newState)
        self.lblLastMeld.setEnabled(newState)
        self.cbLastMeld.setEnabled(newState)
        if self.game:
            for player in self.game.players:
                player.refreshManualRules(self.sender())

    def clear(self):
        """prepare for next hand"""
        if self.game:
            for idx, player in enumerate(self.game.players):
                self.spValues[idx].clear()
                self.spValues[idx].setValue(0)
                self.wonBoxes[idx].setChecked(False)
                player.payment = 0
                player.invalidateHand()
        for box in self.wonBoxes:
            box.setVisible(False)
        self.draw.setChecked(False)
        self.updateManualRules()

        if self.game is None:
            self.hide()
        else:
            for idx, player in enumerate(self.game.players):
                self.windLabels[idx].setPixmap(WINDPIXMAPS[(player.wind,
                            player.wind == WINDS[self.game.roundsFinished % 4])])
            self.computeScores()
            self.spValues[0].setFocus()
            self.spValues[0].selectAll()

    def computeScores(self):
        """if tiles have been selected, compute their value"""
        # pylint: disable=R0912
        # too many branches
        if not self.game:
            return
        if self.game.finished():
            self.hide()
            return
        for idx, player in enumerate(self.game.players):
            self.spValues[idx].blockSignals(True) # we do not want that change to call computeScores again
            self.wonBoxes[idx].blockSignals(True) # we do not want that change to call computeScores again
            if player.handBoard and player.handBoard.tiles:
                self.spValues[idx].setEnabled(False)
                self.nameLabels[idx].setBuddy(self.wonBoxes[idx])
                for loop in range(10):
                    prevTotal = player.handTotal
                    handContent = player.computeHand(asWinner=True)
                    self.wonBoxes[idx].setVisible(handContent.won)
                    if not self.wonBoxes[idx].isVisibleTo(self) and self.wonBoxes[idx].isChecked():
                        self.wonBoxes[idx].setChecked(False)
                        self.game.winner = None
                    elif prevTotal == player.handTotal:
                        break
                    player.refreshManualRules()
                self.spValues[idx].setValue(player.handTotal)
            else:
                if not self.spValues[idx].isEnabled():
                    self.spValues[idx].clear()
                    self.spValues[idx].setValue(0)
                    self.spValues[idx].setEnabled(True)
                    self.nameLabels[idx].setBuddy(self.spValues[idx])
                self.wonBoxes[idx].setVisible(player.handTotal >= self.game.ruleset.minMJTotal())
                if not self.wonBoxes[idx].isVisibleTo(self) and self.wonBoxes[idx].isChecked():
                    self.wonBoxes[idx].setChecked(False)
            if not self.wonBoxes[idx].isVisibleTo(self) and player is self.game.winner:
                self.game.winner = None
            self.spValues[idx].blockSignals(False)
            self.wonBoxes[idx].blockSignals(False)
        if Internal.field.explainView:
            Internal.field.explainView.refresh(self.game)

    def __lastMeldContent(self):
        """prepare content for lastmeld combo"""
        lastTiles = set()
        winnerTiles = []
        if self.game.winner and self.game.winner.handBoard:
            winnerTiles = self.game.winner.handBoard.tiles
            pairs = []
            for meld in self.game.winner.hand.melds:
                if len(meld) < 4:
                    pairs.extend(meld.pairs)
            for tile in winnerTiles:
                if tile.element in pairs and not tile.isBonus():
                    lastTiles.add(tile.element)
        return lastTiles, winnerTiles

    def __fillLastTileComboWith(self, lastTiles, winnerTiles):
        """fill last meld combo with prepared content"""
        self.comboTilePairs = lastTiles
        idx = self.cbLastTile.currentIndex()
        if idx < 0:
            idx = 0
        indexedTile = str(self.cbLastTile.itemData(idx).toPyObject())
        restoredIdx = None
        self.cbLastTile.clear()
        if not winnerTiles:
            return
        pmSize = winnerTiles[0].board.tileset.faceSize
        pmSize = QSize(pmSize.width() * 0.5, pmSize.height() * 0.5)
        self.cbLastTile.setIconSize(pmSize)
        QPixmapCache.clear()
        self.__tilePixMaps = []
        shownTiles = set()
        for tile in winnerTiles:
            if tile.element in lastTiles and tile.element not in shownTiles:
                shownTiles.add(tile.element)
                self.cbLastTile.addItem(QIcon(tile.graphics.pixmapFromSvg(pmSize, withBorders=False)),
                        '', QVariant(tile.element))
                if indexedTile == tile.element:
                    restoredIdx = self.cbLastTile.count() - 1
        if not restoredIdx and indexedTile:
            # try again, maybe the tile changed between concealed and exposed
            indexedTile = indexedTile.lower()
            for idx in range(self.cbLastTile.count()):
                if indexedTile == str(self.cbLastTile.itemData(idx).toPyObject()).lower():
                    restoredIdx = idx
                    break
        if not restoredIdx:
            restoredIdx = 0
        self.cbLastTile.setCurrentIndex(restoredIdx)
        self.prevLastTile = self.computeLastTile()

    def clearLastTileCombo(self):
        """as the name says"""
        self.comboTilePairs = None
        self.cbLastTile.clear()

    def fillLastTileCombo(self):
        """fill the drop down list with all possible tiles.
        If the drop down had content before try to preserve the
        current index. Even if the tile changed state meanwhile."""
        if self.game is None:
            return
        lastTiles, winnerTiles = self.__lastMeldContent()
        if self.comboTilePairs == lastTiles:
            return
        self.cbLastTile.blockSignals(True) # we only want to emit the changed signal once
        try:
            self.__fillLastTileComboWith(lastTiles, winnerTiles)
        finally:
            self.cbLastTile.blockSignals(False)
            self.cbLastTile.currentIndexChanged.emit(0)

    def __fillLastMeldComboWith(self, winnerMelds, indexedMeld, lastTile):
        """fill last meld combo with prepared content"""
        winner = self.game.winner
        faceWidth = winner.handBoard.tileset.faceSize.width() * 0.5
        faceHeight = winner.handBoard.tileset.faceSize.height() * 0.5
        restoredIdx = None
        for meld in winnerMelds:
            pixMap = QPixmap(faceWidth * len(meld), faceHeight)
            pixMap.fill(Qt.transparent)
            self.__meldPixMaps.append(pixMap)
            painter = QPainter(pixMap)
            for element in meld.pairs:
                painter.drawPixmap(0, 0,
                    winner.handBoard.tilesByElement(element) \
                    [0].graphics.pixmapFromSvg(QSize(faceWidth, faceHeight), withBorders=False))
                painter.translate(QPointF(faceWidth, 0.0))
            self.cbLastMeld.addItem(QIcon(pixMap), '', QVariant(meld.joined))
            if indexedMeld == meld.joined:
                restoredIdx = self.cbLastMeld.count() - 1
        if not restoredIdx and indexedMeld:
            # try again, maybe the meld changed between concealed and exposed
            indexedMeld = indexedMeld.lower()
            for idx in range(self.cbLastMeld.count()):
                meldContent = str(self.cbLastMeld.itemData(idx).toPyObject())
                if indexedMeld == meldContent.lower():
                    restoredIdx = idx
                    if lastTile not in meldContent:
                        if lastTile.lower() == lastTile:
                            lastTile = lastTile.capitalize()
                        else:
                            lastTile = lastTile.lower()
                        assert lastTile in meldContent
                        self.cbLastTile.blockSignals(True) # we want to continue right here
                        idx = self.cbLastTile.findData(QVariant(lastTile))
                        self.cbLastTile.setCurrentIndex(idx)
                        self.cbLastTile.blockSignals(False)
                    break
        if not restoredIdx:
            restoredIdx = 0
        self.cbLastMeld.setCurrentIndex(restoredIdx)
        self.cbLastMeld.setIconSize(QSize(faceWidth * 3, faceHeight))

    def fillLastMeldCombo(self):
        """fill the drop down list with all possible melds.
        If the drop down had content before try to preserve the
        current index. Even if the meld changed state meanwhile."""
        self.cbLastMeld.blockSignals(True) # we only want to emit the changed signal once
        try:
            showCombo = False
            idx = self.cbLastMeld.currentIndex()
            if idx < 0:
                idx = 0
            indexedMeld = str(self.cbLastMeld.itemData(idx).toPyObject())
            self.cbLastMeld.clear()
            self.__meldPixMaps = []
            if not self.game.winner:
                return
            if self.cbLastTile.count() == 0:
                return
            lastTile = Internal.field.computeLastTile()
            winnerMelds = [m for m in self.game.winner.hand.melds if len(m) < 4 \
                and lastTile in m.pairs]
            assert len(winnerMelds)
            if len(winnerMelds) == 1:
                self.cbLastMeld.addItem(QIcon(), '', QVariant(winnerMelds[0].joined))
                self.cbLastMeld.setCurrentIndex(0)
                return
            showCombo = True
            self.__fillLastMeldComboWith(winnerMelds, indexedMeld, lastTile)
        finally:
            self.lblLastMeld.setVisible(showCombo)
            self.cbLastMeld.setVisible(showCombo)
            self.cbLastMeld.blockSignals(False)
            self.cbLastMeld.currentIndexChanged.emit(0)

    def slotInputChanged(self):
        """some input fields changed: update"""
        for player in self.game.players:
            player.invalidateHand()
        self.updateManualRules()
        self.computeScores()
        self.validate()

    def validate(self):
        """update the status of the OK button"""
        game = self.game
        if game:
            valid = True
            if game.winner and game.winner.handTotal < game.ruleset.minMJTotal():
                valid = False
            elif not game.winner and not self.draw.isChecked():
                valid = False
            self.btnSave.setEnabled(valid)
Example #16
0
class CaseInitializationConfigurationPanel(RowPanel):
    @may_take_a_long_time
    def __init__(self):
        RowPanel.__init__(self, "Case Management")
        self.setMinimumWidth(600)

        self.addCreateNewCaseTab()
        self.addInitializeFromScratchTab()
        self.addInitializeFromExistingTab()
        self.addShowCaseInfo()

        self.endTabs()

    def newValidatedKeywordPopup(self, existing_keywords):
        dialog = ValidatedDialog("New case", "Enter name of new case:",
                                 existing_keywords)
        return dialog.showAndTell()

    def addCreateNewCaseTab(self):
        self.startTabs("Create new case")

        case_list = KeywordList(CaseList(), "Available cases",
                                "init/case_list")
        case_list.setMaximumWidth(250)
        case_list.newKeywordPopup = self.newValidatedKeywordPopup
        case_list.setSelectable(False)

        self.addRow(case_list)

    def addInitializeFromScratchTab(self):
        self.addTab("Initialize from scratch")

        case_model = CaseSelectorModel()
        case_selector = ComboChoice(case_model, "Target case",
                                    "init/current_case_selection")
        self.addRow(case_selector)

        row_group = RowGroup()

        parameter_model = InitializationParametersModel()
        parameter_check_list = CheckList(parameter_model, "Parameters",
                                         "init/select_parameters")
        parameter_check_list.setMaximumWidth(300)
        row_group.addWidget(parameter_check_list)

        member_model = InitializationMembersModel()
        member_check_list = CheckList(member_model, "Members",
                                      "init/select_members")
        member_check_list.setMaximumWidth(150)
        row_group.addWidget(member_check_list)

        self.addRow(row_group)

        self.addSpace(10)

        initialize_from_scratch = InitializeFromScratchModel()
        self.addRow(
            Button(initialize_from_scratch,
                   help_link="init/initialize_from_scratch"))

        self.addSpace(10)

    def addInitializeFromExistingTab(self):
        self.addTab("Initialize from existing")

        case_model = CaseSelectorModel()
        target_case_selector = ComboChoice(case_model, "Target case",
                                           "init/current_case_selection")
        self.addRow(target_case_selector)

        initialized_cases = ComboChoice(InitializedCaseSelectorModel(),
                                        "Source case", "init/source_case")
        self.addRow(initialized_cases)

        #self.addRow("State", "Analyzed/Forecast")

        timestep_group = RowGroup("Timestep")
        history_length = HistoryLengthModel()
        history_length_spinner = IntegerSpinner(history_length, "Timestep",
                                                "config/init/history_length")
        timestep_group.addWidget(history_length_spinner)

        initial = QToolButton()
        initial.setText("Initial")
        initial.clicked.connect(history_length.setToMin)
        timestep_group.addWidget(initial)

        end_of_time = QToolButton()
        end_of_time.setText("End of time")
        end_of_time.clicked.connect(history_length.setToMax)
        timestep_group.addWidget(end_of_time)

        timestep_group.addGroupStretch()

        self.addRow(timestep_group)

        self.addSpace(10)

        row_group = RowGroup()
        parameter_model = InitializationParametersModel()
        parameter_check_list = CheckList(parameter_model, "Parameters",
                                         "init/select_parameters")
        parameter_check_list.setMaximumWidth(300)
        row_group.addWidget(parameter_check_list)

        member_model = InitializationMembersModel()
        member_check_list = CheckList(member_model, "Members",
                                      "init/select_members")
        member_check_list.setMaximumWidth(150)
        row_group.addWidget(member_check_list)

        self.addRow(row_group)

        self.addSpace(10)

        initialize_from_existing = InitializeFromExistingCaseModel()
        self.addRow(
            Button(initialize_from_existing,
                   help_link="init/initialize_from_existing"))

        self.addSpace(10)

    def addShowCaseInfo(self):
        self.addTab("Case Info")

        case_widget = HelpedWidget("Select case", "init/select_case_for_info")

        model = AllCasesModel()
        self.combo = QComboBox()
        self.combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
        self.combo.setMinimumContentsLength(20)
        self.combo.setModel(model)
        self.combo.currentIndexChanged.connect(self.showInfoForCase)

        case_widget.addWidget(self.combo)
        case_widget.addStretch()
        self.addRow(case_widget)

        area_widget = HelpedWidget("Case info", "init/selected_case_info")

        self.text_area = QTextEdit()
        self.text_area.setReadOnly(True)
        self.text_area.setMinimumHeight(300)

        area_widget.addWidget(self.text_area)
        area_widget.addStretch()
        self.addRow(area_widget)

        choice = CaseSelectorModel().getCurrentChoice()
        self.combo.setCurrentIndex(model.indexOf(choice))

    def showInfoForCase(self):
        case = self.combo.currentText()

        states = CaseList().getCaseRealizationStates(str(case))

        html = "<table>"
        for index in range(len(states)):
            html += "<tr><td width=30>%d.</td><td>%s</td></tr>" % (
                index, str(states[index]))

        html += "</table>"

        self.text_area.setHtml(html)