예제 #1
0
class FieldDelegate(QItemDelegate):
    """
    Use of a combo box in the table.
    """
    def __init__(self, parent, mdl):
        super(FieldDelegate, self).__init__(parent)
        self.parent = parent
        self.mdl = mdl

    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        self.modelCombo = ComboModel(editor, 1, 1)
        for fieldId in self.mdl.getFieldIdList(include_none=True):
            label = self.mdl.getLabel(fieldId, include_none=True)
            self.modelCombo.addItem(self.tr(label), label)

        editor.installEventFilter(self)
        return editor

    def setEditorData(self, comboBox, index):
        row = index.row()
        col = index.column()
        string = index.model().getData(index)[col]
        self.modelCombo.setItem(str_model=string)

    def setModelData(self, comboBox, model, index):
        txt = str(comboBox.currentText())
        value = self.modelCombo.dicoV2M[txt]
        log.debug("FieldDelegate value = %s" % value)

        selectionModel = self.parent.selectionModel()
        for idx in selectionModel.selectedIndexes():
            if idx.column() == index.column():
                model.setData(idx, value, Qt.DisplayRole)
예제 #2
0
class LocationDelegate(QItemDelegate):
    """
    Use of a combo box in the table.
    """
    def __init__(self, parent):
        super(LocationDelegate, self).__init__(parent)
        self.parent = parent

    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        self.modelCombo = ComboModel(editor, 4, 1)
        self.modelCombo.addItem(self.tr("cells"), "cells")
        self.modelCombo.addItem(self.tr("interior faces"), "internal")
        self.modelCombo.addItem(self.tr("boundary faces"), "boundary")
        self.modelCombo.addItem(self.tr("vertices"), "vertices")

        editor.installEventFilter(self)
        return editor

    def setEditorData(self, comboBox, index):
        row = index.row()
        col = index.column()
        string = index.model().getData(index)[col]
        self.modelCombo.setItem(str_model=string)

    def setModelData(self, comboBox, model, index):
        txt = str(comboBox.currentText())
        value = self.modelCombo.dicoV2M[txt]
        log.debug("LocationDelegate value = %s" % value)

        selectionModel = self.parent.selectionModel()
        for idx in selectionModel.selectedIndexes():
            if idx.column() == index.column():
                model.setData(idx, value, Qt.DisplayRole)
class CouplingDelegate(QItemDelegate):
    """
    Use of a combo box in the table.
    """
    def __init__(self, parent, mdl, dicoM2V, dicoV2M):
        super(CouplingDelegate, self).__init__(parent)
        self.parent = parent
        self.mdl = mdl
        self.dicoM2V = dicoM2V
        self.dicoV2M = dicoV2M

    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        self.modelCombo = ComboModel(editor, 1, 1)
        fieldId = index.row() + 1

        if self.mdl.getCriterion(fieldId) == "continuous":
            self.modelCombo.addItem(self.tr(self.dicoM2V["none"]), "none")
            self.modelCombo.disableItem(str_model="none")
        else:
            self.modelCombo.addItem(self.tr(self.dicoM2V["none"]), "none")
            carrier = self.mdl.getCarrierField(fieldId)
            if self.mdl.getTurbulenceModel(carrier) == "k-epsilon" or \
               self.mdl.getTurbulenceModel(carrier) == "k-epsilon_linear_production" or \
               self.mdl.getTurbulenceModel(carrier) == "rij-epsilon_ssg" or \
               self.mdl.getTurbulenceModel(carrier) == "rij-epsilon_ebrsm":
                if self.mdl.getFieldNature(fieldId) == "gas":
                    # bulles
                    self.modelCombo.addItem(
                        self.tr(self.dicoM2V["large_inclusions"]),
                        "large_inclusions")
                else:
                    # gouttes et solide
                    self.modelCombo.addItem(
                        self.tr(self.dicoM2V["small_inclusions"]),
                        "small_inclusions")

        editor.setMinimumSize(editor.sizeHint())
        editor.installEventFilter(self)
        return editor

    def setEditorData(self, comboBox, index):
        row = index.row()
        col = index.column()
        string = index.model().getData(index)[col]
        self.modelCombo.setItem(str_view=string)

    def setModelData(self, comboBox, model, index):
        txt = str(comboBox.currentText())
        value = self.modelCombo.dicoV2M[txt]
        log.debug("CouplingDelegate value = %s" % value)

        selectionModel = self.parent.selectionModel()
        for idx in selectionModel.selectedIndexes():
            if idx.column() == index.column():
                model.setData(idx, self.dicoM2V[value], Qt.DisplayRole)
class TurbFluxDelegate(QItemDelegate):
    """
    Use of a combobox in the table.
    """
    def __init__(self, parent, mdl, dicoM2V, dicoV2M):
        super(TurbFluxDelegate, self).__init__(parent)
        self.parent = parent
        self.mdl = mdl
        self.dicoM2V = dicoM2V
        self.dicoV2M = dicoV2M

    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        self.modelCombo = ComboModel(editor, 1, 1)
        fieldId = index.row() + 1

        if self.mdl.getEnergyResolution(fieldId) == 'on':
            if self.mdl.useAdvancedThermalFluxes(fieldId) == True:
                for turbFlux in TurbulenceModelsDescription.ThermalTurbFluxModels:
                    self.modelCombo.addItem(self.tr(self.dicoM2V[turbFlux]),
                                            turbFlux)

            else:
                turb_flux = TurbulenceModelsDescription.ThermalTurbFluxModels[
                    0]
                self.modelCombo.addItem(self.tr(self.dicoM2V[turbFlux]),
                                        turbFlux)
                self.modelCombo.disableItem(index=0)
        else:
            self.modelCombo.addItem(self.tr(self.dicoM2V['none']), 'none')
            self.modelCombo.setItem(str_view='none')

        editor.setMinimumSize(editor.sizeHint())
        editor.installEventFilter(self)
        return editor

    def setEditorData(self, comboBox, index):
        row = index.row()
        col = index.column()
        string = index.model().getData(index)[col]
        self.modelCombo.setItem(str_view=string)

    def setModelData(self, comboBox, model, index):
        txt = str(comboBox.currentText())
        value = self.modelCombo.dicoV2M[txt]
        log.debug("TurbFluxDelegate value = %s" % value)

        selectionModel = self.parent.selectionModel()
        for idx in selectionModel.selectedIndexes():
            if idx.column() == index.column():
                model.setData(idx, self.dicoM2V[value], Qt.DisplayRole)
class TurbulenceDelegate(QItemDelegate):
    """
    Use of a combo box in the table.
    """
    def __init__(self, parent, mdl, dicoM2V, dicoV2M):
        super(TurbulenceDelegate, self).__init__(parent)
        self.parent = parent
        self.mdl = mdl
        self.dicoM2V = dicoM2V
        self.dicoV2M = dicoV2M

    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        self.modelCombo = ComboModel(editor, 1, 1)
        fieldId = index.row() + 1

        if self.mdl.getCriterion(fieldId) == "continuous":
            turbulence_models = TurbulenceModelsDescription.continuousTurbulenceModels
        else:
            carrier = self.mdl.getCarrierField(fieldId)
            if self.mdl.getPredefinedFlow() == "boiling_flow":
                turbulence_models = TurbulenceModelsDescription.bubblyFlowsTurbulenceModels
            elif self.mdl.getPredefinedFlow() == "droplet_flow":
                turbulence_models = TurbulenceModelsDescription.dropletFlowsTurbulenceModels
            elif self.mdl.getTurbulenceModel(carrier) != "none" or \
                    self.mdl.getFieldNature(fieldId) == "solid":
                turbulence_models = TurbulenceModelsDescription.dispersedTurbulenceModels
            else:
                turbulence_models = ["none"]
        for turb in turbulence_models:
            self.modelCombo.addItem(self.tr(self.dicoM2V[turb]), turb)
        editor.setMinimumSize(editor.sizeHint())
        editor.installEventFilter(self)
        return editor

    def setEditorData(self, comboBox, index):
        row = index.row()
        col = index.column()
        string = index.model().getData(index)[col]
        self.modelCombo.setItem(str_view=string)

    def setModelData(self, comboBox, model, index):
        txt = str(comboBox.currentText())
        value = self.modelCombo.dicoV2M[txt]
        log.debug("TurbulenceDelegate value = %s" % value)

        selectionModel = self.parent.selectionModel()
        for idx in selectionModel.selectedIndexes():
            if idx.column() == index.column():
                model.setData(idx, self.dicoM2V[value], Qt.DisplayRole)
class SolverDelegate(QItemDelegate):
    """
    Use of a combo box in the table.
    """
    def __init__(self, parent, dicoM2V, dicoV2M):
        super(SolverDelegate, self).__init__(parent)
        self.parent   = parent
        self.dicoM2V  = dicoM2V
        self.dicoV2M  = dicoV2M


    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        self.modelCombo = ComboModel(editor, 12, 1)
        self.modelCombo.addItem(self.tr(self.dicoM2V["automatic"]), 'automatic')
        self.modelCombo.addItem(self.tr(self.dicoM2V["jacobi"]), 'jacobi')
        self.modelCombo.addItem(self.tr(self.dicoM2V["pcg"]), 'pcg')
        self.modelCombo.addItem(self.tr(self.dicoM2V["cgstab"]), 'cgstab')
        self.modelCombo.addItem(self.tr(self.dicoM2V["jacobi_saturne"]), 'jacobi_saturne')
        self.modelCombo.addItem(self.tr(self.dicoM2V["pcg_saturne"]), 'pcg_saturne')
        self.modelCombo.addItem(self.tr(self.dicoM2V["bicgstab_saturne"]), 'bicgstab_saturne')
        self.modelCombo.addItem(self.tr(self.dicoM2V["bicgstab2_saturne"]), 'bicgstab2_saturne')
        self.modelCombo.addItem(self.tr(self.dicoM2V["gmres_saturne"]), 'gmres_saturne')
        self.modelCombo.addItem(self.tr(self.dicoM2V["gauss_seidel_saturne"]), 'gauss_seidel_saturne')
        self.modelCombo.addItem(self.tr(self.dicoM2V["sym_gauss_seidel_saturne"]), 'sym_gauss_seidel_saturne')
        self.modelCombo.addItem(self.tr(self.dicoM2V["pcr3_saturne"]), 'pcr3_saturne')

        editor.installEventFilter(self)
        return editor


    def setEditorData(self, comboBox, index):
        row = index.row()
        col = index.column()
        string = index.model().getData(index)[col]
        self.modelCombo.setItem(str_view=string)


    def setModelData(self, comboBox, model, index):
        txt = str(comboBox.currentText())
        value = self.modelCombo.dicoV2M[txt]
        log.debug("SolverDelegate value = %s"%value)

        selectionModel = self.parent.selectionModel()
        for idx in selectionModel.selectedIndexes():
            if idx.column() == index.column():
                model.setData(idx, self.dicoM2V[value], Qt.DisplayRole)
예제 #7
0
class EnthalpyDelegate(QItemDelegate):
    """
    Use of a combo box in the table.
    """
    def __init__(self, parent, mdl):
        super(EnthalpyDelegate, self).__init__(parent)
        self.parent   = parent
        self.mdl      = mdl


    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        predefined_flow = self.mdl.getPredefinedFlow()
        if predefined_flow in ["free_surface", "boiling_flow", "droplet_flow", "multiregime"]:
            self.modelCombo = ComboModel(editor, 2, 1)
            self.modelCombo.addItem(self.tr("off"), 'off')
            self.modelCombo.addItem(self.tr("total enthalpy"), 'total_enthalpy')
        else:
            self.modelCombo = ComboModel(editor, 3, 1)
            self.modelCombo.addItem(self.tr("off"), 'off')
            self.modelCombo.addItem(self.tr("total enthalpy"), 'total_enthalpy')
            self.modelCombo.addItem(self.tr("specific enthalpy"), 'specific_enthalpy')

        editor.installEventFilter(self)
        return editor


    def setEditorData(self, comboBox, index):
        col = index.column()
        string = index.model().getData(index)[col]
        self.modelCombo.setItem(str_model=string)


    def setModelData(self, comboBox, model, index):
        txt = str(comboBox.currentText())
        value = self.modelCombo.dicoV2M[txt]
        log.debug("EnthalpyDelegate value = %s"%value)

        selectionModel = self.parent.selectionModel()
        for idx in selectionModel.selectedIndexes():
            if idx.column() == index.column():
                model.setData(idx, value, Qt.DisplayRole)
예제 #8
0
class CriterionDelegate(QItemDelegate):
    """
    Use of a combo box in the table.
    """
    def __init__(self, parent):
        super(CriterionDelegate, self).__init__(parent)
        self.parent   = parent


    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        self.modelCombo = ComboModel(editor, 3, 1)
        self.modelCombo.addItem(self.tr("continuous"), 'continuous')
        self.modelCombo.addItem(self.tr("dispersed"), 'dispersed')
        self.modelCombo.addItem(self.tr("auto"), 'auto')
        # TODO to delete if/when the auto option is implemented
        self.modelCombo.disableItem(2)
        # fixed to continuous for field 1
        if index.row() == 0 :
            editor.setEnabled(False)

        editor.installEventFilter(self)
        return editor


    def setEditorData(self, comboBox, index):
        row = index.row()
        col = index.column()
        string = index.model().getData(index)[col]
        self.modelCombo.setItem(str_model=string)


    def setModelData(self, comboBox, model, index):
        txt = str(comboBox.currentText())
        value = self.modelCombo.dicoV2M[txt]
        log.debug("CriterionDelegate value = %s"%value)

        selectionModel = self.parent.selectionModel()
        for idx in selectionModel.selectedIndexes():
            if idx.column() == index.column():
                model.setData(idx, value, Qt.DisplayRole)
예제 #9
0
class NatureDelegate(QItemDelegate):
    """
    Use of a combo box in the table.
    """
    def __init__(self, parent):
        super(NatureDelegate, self).__init__(parent)
        self.parent   = parent


    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        self.modelCombo = ComboModel(editor, 3, 1)
        self.modelCombo.addItem(self.tr("liquid"), 'liquid')
        self.modelCombo.addItem(self.tr("gas"), 'gas')
        self.modelCombo.addItem(self.tr("solid"), 'solid')

        row = index.row()
        if (row == 0) :
            self.modelCombo.disableItem(2)
        else :
            self.modelCombo.enableItem(2)

        editor.installEventFilter(self)
        return editor


    def setEditorData(self, comboBox, index):
        col = index.column()
        string = index.model().getData(index)[col]
        self.modelCombo.setItem(str_model=string)


    def setModelData(self, comboBox, model, index):
        txt = str(comboBox.currentText())
        value = self.modelCombo.dicoV2M[txt]
        log.debug("NatureDelegate value = %s"%value)

        selectionModel = self.parent.selectionModel()
        for idx in selectionModel.selectedIndexes():
            if idx.column() == index.column():
                model.setData(idx, value, Qt.DisplayRole)
class SchemeDelegate(QItemDelegate):
    """
    Use of a combo box in the table.
    """
    def __init__(self, parent, dicoM2V, dicoV2M):
        super(SchemeDelegate, self).__init__(parent)
        self.parent   = parent
        self.dicoM2V  = dicoM2V
        self.dicoV2M  = dicoV2M


    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        self.modelCombo = ComboModel(editor, 3, 1)
        self.modelCombo.addItem(self.tr(self.dicoM2V["centered"]), 'centered')
        self.modelCombo.addItem(self.tr(self.dicoM2V["upwind"]), 'upwind')
        self.modelCombo.addItem(self.tr(self.dicoM2V["solu"]), 'solu')

        editor.installEventFilter(self)
        return editor


    def setEditorData(self, comboBox, index):
        row = index.row()
        col = index.column()
        string = index.model().getData(index)[col]
        self.modelCombo.setItem(str_view=string)


    def setModelData(self, comboBox, model, index):
        txt = str(comboBox.currentText())
        value = self.modelCombo.dicoV2M[txt]
        log.debug("SchemeDelegate value = %s"%value)

        selectionModel = self.parent.selectionModel()
        for idx in selectionModel.selectedIndexes():
            if idx.column() == index.column():
                model.setData(idx, self.dicoM2V[value], Qt.DisplayRole)
예제 #11
0
class UserDimensionDelegate(QItemDelegate):
    """
    Use of a combo box in the table for the user array dimension.
    """
    def __init__(self, parent):
        super(UserDimensionDelegate, self).__init__(parent)
        self.parent = parent

    def createEditor(self, parent, option, index):
        editor = QComboBox(parent)
        self.modelCombo = ComboModel(editor, 5, 1)

        self.modelCombo.addItem(self.tr("1"), "1")
        self.modelCombo.addItem(self.tr("2"), "2")
        self.modelCombo.addItem(self.tr("3"), "3")
        self.modelCombo.addItem(self.tr("6"), "6")
        self.modelCombo.addItem(self.tr("9"), "9")

        editor.installEventFilter(self)
        return editor

    def setEditorData(self, comboBox, index):
        row = index.row()
        col = index.column()
        string = index.model().getData(index)[col]
        self.modelCombo.setItem(str_model=string)

    def setModelData(self, comboBox, model, index):
        txt = str(comboBox.currentText())
        value = self.modelCombo.dicoV2M[txt]
        log.debug("UserDimensionDelegate value = %s" % value)

        selectionModel = self.parent.selectionModel()
        for idx in selectionModel.selectedIndexes():
            if idx.column() == index.column():
                model.setData(idx, value, Qt.DisplayRole)
예제 #12
0
class BoundaryConditionsCompressibleOutletView(
        QWidget, Ui_BoundaryConditionsCompressibleOutletForm):
    def __init__(self, parent):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_BoundaryConditionsCompressibleOutletForm.__init__(self)
        self.setupUi(self)

    def setup(self, case):
        """
        Setup the widget
        """
        self.case = case
        self.__boundary = None

        self.case.undoStopGlobal()

        self.mdl = CompressibleModel(self.case)

        # Connections
        self.comboBoxTypeOutlet.activated[str].connect(self.slotOutletType)
        self.lineEditPressure.textChanged[str].connect(self.slotPressureValue)

        # Combo models
        self.modelTypeOutlet = ComboModel(self.comboBoxTypeOutlet, 2, 1)
        self.modelTypeOutlet.addItem(self.tr("supersonic outlet"),
                                     'supersonic_outlet')
        self.modelTypeOutlet.addItem(self.tr("subsonic outlet"),
                                     'subsonic_outlet')

        # Validators
        validatorP = DoubleValidator(self.lineEditPressure, min=0.0)

        # Apply validators
        self.lineEditPressure.setValidator(validatorP)

        self.case.undoStartGlobal()

    def showWidget(self, boundary):
        """
        Show the widget
        """
        label = boundary.getLabel()
        self.__boundary = Boundary('compressible_outlet', label, self.case)
        self.initialize()

    def initialize(self):

        # Initialize thermodynamic value

        outlet_type = self.__boundary.getOutletType()
        self.modelTypeOutlet.setItem(str_model=outlet_type)
        self.__boundary.setOutletType(outlet_type)
        if outlet_type == 'supersonic_outlet':
            self.frameDensity.hide()
        else:
            self.frameDensity.show()
            pressure = self.__boundary.getPressureValue()
            self.lineEditPressure.setText(str(pressure))

        self.show()

    def hideWidget(self):
        """
        Hide all
        """
        self.hide()

    @pyqtSlot(str)
    def slotOutletType(self, text):
        """
        INPUT outlet type
        """
        value = self.modelTypeOutlet.dicoV2M[str(text)]
        log.debug("__slotOutletType value = %s " % value)

        self.__boundary.setOutletType(value)
        self.initialize()

    @pyqtSlot(str)
    def slotPressureValue(self, text):
        """
        INPUT outlet pressure
        """
        if self.sender().validator().state == QValidator.Acceptable:
            t = from_qvariant(text, float)
            self.__boundary.setPressureValue(t)

    def getCompressibleModel(self):
        """
        Return the compressible model
        """
        model = self.mdl.getCompressibleModel()
        return model
class LagrangianBoundaryView(QWidget, Ui_LagrangianBoundaryForm):
    """
    """
    def __init__(self, parent):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_LagrangianBoundaryForm.__init__(self)
        self.setupUi(self)

    def setup(self, case):

        self.case = case
        self.case.undoStopGlobal()
        self.model = LagrangianBoundariesModel(self.case)
        self.zone = None
        self.dicoM2V = {}
        self.dicoV2M = {}

        self._setConnections()
        self._setValidators()

        self.case.undoStartGlobal()

    def _setValidators(self):
        validatorIJNBP = IntValidator(self.lineEditIJNBP, min=0)
        validatorIJFRE = IntValidator(self.lineEditIJFRE, min=0)
        validatorICLST = IntValidator(self.lineEditICLST, min=0)
        validatorIDEBT = DoubleValidator(self.lineEditIDEBT, min=0.)
        validatorIPOIT = DoubleValidator(self.lineEditIPOIT, min=0.)
        validatorIPOIT.setExclusiveMin(True)
        validatorIROPT = DoubleValidator(self.lineEditIROPT, min=0.)
        validatorIROPT.setExclusiveMin(True)
        validatorIRCOLM = DoubleValidator(self.lineEditIRCOLM, min=0.)
        validatorIUNO = DoubleValidator(self.lineEditIUNO)
        validatorIUPT = DoubleValidator(self.lineEditIUPT)
        validatorIVPT = DoubleValidator(self.lineEditIVPT)
        validatorIWPT = DoubleValidator(self.lineEditIWPT)
        validatorITPT = DoubleValidator(self.lineEditITPT)
        validatorICPT = DoubleValidator(self.lineEditICPT)
        validatorIEPSI = DoubleValidator(self.lineEditIEPSI)
        validatorIDPT = DoubleValidator(self.lineEditIDPT, min=0.)
        validatorIVDPT = DoubleValidator(self.lineEditIVDPT)
        validatorINUCHL = IntValidator(self.lineEditINUCHL, min=0)
        validatorIHPT = DoubleValidator(self.lineEditIHPT)
        self.lineEditIJNBP.setValidator(validatorIJNBP)
        self.lineEditIJFRE.setValidator(validatorIJFRE)
        self.lineEditICLST.setValidator(validatorICLST)
        self.lineEditIDEBT.setValidator(validatorIDEBT)
        self.lineEditIPOIT.setValidator(validatorIPOIT)
        self.lineEditIROPT.setValidator(validatorIROPT)
        self.lineEditIRCOLM.setValidator(validatorIRCOLM)
        self.lineEditIUNO.setValidator(validatorIUNO)
        self.lineEditIUPT.setValidator(validatorIUPT)
        self.lineEditIVPT.setValidator(validatorIVPT)
        self.lineEditIWPT.setValidator(validatorIWPT)
        self.lineEditITPT.setValidator(validatorITPT)
        self.lineEditICPT.setValidator(validatorICPT)
        self.lineEditIEPSI.setValidator(validatorIEPSI)
        self.lineEditIDPT.setValidator(validatorIDPT)
        self.lineEditIVDPT.setValidator(validatorIVDPT)
        self.lineEditINUCHL.setValidator(validatorINUCHL)
        self.lineEditIHPT.setValidator(validatorIHPT)

    def _setConnections(self):
        self.comboBoxBoundary.activated[str].connect(
            self.slotSetParticleBoundary)
        self.lineEditNbSets.editingFinished.connect(self.slotNbSets)
        self.spinBoxICLAS.valueChanged[int].connect(self.slotICLAS)
        self.lineEditIJNBP.textChanged[str].connect(self.slotIJNBP)
        self.lineEditIJFRE.textChanged[str].connect(self.slotIJFRE)
        self.lineEditICLST.textChanged[str].connect(self.slotICLST)
        self.lineEditIDEBT.textChanged[str].connect(self.slotIDEBT)
        self.comboBoxIPOIT.activated[str].connect(self.slotIPOITChoice)
        self.lineEditIPOIT.textChanged[str].connect(self.slotIPOIT)
        self.lineEditIROPT.textChanged[str].connect(self.slotIROPT)
        self.lineEditIRCOLM.textChanged[str].connect(self.slotIRCOLM)
        self.comboBoxIJUVW.activated[str].connect(self.slotIJUVW)
        self.lineEditIUNO.textChanged[str].connect(self.slotIUNO)
        self.lineEditIUPT.textChanged[str].connect(self.slotIUPT)
        self.lineEditIVPT.textChanged[str].connect(self.slotIVPT)
        self.lineEditIWPT.textChanged[str].connect(self.slotIWPT)
        self.comboBoxIJRTP.activated[str].connect(self.slotIJRTP)
        self.lineEditITPT.textChanged[str].connect(self.slotITPT)
        self.lineEditICPT.textChanged[str].connect(self.slotICPT)
        self.lineEditIEPSI.textChanged[str].connect(self.slotIEPSI)
        self.lineEditIDPT.textChanged[str].connect(self.slotIDPT)
        self.lineEditIVDPT.textChanged[str].connect(self.slotIVDPT)
        self.lineEditINUCHL.textChanged[str].connect(self.slotINUCHL)
        self.lineEditIHPT.textChanged[str].connect(self.slotIHPT)

    def showWidget(self, zone):
        self.zone = zone
        self.show()
        self._hideSubWidgets()
        self._defineV2MDictionary()
        self._fillComboBoxes()
        self._loadCase()

    def _hideSubWidgets(self):
        self.groupBoxNbSets.hide()
        self.groupBoxSetNumber.hide()
        self.groupBoxMain.hide()
        self.groupBoxRate.hide()
        self.groupBoxVelocity.hide()
        self.groupBoxTemperature.hide()
        self.groupBoxDiameter.hide()
        self.groupBoxCoal.hide()

    def _defineV2MDictionary(self):
        if self.model.getFoulingStatus() == "on":
            self.dicoM2V = {
                "wall": {
                    "inlet": self.tr("Particles inlet"),
                    "bounce": self.tr("Particles rebound"),
                    "deposit1": self.tr("Deposition and elimination"),
                    "deposit2": self.tr("Deposition"),
                    "fouling": self.tr("Fouling")
                },
                "inlet": {
                    "inlet": self.tr("Particles inlet"),
                    "bounce": self.tr("Particles rebound"),
                    "outlet": self.tr("Particles outlet")
                },
                "outlet": {
                    "outlet": self.tr("Particles outlet")
                },
                "free_inlet_outlet": {
                    "inlet": self.tr("Particles inlet"),
                    "outlet": self.tr("Particles outlet")
                },
                "imposed_p_outlet": {
                    "outlet": self.tr("Particles outlet")
                },
                "symmetry": {
                    "part_symmetry": self.tr("Particles symmetry"),
                    "bounce": self.tr("Particles rebound")
                }
            }[self.zone.getNature()]
        else:
            self.dicoM2V = {
                "wall": {
                    "inlet": self.tr("Particles inlet"),
                    "bounce": self.tr("Particles rebound"),
                    "deposit1": self.tr("Deposition and elimination"),
                    "deposit2": self.tr("Deposition")
                },
                "inlet": {
                    "inlet": self.tr("Particles inlet"),
                    "bounce": self.tr("Particles rebound"),
                    "outlet": self.tr("Particles outlet")
                },
                "outlet": {
                    "outlet": self.tr("Particles outlet")
                },
                "free_inlet_outlet": {
                    "inlet": self.tr("Particles inlet"),
                    "outlet": self.tr("Particles outlet")
                },
                "imposed_p_outlet": {
                    "outlet": self.tr("Particles outlet")
                },
                "symmetry": {
                    "part_symmetry": self.tr("Particles symmetry"),
                    "bounce": self.tr("Particles rebound")
                }
            }[self.zone.getNature()]
        self.dicoV2M = {}
        for k, v in self.dicoM2V.items():
            self.dicoV2M[v] = k

    def _fillComboBoxes(self):
        self.modelParticleBoundary = ComboModel(self.comboBoxBoundary, 1, 1)
        for key, value in self.dicoM2V.items():
            self.modelParticleBoundary.addItem(value, key)
        self.modelIPOIT = ComboModel(self.comboBoxIPOIT, 2, 1)
        self.modelIPOIT.addItem(self.tr("Mass flow rate"), "rate")
        self.modelIPOIT.addItem(self.tr("Statistical weight set by values"),
                                "prescribed")
        self.modelIJUVW = ComboModel(self.comboBoxIJUVW, 3, 1)
        self.modelIJUVW.addItem(self.tr("Fluid velocity"), "fluid")
        self.modelIJUVW.addItem(self.tr("Normal direction velocity"), "norm")
        self.modelIJUVW.addItem(self.tr("Velocity given by values"),
                                "components")
        self.modelIJRTP = ComboModel(self.comboBoxIJRTP, 2, 1)
        self.modelIJRTP.addItem(self.tr("Fluid temperature"), "fluid")
        self.modelIJRTP.addItem(self.tr("Temperature set by values"),
                                "prescribed")

    def _loadCase(self):
        nature = self.zone.getNature()
        label = self.zone.getLabel()
        self.model.setCurrentBoundaryNode(nature, label)
        interaction = self.model.getBoundaryChoice(nature, label)
        if interaction not in self.dicoM2V.keys():
            print("error: BC '" + label + "' (" + nature + ") type '" +
                  interaction + "' requested\n"
                  "       but model is not active: set to rebound")
            interaction = 'bounce'
            self.model.setBoundaryChoice(nature, label, interaction)
        self.modelParticleBoundary.setItem(str_model=interaction)
        self.slotSetParticleBoundary(
            self.dicoM2V[interaction]
        )  # this is needed because setItem does not trigger comboBox activation
        if interaction == "inlet":
            nb_sets = self.model.getNumberOfSetsValue()
            self.updateInletDisplay(nb_sets)

    def hideWidget(self):
        self.hide()

    def updateInletDisplay(self, nb_sets):
        self.lineEditNbSets.setText(str(nb_sets))
        if int(nb_sets) > 0:
            self.groupBoxSetNumber.show()
            self.spinBoxICLAS.setMinimum(1)
            self.spinBoxICLAS.setMaximum(nb_sets)
            self.spinBoxICLAS.setValue(1)
            self.slotICLAS(1)
        else:
            self.groupBoxSetNumber.hide()
            self.groupBoxMain.hide()
            self.groupBoxRate.hide()
            self.groupBoxVelocity.hide()
            self.groupBoxTemperature.hide()
            self.groupBoxDiameter.hide()
            self.groupBoxCoal.hide()

    @pyqtSlot()
    def slotNbSets(self):
        nb_sets = from_qvariant(self.lineEditNbSets.text(), to_text_string)
        try:
            nb_sets = int(nb_sets)
        except Exception:
            nb_sets = self.model.getNumberOfSetsValue()
            self.lineEditNbSets.setText(str(nb_sets))
            return
        self.model.setNumberOfSetsValue(nb_sets)
        self.updateInletDisplay(nb_sets)

        return

    @pyqtSlot(str)
    def slotSetParticleBoundary(self, interaction):
        interaction = self.dicoV2M[interaction]
        self.model.setBoundaryChoice(self.zone.getNature(),
                                     self.zone.getLabel(), interaction)
        if interaction == "inlet":
            self.groupBoxNbSets.show()
        else:
            self.lineEditNbSets.setText("0")
            self.groupBoxNbSets.hide()

    @pyqtSlot(int)
    def slotICLAS(self, iset):
        """
        Input ICLAS.
        """
        self.iset = iset
        label = self.zone.getLabel()
        interaction = self.dicoV2M[str(self.comboBoxBoundary.currentText())]
        if interaction == "inlet":
            self.model.setCurrentSetNode(iset)

        # Main variables
        self.groupBoxMain.show()
        npart = self.model.getNumberOfParticulesInSetValue(label, self.iset)
        self.lineEditIJNBP.setText(str(npart))
        freq = self.model.getInjectionFrequencyValue(label, self.iset)
        self.lineEditIJFRE.setText(str(freq))

        lagStatisticsModel = LagrangianStatisticsModel(self.case)
        if lagStatisticsModel.getGroupOfParticlesValue() > 0:
            igroup = self.model.getParticleGroupNumberValue(label, self.iset)
            self.lineEditICLST.setText(str(igroup))
            self.labelICLST.show()
            self.lineEditICLST.show()
        else:
            self.labelICLST.hide()
            self.lineEditICLST.hide()

        # Rate / stat. weight
        self.groupBoxRate.show()
        choice = self.model.getStatisticalWeightChoice(label, self.iset)
        self.modelIPOIT.setItem(str_model=choice)
        text = self.modelIPOIT.dicoM2V[choice]
        self.slotIPOITChoice(text)

        # Velocity
        self.groupBoxVelocity.show()
        choice = self.model.getVelocityChoice(label, self.iset)
        self.modelIJUVW.setItem(str_model=choice)
        text = self.modelIJUVW.dicoM2V[choice]
        self.slotIJUVW(text)

        # Fouling
        colm = self.model.getFoulingIndexValue(label, self.iset)
        self.lineEditIRCOLM.setText(str(colm))

        # Temperature
        lagModel = LagrangianModel(self.case)
        part_model = lagModel.getParticlesModel()
        status = lagModel.getHeating()
        if part_model == "thermal" and status == "on":
            self.groupBoxTemperature.show()
            choice = self.model.getTemperatureChoice(label, self.iset)
            self.modelIJRTP.setItem(str_model=choice)
            text = self.modelIJRTP.dicoM2V[choice]
            self.slotIJRTP(text)

            cp = self.model.getSpecificHeatValue(label, self.iset)
            self.lineEditICPT.setText(str(cp))
            eps = self.model.getEmissivityValue(label, self.iset)
            self.lineEditIEPSI.setText(str(eps))

        # Coals
        if CoalCombustionModel(
                self.case).getCoalCombustionModel("only") != 'off':
            self.groupBoxCoal.show()
            icoal = self.model.getCoalNumberValue(label, self.iset)
            self.lineEditINUCHL.setText(str(icoal))
            temp = self.model.getCoalTemperatureValue(label, self.iset)
            self.lineEditIHPT.setText(str(temp))

        # Diameter
        self.groupBoxDiameter.show()

        diam = self.model.getDiameterValue(label, self.iset)
        vdiam = self.model.getDiameterVarianceValue(label, self.iset)
        self.lineEditIDPT.setText(str(diam))
        self.lineEditIVDPT.setText(str(vdiam))

        # Coal
        if CoalCombustionModel(
                self.case).getCoalCombustionModel("only") != 'off':
            self.labelIROPT.hide()
            self.labelUnitIROPT.hide()
            self.lineEditIROPT.hide()
예제 #14
0
class BoundaryConditionsMobileMeshView(QWidget,
                                       Ui_BoundaryConditionsMobileMeshForm):
    """
    Boundary condifition for mobil mesh (ALE and/or Fluid-interaction)
    """
    def __init__(self, parent):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_BoundaryConditionsMobileMeshForm.__init__(self)
        self.setupUi(self)

    def setup(self, case):
        """
        Setup the widget
        """
        self.case = case
        self.__boundary = None

        self.case.undoStopGlobal()

        self.__model = MobileMeshModel(self.case)
        self.notebook = NotebookModel(self.case)

        self.__comboModel = ComboModel(self.comboMobilBoundary, 6, 1)
        self.__comboModel.addItem(self.tr("Fixed boundary"), "fixed_boundary")
        self.__comboModel.addItem(self.tr("Sliding boundary"),
                                  "sliding_boundary")
        self.__comboModel.addItem(self.tr("Internal coupling"),
                                  "internal_coupling")
        self.__comboModel.addItem(self.tr("External coupling"),
                                  "external_coupling")
        self.__comboModel.addItem(self.tr("Fixed velocity"), "fixed_velocity")
        self.__comboModel.addItem(self.tr("Fixed displacement"),
                                  "fixed_displacement")

        self.comboMobilBoundary.activated[str].connect(self.__slotCombo)
        self.pushButtonMobilBoundary.clicked.connect(self.__slotFormula)

        self.case.undoStartGlobal()

    @pyqtSlot()
    def __slotFormula(self):
        """
        Run formula editor.
        """
        exp = self.__boundary.getALEFormula()
        c = self.__boundary.getALEChoice()

        if c == "fixed_velocity":
            if not exp:
                exp = 'mesh_velocity[0] = 0.;\nmesh_velocity[1] = 0.;\nmesh_velocity[2] = 0.;'
            req = [('mesh_velocity[0]', 'Fixed velocity of the mesh'),
                   ('mesh_velocity[1]', 'Fixed velocity of the mesh'),
                   ('mesh_velocity[2]', 'Fixed velocity of the mesh')]
            exa = 'mesh_velocity[0] = 0.;\nmesh_velocity[1] = 0.;\nmesh_velocity[2] = 1.;'
        elif c == "fixed_displacement":
            if not exp:
                exp = 'mesh_displacement[0] = 0.;\nmesh_displacement[1] = 0.;\nmesh_displacement[2] = 0.;'
            req = [('mesh_displacement[0]', 'Fixed displacement of the mesh'),
                   ('mesh_displacement[1]', 'Fixed displacement of the mesh'),
                   ('mesh_displacement[2]', 'Fixed displacement of the mesh')]
            exa = 'mesh_displacement[0] = 0.;\nmesh_displacement[1] = 0.;\nmesh_displacement[2] = 1.;'

        sym = [('x', "X face's gravity center"),
               ('y', "Y face's gravity center"),
               ('z', "Z face's gravity center"), ('dt', 'time step'),
               ('t', 'current time'), ('iter', 'number of iteration'),
               ('surface', 'Boundary zone surface')]

        for (nme, val) in self.notebook.getNotebookList():
            sym.append((nme, 'value (notebook) = ' + str(val)))

        dialog = QMegEditorView(parent=self,
                                function_type='bnd',
                                zone_name=self.__boundary._label,
                                variable_name='mesh_velocity',
                                expression=exp,
                                required=req,
                                symbols=sym,
                                condition=c,
                                examples=exa)

        if dialog.exec_():
            result = dialog.get_result()
            log.debug("slotFormulaMobileMeshBoundary -> %s" % str(result))
            self.__boundary.setFormula(str(result))
            self.pushButtonMobilBoundary.setStyleSheet(
                "background-color: green")
            self.pushButtonMobilBoundary.setToolTip(result)

    @pyqtSlot(str)
    def __slotCombo(self, text):
        """
        Called when the combobox changed.
        """
        modelData = self.__comboModel.dicoV2M[str(text)]

        if modelData == self.__boundary.getALEChoice():
            return

        self.__boundary.setALEChoice(modelData)
        exp = self.__boundary.getALEFormula()

        # Hide/Show formula button.
        # Formula is always reset when changing values, so set
        # color to red.
        if modelData in ["fixed_velocity", "fixed_displacement"]:
            self.pushButtonMobilBoundary.show()
        else:
            self.pushButtonMobilBoundary.hide()
        if exp:
            self.pushButtonMobilBoundary.setStyleSheet("background-color: red")
            self.pushButtonMobilBoundary.setToolTip(exp)
        else:
            self.pushButtonMobilBoundary.setStyleSheet("background-color: red")

    def showWidget(self, b):
        """
        Show the widget
        """
        if self.__model.getMethod() != "off":
            self.__boundary = b
            modelData = b.getALEChoice()
            self.__comboModel.setItem(str_model=modelData)
            if modelData in ["fixed_velocity", "fixed_displacement"]:
                self.pushButtonMobilBoundary.show()
            else:
                self.pushButtonMobilBoundary.hide()
            self.show()
        else:
            self.hideWidget()

    def hideWidget(self):
        """
        Hide all
        """
        self.hide()
class DropletCondensationEvaporationView(QWidget,
                                         Ui_DropletCondensationEvaporation):
    """
    Droplet Condensation-Evaporation model layout.
    """
    def __init__(self, parent):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_DropletCondensationEvaporation.__init__(self)
        self.setupUi(self)

    def setup(self, case):
        self.case = case
        self.case.undoStopGlobal()
        self.mdl = DropletCondensationEvaporationModel(self.case)

        self.modelYPlus = ComboModel(self.comboBoxYPlus, 3, 1)
        self.modelYPlus.addItem(self.tr("Boundary cell center"), "center")
        self.modelYPlus.addItem(self.tr("Y+ = "), "Yplus_value")
        self.modelYPlus.addItem(self.tr("Droplets diameter"), "diameter")

        # Validators

        validatorYplus = DoubleValidator(self.lineEditYPlus, min=0.0)

        validatorYplus.setExclusiveMin(True)

        self.lineEditYPlus.setValidator(validatorYplus)

        # Connect signals to slots
        self.comboBoxYPlus.activated[str].connect(self.slotYPlus)
        self.lineEditYPlus.textChanged[str].connect(self.slotYPlusValue)

        isYPlus = self.mdl.getYPlusModel()
        self.modelYPlus.setItem(str_model=isYPlus)

        if isYPlus == "Yplus_value":
            self.lineEditYPlus.show()
            self.lineEditYPlus.setText(str(self.mdl.getYPlusValue()))
        else:
            self.lineEditYPlus.hide()

        self.case.undoStartGlobal()

    @pyqtSlot(str)
    def slotYPlus(self, text):
        """
        configure Y Plus model
        """
        value = self.modelYPlus.dicoV2M[text]
        log.debug("slotYPlus -> %s" % value)
        self.mdl.setYPlusModel(value)

        if value == "Yplus_value":
            self.lineEditYPlus.show()
            self.lineEditYPlus.setText(str(self.mdl.getYPlusValue()))
        else:
            self.lineEditYPlus.hide()

    @pyqtSlot(str)
    def slotYPlusValue(self, text):
        """
        Update the Yplus value
        """
        if self.lineEditYPlus.validator().state == QValidator.Acceptable:
            value = from_qvariant(text, float)
            self.mdl.setYPlusValue(value)
예제 #16
0
class GasCombustionView(QWidget, Ui_GasCombustionForm):
    """
    Class to open the Gas Combustion option Page.
    """
    def __init__(self, parent, case):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_GasCombustionForm.__init__(self)
        self.setupUi(self)

        self.case = case
        self.case.undoStopGlobal()
        self.mdl = GasCombustionModel(self.case)
        self.thermodata = ThermochemistryData(self.case)

        # Model for table View
        self.modelSpecies = StandardItemModelSpecies(self, self.thermodata)
        self.tableViewSpecies.setModel(self.modelSpecies)

        # Delegates
        delegateLabel = NameDelegate(self.tableViewSpecies)
        delegateChemicalFormula = ChemicalFormulaDelegate(
            self.tableViewSpecies)
        delegateCompFuel = ValueDelegate(self.tableViewSpecies)
        delegateCompOxi = ValueDelegate(self.tableViewSpecies)
        delegateCompProd = ValueDelegate(self.tableViewSpecies)
        delegateCoeffAbsorp = ValueDelegate(self.tableViewSpecies)

        self.tableViewSpecies.setItemDelegateForColumn(0, delegateLabel)
        self.tableViewSpecies.setItemDelegateForColumn(
            1, delegateChemicalFormula)
        self.tableViewSpecies.setItemDelegateForColumn(2, delegateCompFuel)
        self.tableViewSpecies.setItemDelegateForColumn(3, delegateCompOxi)
        self.tableViewSpecies.setItemDelegateForColumn(4, delegateCompProd)
        self.tableViewSpecies.setItemDelegateForColumn(5, delegateCoeffAbsorp)

        # tableView
        if QT_API == "PYQT4":
            self.tableViewSpecies.horizontalHeader().setResizeMode(
                QHeaderView.Stretch)
            self.tableViewSpecies.horizontalHeader().setResizeMode(
                0, QHeaderView.ResizeToContents)
            self.tableViewSpecies.horizontalHeader().setResizeMode(
                1, QHeaderView.ResizeToContents)
        elif QT_API == "PYQT5":
            self.tableViewSpecies.horizontalHeader().setSectionResizeMode(
                QHeaderView.Stretch)
            self.tableViewSpecies.horizontalHeader().setSectionResizeMode(
                0, QHeaderView.ResizeToContents)
            self.tableViewSpecies.horizontalHeader().setSectionResizeMode(
                1, QHeaderView.ResizeToContents)

        # Set models and number of elements for combo boxes
        self.modelGasCombustionOption = ComboModel(
            self.comboBoxGasCombustionOption, 1, 1)

        # Combo models to choose the mode to create the Janaf File

        self.userModeForChemicalReaction = ComboModel(self.comboBoxUserChoice,
                                                      2, 1)

        self.userModeForChemicalReaction.addItem("Automatic definition",
                                                 'auto')
        self.userModeForChemicalReaction.addItem("Defined by user", 'user')

        # Connections
        self.comboBoxUserChoice.activated[str].connect(self.slotUserChoice)
        self.comboBoxGasCombustionOption.activated[str].connect(
            self.slotGasCombustionOption)
        self.pushButtonThermochemistryData.pressed.connect(
            self.__slotSearchThermochemistryData)
        self.radioButtonCreateJanafFile.clicked.connect(
            self.slotCreateJanafFile)
        self.lineEditNbPointsTabu.textChanged[str].connect(
            self.slotNbPointsTabu)
        self.lineEditMaximumTemp.textChanged[str].connect(self.slotMaximumTemp)
        self.lineEditMinimumTemp.textChanged[str].connect(self.slotMinimumTemp)
        self.pushButtonAddSpecies.clicked.connect(self.slotAddSpecies)
        self.pushButtonDeleteSpecies.clicked.connect(self.slotDeleteSpecies)
        self.pushButtonGenerateJanafFile.clicked.connect(
            self.slotGenerateJanafFile)
        self.lineEditFuel.textChanged[str].connect(self.slotFuel)
        self.lineEditO2.textChanged[str].connect(self.slotVolPropO2)
        self.lineEditN2.textChanged[str].connect(self.slotVolPropN2)
        self.lineEditCOyield.textChanged[str].connect(self.slotCOyield)
        self.lineEditCSyield.textChanged[str].connect(self.slotCSyield)
        self.modelSpecies.dataChanged.connect(self.dataChanged)

        # Validators
        validatorNbPointsTabu = IntValidator(self.lineEditNbPointsTabu, min=1)
        validatorMaximumTemp = DoubleValidator(self.lineEditMaximumTemp,
                                               min=273.0)
        validatorMinimumTemp = DoubleValidator(self.lineEditMinimumTemp,
                                               min=273.0)
        rx = "[chonlCHONL()][CHONLchonl()0-9]{0," + str(LABEL_LENGTH_MAX -
                                                        1) + "}"
        validatorFuel = RegExpValidator(self.lineEditFuel, QRegExp(rx))
        validatorO2 = DoubleValidator(self.lineEditO2, min=1e-12, max=1.0)
        validatorN2 = DoubleValidator(self.lineEditN2, min=0.0, max=1.0)
        validatorCOyield = DoubleValidator(self.lineEditCOyield, min=0.0)
        validatorCSyield = DoubleValidator(self.lineEditCSyield, min=0.0)

        self.lineEditNbPointsTabu.setValidator(validatorNbPointsTabu)
        self.lineEditMaximumTemp.setValidator(validatorMaximumTemp)
        self.lineEditMinimumTemp.setValidator(validatorMinimumTemp)
        self.lineEditFuel.setValidator(validatorFuel)
        self.lineEditO2.setValidator(validatorO2)
        self.lineEditN2.setValidator(validatorN2)
        self.lineEditCOyield.setValidator(validatorCOyield)
        self.lineEditCSyield.setValidator(validatorCSyield)

        NbPointsTabu = self.thermodata.getNbPointsTabu()
        MaximumTemp = self.thermodata.getMaximumTemp()
        MinimumTemp = self.thermodata.getMinimumTemp()
        Option_UserMode = self.thermodata.getUserModeForChemicalReaction()
        ChemicalFormulaFuel = self.thermodata.getChemicalFormulaFuel()
        VolPropO2 = self.thermodata.getVolPropO2()
        VolPropN2 = self.thermodata.getVolPropN2()
        COyield = self.thermodata.getCOyield()
        CSyield = self.thermodata.getCSyield()

        self.lineEditNbPointsTabu.setText(str(NbPointsTabu))
        self.lineEditMaximumTemp.setText(str(MaximumTemp))
        self.lineEditMinimumTemp.setText(str(MinimumTemp))
        self.lineEditFuel.setText(str(ChemicalFormulaFuel))
        self.lineEditO2.setText(str(VolPropO2))
        self.lineEditN2.setText(str(VolPropN2))
        self.lineEditCOyield.setText(str(COyield))
        self.lineEditCSyield.setText(str(CSyield))

        # Initialize Widgets

        self.tableViewSpecies.reset()
        self.modelSpecies = StandardItemModelSpecies(self, self.thermodata)
        self.tableViewSpecies.setModel(self.modelSpecies)

        model = self.mdl.getGasCombustionModel()

        if model == 'd3p':
            self.modelGasCombustionOption.addItem(self.tr("adiabatic model"),
                                                  "adiabatic")
            self.modelGasCombustionOption.addItem(
                self.tr("non adiabatic model"), "extended")
        elif model == 'ebu':
            self.modelGasCombustionOption.addItem(
                self.tr("reference Spalding model"), "spalding")
            self.modelGasCombustionOption.addItem(
                self.tr("extended model with enthalpy source term"),
                "enthalpy_st")
            self.modelGasCombustionOption.addItem(
                self.tr("extended model with mixture fraction transport"),
                "mixture_st")
            self.modelGasCombustionOption.addItem(
                self.
                tr("extended model with enthalpy and mixture fraction transport"
                   ), "enthalpy_mixture_st")
        elif model == 'lwp':
            self.modelGasCombustionOption.addItem(
                self.tr("reference two-peak model with adiabatic condition"),
                "2-peak_adiabatic")
            self.modelGasCombustionOption.addItem(
                self.tr("reference two-peak model with enthalpy source term"),
                "2-peak_enthalpy")
            self.modelGasCombustionOption.addItem(
                self.tr("reference three-peak model with adiabatic condition"),
                "3-peak_adiabatic")
            self.modelGasCombustionOption.addItem(
                self.tr(
                    "reference three-peak model with enthalpy source term"),
                "3-peak_enthalpy")
            self.modelGasCombustionOption.addItem(
                self.tr("reference four-peak model with adiabatic condition"),
                "4-peak_adiabatic")
            self.modelGasCombustionOption.addItem(
                self.tr("reference four-peak model with enthalpy source term"),
                "4-peak_enthalpy")

        option = self.mdl.getGasCombustionOption()
        self.modelGasCombustionOption.setItem(str_model=option)

        name = self.mdl.getThermoChemistryDataFileName()
        if name != None and name != "":
            self.labelThermochemistryFile.setText(str(name))
            self.pushButtonThermochemistryData.setStyleSheet(
                "background-color: green")
        else:
            self.pushButtonThermochemistryData.setStyleSheet(
                "background-color: red")

        self.radioButtonCreateJanafFile.hide()

        if self.thermodata.getCreateThermoDataFile() == 'on':
            self.radioButtonCreateJanafFile.setChecked(True)
            self.userModeForChemicalReaction.setItem(str_model=Option_UserMode)
            for label in self.thermodata.getSpeciesNamesList():
                self.modelSpecies.newItem(label)
        else:
            self.radioButtonCreateJanafFile.setChecked(False)

        # for the moment the option to create Janaf file in the GUI is only available with d3p
        if model == 'd3p':
            self.radioButtonCreateJanafFile.show()
            self.groupBoxTabulation.show()
            self.groupBoxChemicalReaction.show()
            self.groupBoxDefinedByUser.show()
            self.groupBoxGenerateDataFile.show()
            self.groupBoxAutomatic.show()

        self.slotCreateJanafFile()

        self.case.undoStartGlobal()

    @pyqtSlot(str)
    def slotGasCombustionOption(self, text):
        """
        Private slot.
        Binding method for gas combustion models.
        """
        option = self.modelGasCombustionOption.dicoV2M[str(text)]
        self.mdl.setGasCombustionOption(option)

    @pyqtSlot()
    def __slotSearchThermochemistryData(self):
        """
        Select a properties file of data for electric arc
        """
        data = self.case['data_path']
        if not data:
            data = "."
        title = self.tr("Thermochemistry file of data.")
        filetypes = self.tr("Thermochemistry (*dp_*);;All Files (*)")
        file = QFileDialog.getOpenFileName(self, title, data, filetypes)[0]
        file = str(file)
        if not file:
            return
        file = os.path.basename(file)
        if file not in os.listdir(data):
            title = self.tr("WARNING")
            msg = self.tr("This selected file is not in the DATA directory")
            QMessageBox.information(self, title, msg)
        else:
            self.labelThermochemistryFile.setText(str(file))
            self.mdl.setThermoChemistryDataFileName(file)
            self.pushButtonThermochemistryData.setStyleSheet(
                "background-color: green")

    @pyqtSlot()
    def slotCreateJanafFile(self):
        """
        Determine if the Thermochemistry file is created with the GUI.
        """
        if self.radioButtonCreateJanafFile.isChecked():
            self.thermodata.setCreateThermoDataFile("on")
            self.groupBoxTabulation.show()
            self.groupBoxChemicalReaction.show()
            self.lineEditNbPointsTabu.setText(
                str(self.thermodata.getNbPointsTabu()))
            self.lineEditMaximumTemp.setText(
                str(self.thermodata.getMaximumTemp()))
            self.lineEditMinimumTemp.setText(
                str(self.thermodata.getMinimumTemp()))
            self.slotUserChoice()
            return
        else:
            self.thermodata.setCreateThermoDataFile("off")
            self.groupBoxTabulation.hide()
            self.groupBoxChemicalReaction.hide()
            self.groupBoxDefinedByUser.hide()
            self.groupBoxGenerateDataFile.hide()
            self.groupBoxAutomatic.hide()

    @pyqtSlot(str)
    def slotUserChoice(self):
        """
        """
        model = self.userModeForChemicalReaction.dicoV2M[str(
            self.comboBoxUserChoice.currentText())]
        self.thermodata.setUserModeForChemicalReaction(model)
        self.groupBoxGenerateDataFile.show()
        if model == 'auto':
            self.groupBoxAutomatic.show()
            self.groupBoxDefinedByUser.hide()
            #update of the xml from the GUI
            self.slotFuel(self.lineEditFuel.text())
            self.slotVolPropO2(self.lineEditO2.text())
            self.slotVolPropN2(self.lineEditN2.text())
            self.slotCOyield(self.lineEditCOyield.text())
            self.slotCSyield(self.lineEditCSyield.text())
        elif model == 'user':
            self.groupBoxDefinedByUser.show()
            self.groupBoxAutomatic.hide()
            #update of the xml from the tableView
            row_tab = self.modelSpecies.rowCount()
            for row in range(row_tab):
                data = self.modelSpecies.getItem(row)
                self.thermodata.updateSpecies(data)

    @pyqtSlot(str)
    def slotNbPointsTabu(self, text):
        """
        Input Number of points for the tabulation (ENTH-TEMP)
        """
        if self.lineEditNbPointsTabu.validator(
        ).state == QValidator.Acceptable:
            NbPointsTabu = from_qvariant(text, int)
            self.thermodata.setNbPointsTabu(NbPointsTabu)

    @pyqtSlot(str)
    def slotMaximumTemp(self, text):
        """
        Input Maximum temperature for the tabulation (ENTH-TEMP)
        """
        if self.lineEditMaximumTemp.validator().state == QValidator.Acceptable:
            MaximumTemp = from_qvariant(text, float)
            self.thermodata.setMaximumTemp(MaximumTemp)

    @pyqtSlot(str)
    def slotMinimumTemp(self, text):
        """
        Input Minimum temperature for the tabulation (ENTH-TEMP)
        """
        if self.lineEditMinimumTemp.validator().state == QValidator.Acceptable:
            MinimumTemp = from_qvariant(text, float)
            self.thermodata.setMinimumTemp(MinimumTemp)

    @pyqtSlot(str)
    def slotFuel(self, text):
        """
        Input the chemical formula for the Fuel
        """
        if self.lineEditFuel.validator().state == QValidator.Acceptable:
            ChemicalFormula = from_qvariant(text, to_text_string)
            self.thermodata.setChemicalFormulaFuel(ChemicalFormula)

    @pyqtSlot(str)
    def slotVolPropO2(self, text):
        """
        Input volume proportion for O2
        """
        if self.lineEditO2.validator().state == QValidator.Acceptable:
            VolPropO2 = from_qvariant(text, float)
            self.thermodata.setVolPropO2(VolPropO2)
            self.lineEditN2.setText(str(round(1.0 - VolPropO2, 12)))

    @pyqtSlot(str)
    def slotVolPropN2(self, text):
        """
        Input volume proportion for N2
        """
        if self.lineEditN2.validator().state == QValidator.Acceptable:
            VolPropN2 = from_qvariant(text, float)
            self.thermodata.setVolPropN2(VolPropN2)
            self.lineEditO2.setText(str(round(1.0 - VolPropN2, 12)))

    @pyqtSlot(str)
    def slotCOyield(self, text):
        """
        Input the CO yield
        """
        if self.lineEditCOyield.validator().state == QValidator.Acceptable:
            COyield = from_qvariant(text, float)
            self.thermodata.setCOyield(COyield)

    @pyqtSlot(str)
    def slotCSyield(self, text):
        """
        Input the CS yield
        """
        if self.lineEditCSyield.validator().state == QValidator.Acceptable:
            CSyield = from_qvariant(text, float)
            self.thermodata.setCSyield(CSyield)

    @pyqtSlot()
    def slotAddSpecies(self):
        """
        Add a new item in the table when the 'Create' button is pushed.
        """
        self.tableViewSpecies.clearSelection()
        self.modelSpecies.newItem()

    @pyqtSlot()
    def slotDeleteSpecies(self):
        """
        Just delete the current selected entries from the table and
        of course from the XML file.
        """
        lst = []
        for index in self.tableViewSpecies.selectionModel().selectedRows():
            row = index.row()
            lst.append(row)

        lst.sort()
        lst.reverse()

        for row in lst:
            label = self.modelSpecies.getItem(row)[0]
            self.thermodata.deleteSpecies(label)
            self.modelSpecies.deleteItem(row)

        self.tableViewSpecies.clearSelection()

    @pyqtSlot()
    def slotGenerateJanafFile(self):
        """
        Generate the Thermochemistry file.
        """

        data = self.case['data_path']
        if not data:
            data = "."
        filename = "dp_ThermochemistryFromGui"
        file_path = os.path.join(data, filename)

        self.thermodata.WriteThermochemistryDataFile(file_path)

        self.mdl.setThermoChemistryDataFileName(filename)

        if self.thermodata.Error_GUI:
            self.labelThermochemistryFile.setText(str("Error in : " +
                                                      filename))
            self.pushButtonGenerateJanafFile.setStyleSheet(
                "background-color: red")
            self.pushButtonThermochemistryData.setStyleSheet(
                "background-color: orange")
        else:
            self.labelThermochemistryFile.setText(str(filename))
            self.pushButtonGenerateJanafFile.setStyleSheet("")
            self.pushButtonThermochemistryData.setStyleSheet(
                "background-color: green")

    @pyqtSlot("QModelIndex, QModelIndex")
    def dataChanged(self, topLeft, bottomRight):
        for row in range(topLeft.row(), bottomRight.row() + 1):
            self.tableViewSpecies.resizeRowToContents(row)
        for col in range(topLeft.column(), bottomRight.column() + 1):
            self.tableViewSpecies.resizeColumnToContents(col)
예제 #17
0
class BoundaryConditionsHydraulicHeadView(
        QWidget, Ui_BoundaryConditionsHydraulicHeadForm):
    def __init__(self, parent):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_BoundaryConditionsHydraulicHeadForm.__init__(self)
        self.setupUi(self)

    def setup(self, case):
        """
        Setup the widget
        """
        self.case = case
        self.__boundary = None
        self.notebook = NotebookModel(self.case)

        self.case.undoStopGlobal()

        # Validators
        validatorHh = DoubleValidator(self.lineEditValueHydraulicHead)
        validatorExHh = DoubleValidator(self.lineEditExHydraulicHead)

        # Apply validators
        self.lineEditValueHydraulicHead.setValidator(validatorHh)
        self.lineEditExHydraulicHead.setValidator(validatorHh)

        self.modelTypeHydraulic = ComboModel(self.comboBoxTypeHydraulicHead, 1,
                                             1)
        self.modelTypeHydraulic.addItem(self.tr("Prescribed value"),
                                        'dirichlet')
        self.modelTypeHydraulic.addItem(
            self.tr("Prescribed value  (user law)"), 'dirichlet_formula')
        self.modelTypeHydraulic.addItem(self.tr("Prescribed flux"), 'neumann')

        # Connections
        self.lineEditValueHydraulicHead.textChanged[str].connect(
            self.slotHydraulicHeadValue)
        self.lineEditExHydraulicHead.textChanged[str].connect(
            self.slotHydraulicHeadFlux)
        self.pushButtonHydraulicHead.clicked.connect(
            self.slotHydraulicHeadFormula)
        self.comboBoxTypeHydraulicHead.activated[str].connect(
            self.slotHydraulicHeadChoice)

        self.case.undoStartGlobal()

    def showWidget(self, boundary):
        """
        Show the widget
        """
        label = boundary.getLabel()
        self.nature = boundary.getNature()
        self.__boundary = Boundary(self.nature, label, self.case)
        self.initialize()

    def initialize(self):
        self.labelValueHydraulicHead.hide()
        self.labelExHydraulicHead.hide()
        self.lineEditValueHydraulicHead.hide()
        self.lineEditExHydraulicHead.hide()
        self.pushButtonHydraulicHead.setEnabled(False)
        self.pushButtonHydraulicHead.setStyleSheet("background-color: None")

        HydraulicChoice = self.__boundary.getHydraulicHeadChoice()
        self.modelTypeHydraulic.setItem(str_model=HydraulicChoice)
        if HydraulicChoice == 'dirichlet':
            self.labelValueHydraulicHead.show()
            self.lineEditValueHydraulicHead.show()
            h_head = self.__boundary.getHydraulicHeadValue()
            self.lineEditValueHydraulicHead.setText(str(h_head))
        elif HydraulicChoice == 'neumann':
            self.labelExHydraulicHead.show()
            self.lineEditExHydraulicHead.show()
            h_head = self.__boundary.getHydraulicHeadFlux()
            self.lineEditExHydraulicHead.setText(str(h_head))
        elif HydraulicChoice == 'dirichlet_formula':
            self.pushButtonHydraulicHead.setEnabled(True)

            exp = self.__boundary.getHydraulicHeadFormula()
            if exp:
                self.pushButtonHydraulicHead.setStyleSheet(
                    "background-color: green")
                self.pushButtonHydraulicHead.setToolTip(exp)
            else:
                self.pushButtonHydraulicHead.setStyleSheet(
                    "background-color: red")

        self.show()

    def hideWidget(self):
        """
        Hide all
        """
        self.hide()

    @pyqtSlot(str)
    def slotHydraulicHeadValue(self, text):
        """
        INPUT hydraulic head value
        """
        if self.lineEditValueHydraulicHead.validator(
        ).state == QValidator.Acceptable:
            t = from_qvariant(text, float)
            self.__boundary.setHydraulicHeadValue(t)

    @pyqtSlot(str)
    def slotHydraulicHeadFlux(self, text):
        """
        INPUT hydraulic head flux
        """
        if self.lineEditExHydraulicHead.validator(
        ).state == QValidator.Acceptable:
            t = from_qvariant(text, float)
            self.__boundary.setHydraulicHeadFlux(t)

    @pyqtSlot()
    def slotHydraulicHeadFormula(self):
        """
        """
        exp = self.__boundary.getHydraulicHeadFormula()
        exa = """#example: """
        req = [("H", "hydraulic head")]

        sym = [('x', "X face's gravity center"),
               ('y', "Y face's gravity center"),
               ('z', "Z face's gravity center"), ('dt', 'time step'),
               ('t', 'current time'), ('iter', 'number of iteration'),
               ('surface', 'Boundary zone surface')]

        for (nme, val) in self.notebook.getNotebookList():
            sym.append((nme, 'value (notebook) = ' + str(val)))

        dialog = QMegEditorView(parent=self,
                                function_type='bnd',
                                zone_name=self.__boundary._label,
                                variable_name='hydraulic_head',
                                expression=exp,
                                required=req,
                                symbols=sym,
                                condition='dirichlet_formula',
                                examples=exa)

        if dialog.exec_():
            result = dialog.get_result()
            log.debug("slotHydraulicHeadFormula -> %s" % str(result))
            self.__boundary.setHydraulicHeadFormula(str(result))
            self.pushButtonHydraulicHead.setStyleSheet(
                "background-color: green")
            self.pushButtonHydraulicHead.setToolTip(result)

    @pyqtSlot(str)
    def slotHydraulicHeadChoice(self, text):
        """
        INPUT label for choice of zone
        """
        HydraulicChoice = self.modelTypeHydraulic.dicoV2M[str(text)]
        self.__boundary.setHydraulicHeadChoice(HydraulicChoice)
        self.initialize()
class NeptuneWallTransferView(QWidget, Ui_NeptuneWallTransferForm):
    def __init__(self, parent, case):
        QWidget.__init__(self, parent)
        Ui_NeptuneWallTransferForm.__init__(self)
        self.setupUi(self)

        self.case = case
        self.case.undoStopGlobal()
        self.xml_model = NeptuneWallTransferModel(self.case)

        self.set_connections()
        # Connections must be set before ComboModel is declared.
        self.combomodel_wallmodel = ComboModel(self.comboBoxWallTransferType)
        self.fill_widgets()
        self.initialize_widgets()
        self.update_view()

    def initialize_widgets(self):
        predefined_flow = MainFieldsModel(self.case).getPredefinedFlow()
        if predefined_flow in ["free_surface", "boiling_flow"]:
            self.combomodel_wallmodel.setItem(str_model="nucleate_boiling")
            self.setEnabled(False)
        elif predefined_flow == "droplet_flow":
            self.combomodel_wallmodel.setItem(
                str_model="droplet_evaporation_condensation")
            self.setEnabled(False)
        elif predefined_flow == "multiregime":
            self.combomodel_wallmodel.disableItem(str_model="none")
            self.combomodel_wallmodel.setItem(
                str_model=self.xml_model.wall_transfer_type)
            self.boilingWidget.setEnabled(False)
            self.dropletWidget.setEnabled(False)
        else:
            self.combomodel_wallmodel.setItem(
                str_model=self.xml_model.wall_transfer_type)

    def update_view(self):
        model = self.xml_model.wall_transfer_type
        self.boilingWidget.hide()
        self.dropletWidget.hide()
        if model == "nucleate_boiling":
            self.boilingWidget.setup(self.case)
            self.boilingWidget.show()
        elif model == "droplet_evaporation_condensation":
            self.dropletWidget.setup(self.case)
            self.dropletWidget.show()
        elif model == "none":
            pass
        else:
            raise ValueError("Unknown model {0}".format(model))
        return

    def fill_widgets(self):
        self.combomodel_wallmodel.addItem(self.tr("None"), "none")
        self.combomodel_wallmodel.addItem(self.tr("Nucleate boiling"),
                                          "nucleate_boiling")
        self.combomodel_wallmodel.addItem(
            self.tr("Droplet evaporation/condensation"),
            "droplet_evaporation_condensation")
        return

    def set_connections(self):
        self.comboBoxWallTransferType.currentTextChanged[str].connect(
            self.slot_set_wall_model)

    @pyqtSlot(str)
    def slot_set_wall_model(self, text):
        model = self.combomodel_wallmodel.dicoV2M[text]
        self.xml_model.wall_transfer_type = model
        self.update_view()
        return
class TimeStepView(QWidget, Ui_TimeStep):
    """
    Time step control layout.
    """
    def __init__(self, parent, case):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_TimeStep.__init__(self)
        self.setupUi(self)

        self.case = case
        self.case.undoStopGlobal()
        self.mdl = TimeStepModel(self.case)

        # Combo box models

        self.modelTimeStepOption = ComboModel(self.comboBoxTimeStepOption, 3, 1)
        self.modelTimeStepOption.addItem(self.tr("Constant"), "constant")
        self.modelTimeStepOption.addItem(self.tr("Adaptive"), "uniform")
        self.modelTimeStepOption.addItem(self.tr("Steady"), "steady")

        self.modelTimeStop = ComboModel(self.comboBoxTimeStopType, 2, 1)
        self.modelTimeStop.addItem(self.tr("Number of time steps"), "iteration")
        self.modelTimeStop.addItem(self.tr("Time analysis (s)"), "time")

        # Validators

        validatorRefT   = DoubleValidator(self.lineEditReferenceTimeStep, min = 0.0)
        validatorNumT   = IntValidator(self.lineEditNumberTimeStep, min = 0)
        validatorAnaT   = DoubleValidator(self.lineEditTimeAnalysis)
        validatorDtMin  = DoubleValidator(self.lineEditDtMin, min = 0.0)
        validatorDtMax  = DoubleValidator(self.lineEditDtMax, min = 0.0)
        validatorIncMax = DoubleValidator(self.lineEditDtIncreasingMax, min = 0.0)
        validatorDecMax = DoubleValidator(self.lineEditDtDecreasingMax, min = 0.0)

        validatorRefT.setExclusiveMin(True)
        validatorNumT.setExclusiveMin(True)
        validatorDtMin.setExclusiveMin(True)
        validatorDtMax.setExclusiveMin(True)
        validatorIncMax.setExclusiveMin(True)
        validatorDecMax.setExclusiveMin(True)

        self.lineEditReferenceTimeStep.setValidator(validatorRefT)
        self.lineEditNumberTimeStep.setValidator(validatorNumT)
        self.lineEditTimeAnalysis.setValidator(validatorAnaT)
        self.lineEditDtMin.setValidator(validatorDtMin)
        self.lineEditDtMax.setValidator(validatorDtMax)
        self.lineEditDtIncreasingMax.setValidator(validatorIncMax)
        self.lineEditDtDecreasingMax.setValidator(validatorDecMax)

        # tableViewCourantFourier

        self.tableModelCourantFourier = StandardItemModelCourantFourier(self.mdl)
        self.tableViewCourantFourier.setModel(self.tableModelCourantFourier)
        self.tableViewCourantFourier.resizeColumnsToContents()
        self.tableViewCourantFourier.resizeRowsToContents()
        if QT_API == "PYQT4":
            self.tableViewCourantFourier.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)
            self.tableViewCourantFourier.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
            self.tableViewCourantFourier.horizontalHeader().setResizeMode(0,QHeaderView.Stretch)
        elif QT_API == "PYQT5":
            self.tableViewCourantFourier.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
            self.tableViewCourantFourier.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
            self.tableViewCourantFourier.horizontalHeader().setSectionResizeMode(0,QHeaderView.Stretch)
        self.tableViewCourantFourier.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableViewCourantFourier.setSelectionMode(QAbstractItemView.SingleSelection)

        delegateMaxFourier = ValueDelegate(self.tableViewCourantFourier)
        delegateMaxCourant = ValueDelegate(self.tableViewCourantFourier)

        self.tableViewCourantFourier.setItemDelegateForColumn(1, delegateMaxFourier)
        self.tableViewCourantFourier.setItemDelegateForColumn(2, delegateMaxCourant)

        # Connect signals to slots
        self.comboBoxTimeStepOption.activated[str].connect(self.slotTimeStepOption)
        self.comboBoxTimeStopType.activated[str].connect(self.slotTimeStop)
        self.lineEditReferenceTimeStep.textChanged[str].connect(self.slotReferenceTimeStep)
        self.lineEditNumberTimeStep.textChanged[str].connect(self.slotNumberTimeStep)
        self.lineEditTimeAnalysis.textChanged[str].connect(self.slotTimeAnalysis)
        self.lineEditDtMin.textChanged[str].connect(self.slotDtMin)
        self.lineEditDtMax.textChanged[str].connect(self.slotDtMax)
        self.lineEditDtIncreasingMax.textChanged[str].connect(self.slotDtIncreasingMax)
        self.lineEditDtDecreasingMax.textChanged[str].connect(self.slotDtDecreasingMax)
        self.tableModelCourantFourier.dataChanged.connect(self.dataChanged)

        # Initialize widget
        self.initializeVariables()

        self.case.undoStartGlobal()


    def dataChanged(self, topLeft, bottomRight):
        for row in range(topLeft.row(), bottomRight.row()+1):
            self.tableViewCourantFourier.resizeRowToContents(row)
        for col in range(topLeft.column(), bottomRight.column()+1):
            self.tableViewCourantFourier.resizeColumnToContents(col)


    @pyqtSlot(str)
    def slotTimeStepOption(self, text):
        """
        INPUT time option
        """
        model = self.modelTimeStepOption.dicoV2M[text]
        self.mdl.setTimePassingChoice(model)
        self.initializeVariables()


    @pyqtSlot(str)
    def slotTimeStop(self, text):
        """
        INPUT time stop option
        """
        model = self.modelTimeStop.dicoV2M[text]
        self.mdl.setTimeStopChoice(model)

        if model == "time" :
            self.lineEditNumberTimeStep.hide()
            self.lineEditTimeAnalysis.show()
            value = self.mdl.getMaximumTime()
            self.lineEditTimeAnalysis.setText(str(value))
        else :
            self.lineEditNumberTimeStep.show()
            value = self.mdl.getTimeStepsNumber()
            self.lineEditNumberTimeStep.setText(str(value))
            self.lineEditTimeAnalysis.hide()


    @pyqtSlot(str)
    def slotReferenceTimeStep(self, var):
        """
        """
        if self.lineEditReferenceTimeStep.validator().state == QValidator.Acceptable:
            value = from_qvariant(var, float)
            self.mdl.setTimeStep(value)


    @pyqtSlot(str)
    def slotNumberTimeStep(self, var):
        """
        """
        if self.lineEditNumberTimeStep.validator().state == QValidator.Acceptable:
            value = from_qvariant(var, int)
            self.mdl.setTimeStepsNumber(value)


    @pyqtSlot(str)
    def slotTimeAnalysis(self, var):
        """
        """
        if self.lineEditTimeAnalysis.validator().state == QValidator.Acceptable:
            value = from_qvariant(var, float)
            self.mdl.setMaximumTime(value)


    @pyqtSlot(str)
    def slotDtMin(self, var):
        """
        """
        if self.lineEditDtMin.validator().state == QValidator.Acceptable:
            value = from_qvariant(var, float)
            self.mdl.setMinDtDt0Variation(value)


    @pyqtSlot(str)
    def slotDtMax(self, var):
        """
        """
        if self.lineEditDtMax.validator().state == QValidator.Acceptable:
            value = from_qvariant(var, float)
            self.mdl.setMaxDtDt0Variation(value)


    @pyqtSlot(str)
    def slotDtIncreasingMax(self, var):
        """
        """
        if self.lineEditDtIncreasingMax.validator().state == QValidator.Acceptable:
            value = from_qvariant(var, float)
            self.mdl.setMaxDtVariationIncreasing(value)


    @pyqtSlot(str)
    def slotDtDecreasingMax(self, var):
        """
        """
        if self.lineEditDtDecreasingMax.validator().state == QValidator.Acceptable:
            value = from_qvariant(var, float)
            self.mdl.setMaxDtVariationDecreasing(value)


    def initializeVariables(self):
        """
        Initialize when a timee step option is choosen
        """
        value = self.mdl.getTimeStep()
        self.lineEditReferenceTimeStep.setText(str(value))

        model = self.mdl.getTimePassingChoice()
        self.modelTimeStepOption.setItem(str_model = model)

        if model == "constant" or model == "steady":
            self.groupBoxAdvancedParameters.hide()
            self.groupBoxCourantFourierParameters.hide()
        else :
            self.groupBoxAdvancedParameters.show()
            self.groupBoxCourantFourierParameters.show()

            value = self.mdl.getMinDtDt0Variation()
            self.lineEditDtMin.setText(str(value))

            value = self.mdl.getMaxDtDt0Variation()
            self.lineEditDtMax.setText(str(value))

            value = self.mdl.getMaxDtVariationIncreasing()
            self.lineEditDtIncreasingMax.setText(str(value))

            value = self.mdl.getMaxDtVariationDecreasing()
            self.lineEditDtDecreasingMax.setText(str(value))

            if (self.tableModelCourantFourier.rowCount() <= 0) :
                for fieldId in self.mdl.getFieldIdList():
                    self.tableModelCourantFourier.newItem(fieldId)

        model = self.mdl.getTimeStopChoice()
        self.modelTimeStop.setItem(str_model = model)

        if model == "time" :
            self.lineEditNumberTimeStep.hide()
            self.lineEditTimeAnalysis.show()
            value = self.mdl.getMaximumTime()
            self.lineEditTimeAnalysis.setText(str(value))
        else :
            self.lineEditNumberTimeStep.show()
            value = self.mdl.getTimeStepsNumber()
            self.lineEditNumberTimeStep.setText(str(value))
            self.lineEditTimeAnalysis.hide()
예제 #20
0
class OutputFieldsView(QWidget, Ui_OutputFields):
    """
    Output Fields layout.
    """
    def __init__(self, parent, case):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_OutputFields.__init__(self)
        self.setupUi(self)

        self.case   = case
        self.case.undoStopGlobal()
        self.mdl    = OutputFieldsModel(self.case)

        # Combo box models
        self.modelField = ComboModel(self.comboBoxField, 1, 1)
        for fieldId in self.mdl.getFieldIdList() :
            label = self.mdl.getLabel(fieldId)
            name = str(fieldId)
            self.modelField.addItem(self.tr(label), name)

        self.currentid = -1
        if len(self.mdl.getFieldIdList()) > 0 :
            self.currentid = self.mdl.getFieldIdList()[0]
            self.modelField.setItem(str_model = self.currentid)

        self.tableModelGlobalVariables = StandardItemModelGlobalVariables(self, "none", self.mdl)
        self.tableViewGlobalVariables.setModel(self.tableModelGlobalVariables)
        self.tableViewGlobalVariables.resizeColumnsToContents()
        self.tableViewGlobalVariables.resizeRowsToContents()
        if QT_API == "PYQT4":
            self.tableViewGlobalVariables.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
            self.tableViewGlobalVariables.horizontalHeader().setResizeMode(0,QHeaderView.Stretch)
        elif QT_API == "PYQT5":
            self.tableViewGlobalVariables.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
            self.tableViewGlobalVariables.horizontalHeader().setSectionResizeMode(0,QHeaderView.Stretch)
        self.tableViewGlobalVariables.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableViewGlobalVariables.setSelectionMode(QAbstractItemView.SingleSelection)

        self.tableModelFieldsVariables = StandardItemModelGlobalVariables(self, self.currentid, self.mdl)
        self.tableViewFieldsVariables.setModel(self.tableModelFieldsVariables)
        self.tableViewFieldsVariables.resizeColumnsToContents()
        self.tableViewFieldsVariables.resizeRowsToContents()
        if QT_API == "PYQT4":
            self.tableViewFieldsVariables.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
            self.tableViewFieldsVariables.horizontalHeader().setResizeMode(0,QHeaderView.Stretch)
        elif QT_API == "PYQT5":
            self.tableViewFieldsVariables.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
            self.tableViewFieldsVariables.horizontalHeader().setSectionResizeMode(0,QHeaderView.Stretch)
        self.tableViewFieldsVariables.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableViewFieldsVariables.setSelectionMode(QAbstractItemView.SingleSelection)

        delegateNameG   = NameDelegate(self.tableViewGlobalVariables)
        delegateNameF   = NameDelegate(self.tableViewFieldsVariables)
        probesDelegateG = ProbesDelegate(self.tableViewGlobalVariables, self.mdl)
        probesDelegateF = ProbesDelegate(self.tableViewFieldsVariables, self.mdl)

        self.tableViewGlobalVariables.setItemDelegateForColumn(0, delegateNameG)
        self.tableViewGlobalVariables.setItemDelegateForColumn(3, probesDelegateG)
        self.tableViewFieldsVariables.setItemDelegateForColumn(0, delegateNameF)
        self.tableViewFieldsVariables.setItemDelegateForColumn(3, probesDelegateF)

        # Connect signals to slots
        self.tableModelGlobalVariables.dataChanged.connect(self.dataChangedGlobalVariables)
        self.tableModelFieldsVariables.dataChanged.connect(self.dataChangedFieldsVariables)
        self.comboBoxField.activated[str].connect(self.slotField)

        for var in self.mdl.getGlobalVariables() :
            self.tableModelGlobalVariables.newItem("none", var)

        if (len(self.mdl.getFieldIdList())> 0) :
            self.groupBoxField.show()
            self.initializeVariables(self.currentid)
        else :
            self.groupBoxField.hide()

        self.case.undoStartGlobal()


    def dataChangedGlobalVariables(self, topLeft, bottomRight) :
        for row in range(topLeft.row(), bottomRight.row()+1):
            self.tableViewGlobalVariables.resizeRowToContents(row)
        for col in range(topLeft.column(), bottomRight.column()+1):
            self.tableViewGlobalVariables.resizeColumnToContents(col)


    def dataChangedFieldsVariables(self, topLeft, bottomRight) :
        for row in range(topLeft.row(), bottomRight.row()+1):
            self.tableViewFieldsVariables.resizeRowToContents(row)
        for col in range(topLeft.column(), bottomRight.column()+1):
            self.tableViewFieldsVariables.resizeColumnToContents(col)


    @pyqtSlot(str)
    def slotField(self, text):
        """
        INPUT label for choice of field
        """
        self.currentid = self.modelField.dicoV2M[text]
        self.initializeVariables(self.currentid)


    def initializeVariables(self, FieldId) :
        """
        Update variable and property in table
        """
        while self.tableModelFieldsVariables.rowCount():
            self.tableModelFieldsVariables.deleteItem(0)

        for var in self.mdl.getFieldVariables(self.currentid) :
            self.tableModelFieldsVariables.newItem(self.currentid, var)

        self.tableModelFieldsVariables.updateField(self.currentid)
예제 #21
0
class SolidView(QWidget, Ui_Solid):
    """
    Particles interaction layout.
    """
    def __init__(self, parent, case):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_Solid.__init__(self)
        self.setupUi(self)

        self.case = case
        self.case.undoStopGlobal()
        self.mdl = SolidModel(self.case)

        if self.mdl.getSolidFieldIdList() == []:
            self.groupBoxField.hide()
            self.groupBoxInteractions.hide()
            self.groupBoxGeneral.hide()
            self.labelNoParticles.show()
            return

        # Combo box models

        self.modelField = ComboModel(self.comboBoxField, 1, 1)
        for fieldId in self.mdl.getSolidFieldIdList():
            label = self.mdl.getLabel(fieldId)
            name = str(fieldId)
            self.modelField.addItem(self.tr(label), name)

        self.currentid = -1

        if len(self.mdl.getSolidFieldIdList()) > 0:
            self.currentid = self.mdl.getSolidFieldIdList()[0]
            self.modelField.setItem(str_model=self.currentid)

        self.modelFriction = ComboModel(self.comboBoxFriction, 3, 1)
        self.modelFriction.addItem(self.tr("none"), "none")
        self.modelFriction.addItem(self.tr("pressure"), "pressure")
        self.modelFriction.addItem(self.tr("fluxes"), "fluxes")

        self.modelGranular = ComboModel(self.comboBoxGranular, 3, 1)
        self.modelGranular.addItem(self.tr("none"), "none")
        self.modelGranular.addItem(self.tr("pressure"), "pressure")
        self.modelGranular.addItem(self.tr("fluxes"), "fluxes")

        self.modelKinetic = ComboModel(self.comboBoxKinetic, 3, 1)
        self.modelKinetic.addItem(self.tr("none"), "none")
        self.modelKinetic.addItem(self.tr("uncorrelated collision"),
                                  "uncorrelate_collision")
        self.modelKinetic.addItem(self.tr("correlated collision"),
                                  "correlate_collision")

        # Validators

        validatorComp = DoubleValidator(self.lineEditCompaction, min=0.0)
        validatorComp.setExclusiveMin(True)
        self.lineEditCompaction.setValidator(validatorComp)

        # Connect signals to slots
        self.comboBoxField.activated[str].connect(self.slotField)
        self.comboBoxFriction.activated[str].connect(self.slotFriction)
        self.comboBoxGranular.activated[str].connect(self.slotGranular)
        self.comboBoxKinetic.activated[str].connect(self.slotKinetic)
        self.lineEditCompaction.textChanged[str].connect(self.slotCompaction)
        self.checkBoxCoupling.clicked[bool].connect(self.slotCoupling)

        # Initialize widget
        self.initializeVariables(self.currentid)

        self.case.undoStartGlobal()

    @pyqtSlot(str)
    def slotField(self, text):
        """
        INPUT label for choice of field
        """
        self.currentid = self.modelField.dicoV2M[text]
        self.initializeVariables(self.currentid)

    @pyqtSlot(str)
    def slotFriction(self, text):
        """
        INPUT type for choice of friction model
        """
        model = self.modelFriction.dicoV2M[text]
        self.mdl.setFrictionModel(self.currentid, model)

    @pyqtSlot(str)
    def slotGranular(self, text):
        """
        INPUT type for choice of granular model
        """
        model = self.modelGranular.dicoV2M[text]
        self.mdl.setGranularModel(self.currentid, model)

    @pyqtSlot(str)
    def slotKinetic(self, text):
        """
        INPUT type for choice of kinetic model
        """
        model = self.modelKinetic.dicoV2M[text]
        self.mdl.setKineticModel(self.currentid, model)

    @pyqtSlot(str)
    def slotCompaction(self, var):
        """
        """
        if self.lineEditCompaction.validator().state == QValidator.Acceptable:
            value = from_qvariant(var, float)
            self.mdl.setCompaction(value)

    def initializeVariables(self, fieldId):
        """
        Initialize variables when a new fieldId is choosen
        """
        self.labelNoParticles.hide()

        value = self.mdl.getCompaction()
        self.lineEditCompaction.setText(str(value))

        model = self.mdl.getFrictionModel(fieldId)
        self.modelFriction.setItem(str_model=model)

        model = self.mdl.getGranularModel(fieldId)
        self.modelGranular.setItem(str_model=model)

        model = self.mdl.getKineticModel(fieldId)
        self.modelKinetic.setItem(str_model=model)

        if self.mdl.getTurbulenceModel(fieldId) == "q2-q12":
            self.labelCoupling.show()
            self.checkBoxCoupling.show()

            isCoupling = self.mdl.getCouplingStatus(fieldId) == "on"
            self.checkBoxCoupling.setChecked(isCoupling)

        else:
            self.labelCoupling.hide()
            self.checkBoxCoupling.hide()

    @pyqtSlot(bool)
    def slotCoupling(self, checked):
        """
        check box for polydispersed coupling
        """
        status = 'off'
        if checked:
            status = 'on'
        self.mdl.setCouplingStatus(self.currentid, status)
class InterfacialEnthalpyView(QWidget, Ui_InterfacialEnthalpy):
    """
    InterfacialEnthalpyView layout.
    """
    def __init__(self, parent, case):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_InterfacialEnthalpy.__init__(self)
        self.setupUi(self)

        self.case = case
        self.case.undoStopGlobal()
        self.mdl = InterfacialEnthalpyModel(self.case)

        # Combo models
        liquid_vapor_couples = self.mdl.getLiquidVaporCouples()
        self.modelLiquidVaporFields = ComboModel(
            self.comboBoxLiquidVaporFields, 1, 1)
        self.modelLiquidVaporFields.addItem("None", "none")
        for id_pair in liquid_vapor_couples:
            field_descriptions = []
            for id in id_pair:
                name = self.mdl.getLabel(id)
                phase = self.mdl.getFieldNature(id)
                criterion = self.mdl.getCriterion(id)
                field_descriptions.append("{0} ({1} {2})".format(
                    name, criterion, phase))
            # Display fields as "Field1 (continuous liquid) / Field2 (dispersed gas)"
            view = self.tr(" / ".join(field_descriptions))
            model = "{0}_{1}".format(*id_pair)
            self.modelLiquidVaporFields.addItem(view, model)

        self.modelPonderationCoefFielda = ComboModel(
            self.comboBoxPonderationCoefFielda, 3, 1)
        self.modelPonderationCoefFielda.addItem(self.tr("alp1"), "alp1")
        self.modelPonderationCoefFielda.addItem(self.tr("alp2"), "alp2")
        self.modelPonderationCoefFielda.addItem(self.tr("alp1*alp2"),
                                                "alp1_alp2")

        self.modelPonderationCoefFieldb = ComboModel(
            self.comboBoxPonderationCoefFieldb, 3, 1)
        self.modelPonderationCoefFieldb.addItem(self.tr("alp1"), "alp1")
        self.modelPonderationCoefFieldb.addItem(self.tr("alp2"), "alp2")
        self.modelPonderationCoefFieldb.addItem(self.tr("alp1*alp2"),
                                                "alp1_alp2")

        self.modelSolidEnergyTransfer = ComboModel(
            self.comboBoxSolidEnergyTransfer, 2, 1)
        self.modelSolidEnergyTransfer.addItem(self.tr("none"), "none")
        self.modelSolidEnergyTransfer.addItem(self.tr("gas-particle"),
                                              "gas_particule")

        self.modelFieldaModel = ComboModel(self.comboBoxFieldaModel, 1, 1)
        self.modelFieldaModel.addItem(self.tr("No source term"),
                                      "no_source_term")
        self.modelFieldaModel.addItem(
            self.tr("Relaxation time : alphk.rok.cpk.(Ts-Tk)/tauk"),
            "relaxation_time")
        self.modelFieldbModel = ComboModel(self.comboBoxFieldbModel, 1, 1)
        self.modelFieldbModel.addItem(self.tr("No source term"),
                                      "no_source_term")
        self.modelFieldbModel.addItem(
            self.tr("Relaxation time : alphk.rok.cpk.(Ts-Tk)/tauk"),
            "relaxation_time")

        self.groupBoxLiquidVaporModel.hide()
        self.groupBoxSolidEnergyTransfer.hide()
        if (len(self.mdl.getSolidFieldIdList()) > 0):
            model = self.mdl.getSolidEnergyTransfer()
            self.modelSolidEnergyTransfer.setItem(str_model=model)
            self.groupBoxSolidEnergyTransfer.show()
            self.groupBoxEnergyTransfer.hide()

        self.setValidators()
        self.setConnections()

        # Initial state of Pool boiling model
        if self.mdl.getPoolBoiling() == 'on':
            self.checkBoxActivatePool.setChecked(True)

        # Initialize pair of fields
        predefined_flow = self.mdl.getPredefinedFlow()
        if predefined_flow == "None":
            if self.mdl.getEnthalpyCoupleFieldId() is None:
                self.modelLiquidVaporFields.setItem(str_model="none")
            else:
                field_id_a, field_id_b = self.mdl.getEnthalpyCoupleFieldId()
                model = "{0}_{1}".format(field_id_a, field_id_b)
                self.modelLiquidVaporFields.setItem(str_model=model)
        elif predefined_flow == "free_surface":
            self.lockFreeSurfaceOptions()
        elif predefined_flow == "boiling_flow":
            self.lockBubblyFlowOptions()
        elif predefined_flow == "droplet_flow":
            self.lockDropletFlowOptions()
        elif predefined_flow == "particles_flow":
            # self.lockParticlesFlowOptions()
            # TODO check if options should be locked or not
            pass
        elif predefined_flow == "multiregime":
            self.lockMultiregimeFlowOptions()

        self.case.undoStartGlobal()

    def lockMultiregimeFlowOptions(self):
        self.modelLiquidVaporFields.setItem(str_model="1_2")
        self.modelFieldaModel.setItem(str_model="wall_law_type_model")
        self.modelFieldbModel.setItem(str_model="sublayer_LI3C")
        self.comboBoxLiquidVaporFields.setEnabled(False)
        self.comboBoxFieldaModel.setEnabled(False)
        self.comboBoxFieldbModel.setEnabled(False)

    def lockParticlesFlowOptions(self):
        self.modelSolidEnergyTransfer.setItem(str_model="gas_particule")
        self.comboBoxSolidEnergyTransfer.setEnabled(False)

    def lockDropletFlowOptions(self):
        self.modelLiquidVaporFields.setItem(str_model="1_2")
        self.modelFieldaModel.setItem(str_model="droplet_model_for_vapour")
        self.modelFieldbModel.setItem(str_model="droplet_model_for_liquid")
        self.comboBoxLiquidVaporFields.setEnabled(False)
        self.comboBoxFieldaModel.setEnabled(False)
        self.comboBoxFieldbModel.setEnabled(False)

    def lockBubblyFlowOptions(self):
        self.modelLiquidVaporFields.setItem(str_model="1_2")
        self.modelFieldaModel.setItem(str_model="bubble_model_for_liquid")
        self.modelFieldbModel.setItem(str_model="relaxation_time_subcooled")
        self.comboBoxLiquidVaporFields.setEnabled(False)
        self.comboBoxFieldaModel.setEnabled(False)
        self.comboBoxFieldbModel.setEnabled(False)

    def lockFreeSurfaceOptions(self):
        self.modelLiquidVaporFields.setItem(str_model="1_2")
        self.modelFieldaModel.setItem(str_model="wall_law_type_model")
        self.modelFieldbModel.setItem(str_model="sublayer_LI3C")
        self.comboBoxLiquidVaporFields.setEnabled(False)
        self.comboBoxFieldaModel.setEnabled(False)
        self.comboBoxFieldbModel.setEnabled(False)

    def setValidators(self):
        validatorRelaxa = DoubleValidator(self.lineEditRelaxationTimeFielda,
                                          min=0.0)
        validatorRelaxb = DoubleValidator(self.lineEditRelaxationTimeFieldb,
                                          min=0.0)
        self.lineEditRelaxationTimeFielda.setValidator(validatorRelaxa)
        self.lineEditRelaxationTimeFieldb.setValidator(validatorRelaxb)

    def setConnections(self):
        self.comboBoxLiquidVaporFields.currentTextChanged[str].connect(
            self.slotSelectInteraction)
        self.comboBoxSolidEnergyTransfer.currentTextChanged[str].connect(
            self.slotSolidEnergyTransfer)
        self.comboBoxFieldaModel.currentTextChanged[str].connect(
            self.slotFieldaModel)
        self.comboBoxPonderationCoefFielda.activated[str].connect(
            self.slotPonderationCoefFielda)
        self.comboBoxFieldbModel.currentTextChanged[str].connect(
            self.slotFieldbModel)
        self.comboBoxPonderationCoefFieldb.activated[str].connect(
            self.slotPonderationCoefFieldb)
        self.lineEditRelaxationTimeFielda.textChanged[str].connect(
            self.slotRelaxationTimeFielda)
        self.lineEditRelaxationTimeFieldb.textChanged[str].connect(
            self.slotRelaxationTimeFieldb)
        self.checkBoxActivatePool.stateChanged.connect(
            self.slotPoolBoilingModel)

    @pyqtSlot(str)
    def slotSelectInteraction(self, value):
        """
        Select a Field in the QTable
        """
        selection = self.modelLiquidVaporFields.dicoV2M[value]
        if selection == "none":
            self.groupBoxLiquidVaporModel.hide()
            self.mdl.deleteLiquidVaporEnthalpyTransfer()
            return
        fieldaId, fieldbId = selection.split("_")
        if self.mdl.getEnthalpyCoupleFieldId() is None:
            self.mdl.addLiquidVaporEnthalpyTransfer(fieldaId, fieldbId)
        self.mdl.setEnthalpyCoupleFieldId(fieldaId, fieldbId)
        self.updateLiquidVaporModel()
        self.groupBoxLiquidVaporModel.show()
        ifm = InterfacialForcesModel(self.case)

        if len(NonCondensableModel(self.case).getNonCondensableLabelList()) > 0 \
                and ifm.getContinuousCouplingModel(fieldaId, fieldbId) in \
                ifm.getAvailableContinuousDragModelList():
            self.checkBoxActivatePool.show()
        else:
예제 #23
0
class GlobalNumericalParametersView(QWidget, Ui_GlobalNumericalParameters):
    """
    Global numerical parameters layout.
    """
    def __init__(self, parent, case):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_GlobalNumericalParameters.__init__(self)
        self.setupUi(self)

        self.case = case
        self.case.undoStopGlobal()
        self.mdl = GlobalNumericalParametersModel(self.case)

        # Combo model
        self.modelVelocityAlgorithm = ComboModel(
            self.comboBoxVelocityAlgorithm, 3, 1)
        self.modelVelocityAlgorithm.addItem(self.tr("Standard"),
                                            "standard_difvit")
        self.modelVelocityAlgorithm.addItem(self.tr("Coupled"),
                                            "coupled_difvitc")
        self.modelVelocityAlgorithm.addItem(
            self.tr("Mean velocity - relative velocity"),
            "mean_velocity_relative_velocity")

        mfm = MainFieldsModel(self.case)
        if len(mfm.getFieldIdList()) < 2:
            self.modelVelocityAlgorithm.disableItem(2)
        else:
            self.modelVelocityAlgorithm.enableItem(2)

        # Validator
        validatorMaxRestart = IntValidator(self.lineEditMaxRestart, min=0)
        validatorSplitting = DoubleValidator(self.lineEditTimeSplitting,
                                             min=0.)
        validatorPRelax = DoubleValidator(self.lineEditPressureRelaxation,
                                          min=0.)
        validatorMinP = DoubleValidator(self.lineEditMinimumPressure)
        validatorMaxP = DoubleValidator(self.lineEditMaximumPressure)

        validatorMaxRestart.setExclusiveMin(False)
        validatorSplitting.setExclusiveMin(True)
        validatorPRelax.setExclusiveMin(True)

        self.lineEditMaxRestart.setValidator(validatorMaxRestart)
        self.lineEditTimeSplitting.setValidator(validatorSplitting)
        self.lineEditPressureRelaxation.setValidator(validatorPRelax)
        self.lineEditMinimumPressure.setValidator(validatorMinP)
        self.lineEditMaximumPressure.setValidator(validatorMaxP)

        # Connections
        self.checkBoxRestart.clicked.connect(self.slotRestart)
        self.checkBoxPotentialState.clicked.connect(self.slotPotentialState)
        self.checkBoxFacesReconstruction.clicked.connect(
            self.slotFacesReconstruction)
        self.checkBoxMultigrid.clicked.connect(self.slotMultigrid)
        self.lineEditMinimumPressure.textChanged[str].connect(
            self.slotMinimumPressure)
        self.lineEditMaximumPressure.textChanged[str].connect(
            self.slotMaximumPressure)
        self.pushButtonAdvanced.clicked.connect(self.slotAdvancedOptions)
        self.lineEditMaxRestart.textChanged[str].connect(self.slotMaxRestart)
        self.lineEditTimeSplitting.textChanged[str].connect(
            self.slotTimeSplitting)
        self.lineEditPressureRelaxation.textChanged[str].connect(
            self.slotPressureRelaxation)
        self.checkBoxUpwindAlphaEnergy.clicked.connect(
            self.slotUpwindAlphaEnergy)
        self.checkBoxStopRestart.clicked.connect(self.slotStopRestart)
        self.comboBoxVelocityAlgorithm.activated[str].connect(
            self.slotVelocityAlgorithm)

        self.checkBoxRegulBadCells.clicked.connect(self.slotRegulateBadCells)

        # Initialize widget
        status = self.mdl.getRestartTimeStep()
        if status == 'on':
            self.checkBoxRestart.setChecked(1)
            self.groupBoxRestartOption.show()

            value = self.mdl.getMaxNumberOfRestart()
            self.lineEditMaxRestart.setText(str(value))
            value = self.mdl.getTimeSplit()
            self.lineEditTimeSplitting.setText(str(value))
            value = self.mdl.getPressureRelaxation()
            self.lineEditPressureRelaxation.setText(str(value))
            status = self.mdl.getUpwindScheme()
            if status == 'on':
                self.checkBoxUpwindAlphaEnergy.setChecked(True)
            else:
                self.checkBoxUpwindAlphaEnergy.setChecked(False)
            status = self.mdl.getStopNoConvergence()
            if status == 'on':
                self.checkBoxStopRestart.setChecked(True)
            else:
                self.checkBoxStopRestart.setChecked(False)
        else:
            self.checkBoxRestart.setChecked(0)
            self.groupBoxRestartOption.hide()

        is_compressible = False
        for fid in mfm.getFieldIdList():
            if mfm.getCompressibleStatus(int(fid)) == 'on':
                is_compressible = True
                break

        if is_compressible:
            self.mdl.setPotentielState('off')
            self.checkBoxPotentialState.setChecked(0)
            self.checkBoxPotentialState.setEnabled(False)
        else:
            status = self.mdl.getPotentielState()
            if status == 'on':
                self.checkBoxPotentialState.setChecked(1)
            else:
                self.checkBoxPotentialState.setChecked(0)

        status = self.mdl.getFacesReconstruction()
        if status == 'on':
            self.checkBoxFacesReconstruction.setChecked(1)
        else:
            self.checkBoxFacesReconstruction.setChecked(0)

        status = self.mdl.getRegulateBadCElls()
        self.checkBoxRegulBadCells.setChecked(status == 'on')

        status = self.mdl.getMultigridStatus()
        if status == 'on':
            self.checkBoxMultigrid.setChecked(1)
        else:
            self.checkBoxMultigrid.setChecked(0)

        value = self.mdl.getMinPressure()
        self.lineEditMinimumPressure.setText(str(value))
        value = self.mdl.getMaxPressure()
        self.lineEditMaximumPressure.setText(str(value))

        model = self.mdl.getVelocityPredictorAlgo()
        self.modelVelocityAlgorithm.setItem(str_model=model)

        self.case.undoStartGlobal()

        predefined_flow = MainFieldsModel(self.case).getPredefinedFlow()
        if predefined_flow in ["free_surface", "droplet_flow", "multiregime"]:
            self.modelVelocityAlgorithm.setItem(str_model="coupled_difvitc")
            self.comboBoxVelocityAlgorithm.setEnabled(False)
        elif predefined_flow == "boiling_flow":
            self.modelVelocityAlgorithm.setItem(
                str_model="mean_velocity_relative_velocity")
            self.comboBoxVelocityAlgorithm.setEnabled(False)

    @pyqtSlot()
    def slotRestart(self):
        """
        Input if restart time step if not converged
        """
        if self.checkBoxRestart.isChecked():
            self.mdl.setRestartTimeStep('on')
            self.groupBoxRestartOption.show()

            value = self.mdl.getMaxNumberOfRestart()
            self.lineEditMaxRestart.setText(str(value))
            value = self.mdl.getTimeSplit()
            self.lineEditTimeSplitting.setText(str(value))
            value = self.mdl.getPressureRelaxation()
            self.lineEditPressureRelaxation.setText(str(value))
            status = self.mdl.getUpwindScheme()
            if status == 'on':
                self.checkBoxUpwindAlphaEnergy.setChecked(True)
            else:
                self.checkBoxUpwindAlphaEnergy.setChecked(False)
            status = self.mdl.getStopNoConvergence()
            if status == 'on':
                self.checkBoxStopRestart.setChecked(True)
            else:
                self.checkBoxStopRestart.setChecked(False)
        else:
            self.mdl.setRestartTimeStep('off')
            self.groupBoxRestartOption.hide()

    @pyqtSlot()
    def slotPotentialState(self):
        """
        Input if restart time step if not converged
        """
        if self.checkBoxPotentialState.isChecked():
            self.mdl.setPotentielState('on')
        else:
            self.mdl.setPotentielState('off')

    @pyqtSlot()
    def slotFacesReconstruction(self):
        """
        Input if faces reconstruction
        """
        if self.checkBoxFacesReconstruction.isChecked():
            self.mdl.setFacesReconstruction('on')
            self.checkBoxFacesReconstruction.setChecked(1)
        else:
            self.mdl.setFacesReconstruction('off')

    @pyqtSlot()
    def slotMultigrid(self):
        """
        Input if multigrid for pressure
        """
        if self.checkBoxMultigrid.isChecked():
            self.mdl.setMultigridStatus('on')
        else:
            self.mdl.setMultigridStatus('off')

    @pyqtSlot(str)
    def slotMinimumPressure(self, text):
        """
        Input value of minimum pressure
        """
        if self.lineEditMinimumPressure.validator(
        ).state == QValidator.Acceptable:
            value = from_qvariant(text, float)
            self.mdl.setMinPressure(value)

    @pyqtSlot(str)
    def slotMaximumPressure(self, text):
        """
        Input value of maximum pressure
        """
        if self.lineEditMaximumPressure.validator(
        ).state == QValidator.Acceptable:
            value = from_qvariant(text, float)
            self.mdl.setMaxPressure(value)

    @pyqtSlot()
    def slotAdvancedOptions(self):
        """
        Ask one popup for advanced specifications
        """
        default = {}
        default['velocity_update'] = self.mdl.getVelocityUpdate()
        default['pressure_symetrisation'] = self.mdl.getPressureSymetrisation()
        default['pressure_gradient'] = self.mdl.getPressureGradient()
        default['max_sum_alpha'] = self.mdl.getSumAlpha()
        default['alpha_p_cycle'] = self.mdl.getAlphaPressureCycles()
        log.debug("slotAdvancedOptions -> %s" % str(default))

        dialog = GlobalNumericalParametersAdvancedOptionsDialogView(
            self, self.case, default)
        if dialog.exec_():
            result = dialog.get_result()
            log.debug("slotAdvancedOptions -> %s" % str(result))
            self.mdl.setVelocityUpdate(result['velocity_update'])
            self.mdl.setPressureSymetrisation(result['pressure_symetrisation'])
            self.mdl.setPressureGradient(result['pressure_gradient'])
            self.mdl.setSumAlpha(result['max_sum_alpha'])
            self.mdl.setAlphaPressureCycles(result['alpha_p_cycle'])

    @pyqtSlot(str)
    def slotMaxRestart(self, text):
        """
        Input value of Maximum number of restart
        """
        if self.lineEditMaxRestart.validator().state == QValidator.Acceptable:
            value = from_qvariant(text, int)
            self.mdl.setMaxNumberOfRestart(value)

    @pyqtSlot(str)
    def slotTimeSplitting(self, text):
        """
        Input value of time-step splitting
        """
        if self.lineEditTimeSplitting.validator(
        ).state == QValidator.Acceptable:
            value = from_qvariant(text, float)
            self.mdl.setTimeSplit(value)

    @pyqtSlot(str)
    def slotPressureRelaxation(self, text):
        """
        Input value of pressure increment relaxation
        """
        if self.lineEditPressureRelaxation.validator(
        ).state == QValidator.Acceptable:
            value = from_qvariant(text, float)
            self.mdl.setPressureRelaxation(value)

    @pyqtSlot()
    def slotUpwindAlphaEnergy(self):
        """
        Input if upwind scheme for mass and energy
        """
        if self.checkBoxUpwindAlphaEnergy.isChecked():
            self.mdl.setUpwindScheme('on')
        else:
            self.mdl.setUpwindScheme('off')

    @pyqtSlot()
    def slotStopRestart(self):
        """
        Input if stop if no convergence
        """
        if self.checkBoxStopRestart.isChecked():
            self.mdl.setStopNoConvergence('on')
        else:
            self.mdl.setStopNoConvergence('off')

    @pyqtSlot(str)
    def slotVelocityAlgorithm(self, text):
        """
        Input velocity algorithm model
        """
        model = self.modelVelocityAlgorithm.dicoV2M[str(text)]
        self.mdl.setVelocityPredictorAlgo(model)

    @pyqtSlot()
    def slotRegulateBadCells(self):
        """
        Activate bad cells regulations.
        """
        if self.checkBoxRegulBadCells.isChecked():
            self.mdl.setRegulateBadCells('on')
        else:
            self.mdl.setRegulateBadCells('off')
예제 #24
0
class GroundwaterView(QWidget, Ui_GroundwaterForm):
    """
    Class to open Page.
    """
    def __init__(self, parent, case):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_GroundwaterForm.__init__(self)
        self.setupUi(self)

        self.case = case
        self.case.undoStopGlobal()
        self.mdl = GroundwaterModel(self.case)

        self.list_scalars = []
        self.m_sca = DefineUserScalarsModel(self.case)
        for s in self.m_sca.getUserScalarNameList():
            self.list_scalars.append((s, self.tr("Additional scalar")))

        # ComboBox
        self.modelPermeability = ComboModel(self.comboBoxPermeability,2,1)
        self.modelFlowType = ComboModel(self.comboBoxFlowType,2,1)
        self.modelUnsaturated = ComboModel(self.comboBoxUnsaturated,2,1)
        self.modelChemistryModel = ComboModel(self.comboBoxChemistryModel,2,1)
        self.modelSpeciesName = ComboModel(self.comboBoxSpeciesName,1,1)

        self.modelPermeability.addItem(self.tr("isotropic"), 'isotropic')
        self.modelPermeability.addItem(self.tr("anisotropic"), 'anisotropic')
        self.modelFlowType.addItem(self.tr("steady"), 'steady')
        self.modelFlowType.addItem(self.tr("unsteady"), 'unsteady')
        self.modelUnsaturated.addItem(self.tr("True"), 'true')
        self.modelUnsaturated.addItem(self.tr("False"), 'false')
        self.modelChemistryModel.addItem(self.tr("Kd"), 'Kd')
        self.modelChemistryModel.addItem(self.tr("EK"), 'EK')

        self.scalar = ""
        scalar_list = self.m_sca.getUserScalarNameList()
        for s in self.m_sca.getScalarsVarianceList():
            if s in scalar_list: scalar_list.remove(s)

        if scalar_list != []:
            self.scalar = scalar_list[0]
            for scalar in scalar_list:
                self.modelSpeciesName.addItem(scalar)
        else:
            self.groupBoxTransport.hide()

        # Set up validators
        self.lineEditDecayRate.setValidator(DoubleValidator(self.lineEditDecayRate))

        # Connections
        self.comboBoxPermeability.activated[str].connect(self.slotPermeabilityType)
        self.comboBoxFlowType.activated[str].connect(self.slotFlowType)
        self.comboBoxUnsaturated.activated[str].connect(self.slotUnsaturated)
        self.checkBoxGravity.clicked.connect(self.slotGravity)
        self.comboBoxChemistryModel.activated[str].connect(self.slotChemistryModel)
        self.comboBoxSpeciesName.activated[str].connect(self.slotSpeciesName)
        self.lineEditDecayRate.textChanged[str].connect(self.slotDecayRate)

        self.initializeWidget(scalar_list)

        self.case.undoStartGlobal()


    @pyqtSlot()
    def initializeWidget(self, scalar_list):
        """
        """
        value = self.mdl.getPermeabilityType()
        self.modelPermeability.setItem(str_model=value)

        value = self.mdl.getFlowType()
        self.modelFlowType.setItem(str_model=value)

        value = self.mdl.getUnsaturatedZone()
        self.modelUnsaturated.setItem(str_model=value)

        if self.mdl.getGravity() == 'on':
            self.checkBoxGravity.setChecked(True)
        else:
            self.checkBoxGravity.setChecked(False)

        if scalar_list != []:
            value = self.mdl.getDecayRate(self.scalar)
            self.lineEditDecayRate.setText(str(value))
            value = self.mdl.getChemistryModel(self.scalar)
            self.modelChemistryModel.setItem(str_model=value)


    @pyqtSlot(str)
    def slotPermeabilityType(self, text):
        """
        Input permeability type : isotrop or anisotrop.
        """
        mdl = self.modelPermeability.dicoV2M[str(text)]
        self.mdl.setPermeabilityType(mdl)


    @pyqtSlot(str)
    def slotFlowType(self, text):
        """
        Input flow type : steady or unsteady.
        """
        mdl = self.modelFlowType.dicoV2M[str(text)]
        self.mdl.setFlowType(mdl)


    @pyqtSlot(str)
    def slotUnsaturated(self, text):
        """
        Input flow type : steady or unsteady.
        """
        mdl = self.modelUnsaturated.dicoV2M[str(text)]
        self.mdl.setUnsaturatedZone(mdl)


    @pyqtSlot()
    def slotGravity(self):
        """
        Input if gravity is taken into account or not
        """
        if self.checkBoxGravity.isChecked():
            self.mdl.setGravity('on')
        else:
            self.mdl.setGravity('off')


    @pyqtSlot(str)
    def slotSpeciesName(self, text):
        """
        Method to choose the scalar which properties shall be changed
        """
        mdl = self.modelSpeciesName.dicoV2M[str(text)]
        self.scalar = str(text)
        scal = self.scalar
        value = self.mdl.getDecayRate(scal)
        self.lineEditDecayRate.setText(str(value))
        value = self.mdl.getChemistryModel(scal)
        self.modelChemistryModel.setItem(str_model=value)


    @pyqtSlot(str)
    def slotChemistryModel(self, text):
        """
        Input chemistry model for soil-water partition : Kd or EK.
        """
        choice = self.modelChemistryModel.dicoV2M[str(text)]
        scal = self.scalar
        self.mdl.setChemistryModel(scal, choice)


    @pyqtSlot(str)
    def slotDecayRate(self, text):
        """
        """
        if self.lineEditDecayRate.validator().state == QValidator.Acceptable:
            val = float(text)
            scal = self.scalar
            self.mdl.setDecayRate(scal, val)
class BoundaryConditionsCoalInletView(QWidget,
                                      Ui_BoundaryConditionsCoalInletForm):
    def __init__(self, parent):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_BoundaryConditionsCoalInletForm.__init__(self)
        self.setupUi(self)

    def setup(self, case):
        """
        Setup the widget
        """
        self.case = case
        self.__boundary = None

        self.case.undoStopGlobal()
        self.notebook = NotebookModel(self.case)

        # Connections
        self.comboBoxTypeInlet.activated[str].connect(self.__slotInletType)
        self.comboBoxVelocity.activated[str].connect(self.__slotChoiceVelocity)
        self.lineEditVelocity.textChanged[str].connect(
            self.__slotVelocityValue)
        self.lineEditTemperature.textChanged[str].connect(
            self.__slotTemperature)
        self.spinBoxOxydantNumber.valueChanged[int].connect(
            self.__slotOxydantNumber)

        self.comboBoxDirection.activated[str].connect(
            self.__slotChoiceDirection)
        self.lineEditDirectionX.textChanged[str].connect(self.__slotDirX)
        self.lineEditDirectionY.textChanged[str].connect(self.__slotDirY)
        self.lineEditDirectionZ.textChanged[str].connect(self.__slotDirZ)

        # Combo models
        self.modelTypeInlet = ComboModel(self.comboBoxTypeInlet, 2, 1)
        self.modelTypeInlet.addItem(self.tr("only oxydant"), 'oxydantFlow')
        self.modelTypeInlet.addItem(self.tr("oxydant and coal"), 'coalFlow')

        self.modelVelocity = ComboModel(self.comboBoxVelocity, 4, 1)
        self.modelVelocity.addItem(self.tr("norm"), 'norm')
        self.modelVelocity.addItem(self.tr("mass flow rate"), 'flow1')
        self.modelVelocity.addItem(self.tr("norm (user law)"), 'norm_formula')
        self.modelVelocity.addItem(self.tr("mass flow rate (user law)"),
                                   'flow1_formula')

        self.modelDirection = ComboModel(self.comboBoxDirection, 3, 1)
        self.modelDirection.addItem(self.tr("normal to the inlet"), 'normal')
        self.modelDirection.addItem(self.tr("specified coordinates"),
                                    'coordinates')
        self.modelDirection.addItem(self.tr("user profile"), 'formula')

        # Validators
        validatorVelocity = DoubleValidator(self.lineEditVelocity)
        validatorX = DoubleValidator(self.lineEditDirectionX)
        validatorY = DoubleValidator(self.lineEditDirectionY)
        validatorZ = DoubleValidator(self.lineEditDirectionZ)
        validatorTemp = DoubleValidator(self.lineEditTemperature, min=0.)

        # Apply validators
        self.lineEditVelocity.setValidator(validatorVelocity)
        self.lineEditDirectionX.setValidator(validatorX)
        self.lineEditDirectionY.setValidator(validatorY)
        self.lineEditDirectionZ.setValidator(validatorZ)
        self.lineEditTemperature.setValidator(validatorTemp)

        self.pushButtonVelocityFormula.clicked.connect(
            self.__slotVelocityFormula)
        self.pushButtonDirectionFormula.clicked.connect(
            self.__slotDirectionFormula)

        # Useful information about coals, classes, and ratios

        mdl = CoalCombustionModel.CoalCombustionModel(self.case)
        if mdl.getCoalCombustionModel() != "off":
            self.__coalNumber = mdl.getCoalNumber()
            self.__coalClassesNumber = []
            for coal in range(0, self.__coalNumber):
                self.__coalClassesNumber.append(
                    mdl.getClassNumber(str(coal + 1)))
            self.__maxOxydantNumber = mdl.getOxidantNumber()
        else:
            self.__coalNumber = 0
            self.__coalClassesNumber = [0]
            self.__maxOxydantNumber = 1

        self.__ratio = self.__coalNumber * [0]
        for i in range(0, self.__coalNumber):
            self.__ratio[i] = self.__coalClassesNumber[i] * [0]

        # Coal table

        self.__modelCoal = StandardItemModelCoal(self.case)
        self.tableViewCoal.setModel(self.__modelCoal)
        delegateValue = FloatDelegate(self.tableViewCoal, minVal=0.)
        self.tableViewCoal.setItemDelegateForColumn(1, delegateValue)
        self.tableViewCoal.setItemDelegateForColumn(2, delegateValue)

        # Coal mass ratio table

        self.__modelCoalMass = StandardItemModelCoalMass(
            self.case, self.__coalNumber, self.__coalClassesNumber)
        self.tableViewCoalMass.setModel(self.__modelCoalMass)

        delegateValueMass = FloatDelegate(self.tableViewCoalMass, minVal=0.)
        for c in range(self.__modelCoalMass.columnCount()):
            self.tableViewCoalMass.setItemDelegateForColumn(
                c, delegateValueMass)

        self.case.undoStartGlobal()

    def showWidget(self, b):
        """
        Show the widget
        """
        label = b.getLabel()
        self.__boundary = Boundary('coal_inlet', label, self.case)

        # Initialize velocity
        choice = self.__boundary.getVelocityChoice()
        self.modelVelocity.setItem(str_model=choice)
        self.__updateLabel()

        if choice[-7:] == "formula":
            self.pushButtonVelocityFormula.setEnabled(True)
            self.lineEditVelocity.setEnabled(False)
        else:
            self.pushButtonVelocityFormula.setEnabled(False)
            self.lineEditVelocity.setEnabled(True)
            v = self.__boundary.getVelocity()
            self.lineEditVelocity.setText(str(v))

        # Initialize oxydant and temperature
        self.spinBoxOxydantNumber.setMaximum(self.__maxOxydantNumber)
        o = self.__boundary.getOxydantNumber()
        self.spinBoxOxydantNumber.setValue(o)
        t = self.__boundary.getOxydantTemperature()
        self.lineEditTemperature.setText(str(t))

        # Initialize direction
        choice = self.__boundary.getDirectionChoice()
        self.modelDirection.setItem(str_model=choice)
        text = self.modelDirection.dicoM2V[choice]
        if choice == "formula":
            self.pushButtonDirectionFormula.setEnabled(True)
            self.frameDirectionCoordinates.hide()
        elif choice == "coordinates":
            self.pushButtonDirectionFormula.setEnabled(False)
            self.frameDirectionCoordinates.show()
            v = self.__boundary.getDirection('direction_x')
            self.lineEditDirectionX.setText(str(v))
            v = self.__boundary.getDirection('direction_y')
            self.lineEditDirectionY.setText(str(v))
            v = self.__boundary.getDirection('direction_z')
            self.lineEditDirectionZ.setText(str(v))
        elif choice == "normal":
            self.pushButtonDirectionFormula.setEnabled(False)
            self.frameDirectionCoordinates.hide()

        log.debug("showWidget:inlet type: %s " %
                  self.__boundary.getInletType())
        if self.__boundary.getInletType() == "coalFlow":
            self.modelTypeInlet.setItem(str_model="coalFlow")
            self.groupBoxCoal.show()
            self.groupBoxCoalMass.show()
            self.__updateTables()
            self.__boundary.setInletType("coalFlow")
        else:
            self.__boundary.setInletType("oxydantFlow")
            self.modelTypeInlet.setItem(str_model="oxydantFlow")
            self.groupBoxCoal.hide()
            self.groupBoxCoalMass.hide()

        self.show()

    def hideWidget(self):
        """
        Hide all
        """
        self.hide()

    def __updateTables(self):
        """
        Insert rows in the two QTableView.
        """
        # clean the QTableView
        self.__modelCoal.deleteAll()
        self.__modelCoalMass.deleteAll()

        label = self.__boundary.getLabel()
        self.__modelCoalMass.setBoundaryFromLabel(label)
        self.__modelCoal.setBoundaryFromLabel(label)

        # fill the flow and temperature of the coal
        for coal in range(0, self.__coalNumber):
            self.__modelCoal.insertItem(
                self.tr("Coal ") + " " + str(coal + 1),
                self.__boundary.getCoalFlow(coal),
                self.__boundary.getCoalTemperature(coal))

        # fill the ratio of mass for each class for each coal
        for coal in range(0, self.__coalNumber):
            lastValue = 0.
            for coalClass in range(0, self.__coalClassesNumber[coal] - 1):
                lst = self.__boundary.getCoalRatios(coal)
                lastValue += lst[coalClass]
                self.__ratio[coal][coalClass] = lst[coalClass]

            # last class is computed in order to assure that sum is egal to 100%
            coalClass = self.__coalClassesNumber[coal] - 1
            lastValue = 100 - lastValue
            self.__ratio[coal][coalClass] = lastValue

        self.__modelCoalMass.setRatio(self.__ratio)

    @pyqtSlot(str)
    def __slotChoiceVelocity(self, text):
        """
        Private slot.

        Input the velocity boundary type choice (norm, ).

        @type text: C{QString}
        @param text: velocity boundary type choice.
        """
        c = self.modelVelocity.dicoV2M[str(text)]
        log.debug("slotChoiceVelocity: %s " % c)
        self.__boundary.setVelocityChoice(c)

        if c[-7:] == "formula":
            self.pushButtonVelocityFormula.setEnabled(True)
            exp = self.__boundary.getVelocity()
            if exp:
                self.pushButtonVelocityFormula.setStyleSheet(
                    "background-color: green")
                self.pushButtonVelocityFormula.setToolTip(exp)
            else:
                self.pushButtonVelocityFormula.setStyleSheet(
                    "background-color: red")
            self.lineEditVelocity.setEnabled(False)
            self.lineEditVelocity.setText("")
        else:
            self.pushButtonVelocityFormula.setEnabled(False)
            self.pushButtonVelocityFormula.setStyleSheet(
                "background-color: None")
            self.lineEditVelocity.setEnabled(True)
            v = self.__boundary.getVelocity()
            self.lineEditVelocity.setText(str(v))

        self.__updateLabel()

    def __updateLabel(self):
        """
        Update the unit for the velocity specification.
        """
        c = self.__boundary.getVelocityChoice()
        if c in ('norm', 'norm_formula'):
            self.labelUnitVelocity.setText(str('m/s'))
        elif c in ('flow1', 'flow1_formula'):
            self.labelUnitVelocity.setText(str('kg/s'))
        elif c in ('flow2', 'flow2_formula'):
            self.labelUnitVelocity.setText(str('m<sup>3</sup>/s'))

    @pyqtSlot(str)
    def __slotVelocityValue(self, text):
        """
        Private slot.

        New value associated to the velocity boundary type.

        @type text: C{QString}
        @param text: value
        """
        if self.sender().validator().state == QValidator.Acceptable:
            v = from_qvariant(text, float)
            self.__boundary.setVelocity(v)

    @pyqtSlot()
    def __slotVelocityFormula(self):
        """
        """
        exp = self.__boundary.getVelocity()
        c = self.__boundary.getVelocityChoice()
        if c == 'norm_formula':
            exa = "u_norm = 1.0;"
            req = [('u_norm', 'Norm of the velocity')]
        elif c == 'flow1_formula':
            exa = "q_m = 1.0;"
            req = [('q_m', 'mass flow rate')]
        elif c == 'flow2_formula':
            exa = "q_v = 1.0;"
            req = [('q_v', 'volumic flow rate')]

        sym = [('x', "X face's gravity center"),
               ('y', "Y face's gravity center"),
               ('z', "Z face's gravity center"), ('dt', 'time step'),
               ('t', 'current time'), ('iter', 'number of iteration'),
               ('surface', 'Boundary zone surface')]

        for (nme, val) in self.notebook.getNotebookList():
            sym.append((nme, 'value (notebook) = ' + str(val)))

        dialog = QMegEditorView(parent=self,
                                function_type='bnd',
                                zone_name=self.__boundary._label,
                                variable_name='velocity',
                                expression=exp,
                                required=req,
                                symbols=sym,
                                condition=c,
                                examples=exa)

        if dialog.exec_():
            result = dialog.get_result()
            log.debug("slotFormulaVelocity -> %s" % str(result))
            self.__boundary.setVelocity(str(result))
            self.pushButtonVelocityFormula.setToolTip(result)
            self.pushButtonVelocityFormula.setStyleSheet(
                "background-color: green")

    @pyqtSlot(str)
    def __slotChoiceDirection(self, text):
        """
        Input the direction type choice.
        """
        c = self.modelDirection.dicoV2M[str(text)]
        log.debug("slotChoiceVelocity: %s " % c)
        self.__boundary.setDirectionChoice(c)

        if c == "formula":
            self.pushButtonDirectionFormula.setEnabled(True)
            exp = self.__boundary.getDirection('direction_formula')
            if exp:
                self.pushButtonDirectionFormula.setStyleSheet(
                    "background-color: green")
                self.pushButtonDirectionFormula.setToolTip(exp)
            else:
                self.pushButtonDirectionFormula.setStyleSheet(
                    "background-color: red")
            self.frameDirectionCoordinates.hide()
        elif c == "coordinates":
            self.pushButtonDirectionFormula.setEnabled(False)
            self.pushButtonDirectionFormula.setStyleSheet(
                "background-color: None")
            self.frameDirectionCoordinates.show()
            v = self.__boundary.getDirection('direction_x')
            self.lineEditDirectionX.setText(str(v))
            v = self.__boundary.getDirection('direction_y')
            self.lineEditDirectionY.setText(str(v))
            v = self.__boundary.getDirection('direction_z')
            self.lineEditDirectionZ.setText(str(v))
        elif c == "normal":
            self.pushButtonDirectionFormula.setEnabled(False)
            self.pushButtonDirectionFormula.setStyleSheet(
                "background-color: None")
            self.frameDirectionCoordinates.hide()

    @pyqtSlot(str)
    def __slotDirX(self, text):
        """
        INPUT value into direction of inlet flow
        """
        if self.sender().validator().state == QValidator.Acceptable:
            value = from_qvariant(text, float)
            self.__boundary.setDirection('direction_x', value)

    @pyqtSlot(str)
    def __slotDirY(self, text):
        """
        INPUT value into direction of inlet flow
        """
        if self.sender().validator().state == QValidator.Acceptable:
            value = from_qvariant(text, float)
            self.__boundary.setDirection('direction_y', value)

    @pyqtSlot(str)
    def __slotDirZ(self, text):
        """
        INPUT value into direction of inlet flow
        """
        if self.sender().validator().state == QValidator.Acceptable:
            value = from_qvariant(text, float)
            self.__boundary.setDirection('direction_z', value)

    @pyqtSlot()
    def __slotDirectionFormula(self):
        """
        """
        exp = self.__boundary.getDirection('direction_formula')

        req = [('dir_x', 'Direction of the flow along X'),
               ('dir_y', 'Direction of the flow along Y'),
               ('dir_z', 'Direction of the flow along Z')]

        exa = "dir_x = 3.0;\ndir_y = 1.0;\ndir_z = 0.0;\n"

        sym = [('x', "X face's gravity center"),
               ('y', "Y face's gravity center"),
               ('z', "Z face's gravity center"), ('dt', 'time step'),
               ('t', 'current time'), ('iter', 'number of iteration'),
               ('surface', 'Boundary zone surface')]

        for (nme, val) in self.notebook.getNotebookList():
            sym.append((nme, 'value (notebook) = ' + str(val)))

        dialog = QMegEditorView(parent=self,
                                function_type='bnd',
                                zone_name=self.__boundary._label,
                                variable_name='direction',
                                expression=exp,
                                required=req,
                                symbols=sym,
                                condition='formula',
                                examples=exa)

        if dialog.exec_():
            result = dialog.get_result()
            log.debug("slotFormulaDirection -> %s" % str(result))
            self.__boundary.setDirection('direction_formula', str(result))
            self.pushButtonDirectionFormula.setToolTip(result)
            self.pushButtonDirectionFormula.setStyleSheet(
                "background-color: green")

    @pyqtSlot(str)
    def __slotInletType(self, text):
        """
        INPUT inlet type : 'oxydant' or 'oxydant + coal'
        """
        value = self.modelTypeInlet.dicoV2M[str(text)]
        log.debug("__slotInletType value = %s " % value)

        self.__boundary.setInletType(value)

        if value == 'oxydantFlow':
            self.groupBoxCoal.hide()
            self.groupBoxCoalMass.hide()
        else:
            self.groupBoxCoal.show()
            self.groupBoxCoalMass.show()
            self.__updateTables()

    @pyqtSlot(str)
    def __slotTemperature(self, text):
        if self.sender().validator().state == QValidator.Acceptable:
            t = from_qvariant(text, float)
            self.__boundary.setOxydantTemperature(t)

    @pyqtSlot(int)
    def __slotOxydantNumber(self, i):
        self.__boundary.setOxydantNumber(i)

    def getCoalNumber(self):
        """
        Return the coal number
        """
        return self.__coalNumber
class BoundaryConditionsElectricalView(QWidget,
                                       Ui_BoundaryConditionsElectricalForm):
    """
    Boundary condifition for the velocity part
    """
    def __init__(self, parent):
        """
        Constructor.
        """
        QWidget.__init__(self, parent)

        Ui_BoundaryConditionsElectricalForm.__init__(self)
        self.setupUi(self)

    def setup(self, case):
        """
        Setup the widget.
        """
        self.case = case
        self.__boundary = None
        self.__model = ElectricalModel(self.case)
        self.species_list = []
        self.notebook = NotebookModel(self.case)

        self.lineEditValuePotElec.textChanged[str].connect(self.slotPotElec)
        self.lineEditValuePotElecIm.textChanged[str].connect(
            self.slotPotElecIm)
        self.lineEditValueSpecies.textChanged[str].connect(self.slotSpecies)

        self.pushButtonPotVectorFormula.clicked.connect(
            self.slotPotVectorFormula)
        self.pushButtonPotElecFormula.clicked.connect(self.slotPotElecFormula)
        self.pushButtonPotElecImFormula.clicked.connect(
            self.slotPotElecImFormula)

        self.comboBoxTypePotElec.activated[str].connect(self.slotPotElecChoice)
        self.comboBoxTypePotElecIm.activated[str].connect(
            self.slotPotElecImChoice)
        self.comboBoxTypePotVector.activated[str].connect(
            self.slotPotVectorChoice)
        self.comboBoxSpecies.activated[str].connect(self.slotSpeciesChoice)
        self.comboBoxPotVector.activated[str].connect(
            self.slotPotVectorComponentChoice)

        ## Validators
        validatorPotElec = DoubleValidator(self.lineEditValuePotElec)
        validatorPotElecIm = DoubleValidator(self.lineEditValuePotElecIm)
        validatorSpecies = DoubleValidator(self.lineEditValueSpecies, min=0.)

        self.lineEditValuePotElec.setValidator(validatorPotElec)
        self.lineEditValuePotElecIm.setValidator(validatorPotElecIm)
        self.lineEditValueSpecies.setValidator(validatorSpecies)

    def __setBoundary(self, boundary):
        """
        Set the current boundary
        """
        self.__boundary = boundary

        self.nature = boundary.getNature()

        self.groupBoxPotElecIm.hide()
        self.groupBoxPotVector.hide()
        self.groupBoxMixture.hide()

        self.modelPotElec = ComboModel(self.comboBoxTypePotElec, 1, 1)
        self.modelPotElecIm = ComboModel(self.comboBoxTypePotElecIm, 1, 1)
        self.modelPotVector = ComboModel(self.comboBoxTypePotVector, 1, 1)

        self.modelPotElec.addItem(self.tr("Prescribed value"), 'dirichlet')
        self.modelPotElec.addItem(self.tr("Prescribed value  (user law)"),
                                  'dirichlet_formula')
        self.modelPotElec.addItem(self.tr("Prescribed flux"), 'neumann')
        self.modelPotElec.addItem(self.tr("Prescribed flux  (user law)"),
                                  'neumann_formula')
        if self.__model.getScaling() == 'on':
            self.modelPotElec.addItem(self.tr("Implicit value (dpot)"),
                                      'dirichlet_implicit')

        self.potElec = "elec_pot_r"
        self.modelPotElecLabel = ComboModel(self.comboBoxPotElec, 1, 1)
        self.modelPotElecLabel.addItem(self.tr(self.potElec), self.potElec)
        self.modelPotElecLabel.setItem(str_model=self.potElec)

        self.modelPotElecIm.addItem(self.tr("Prescribed value"), 'dirichlet')
        self.modelPotElecIm.addItem(self.tr("Prescribed value  (user law)"),
                                    'dirichlet_formula')
        self.modelPotElecIm.addItem(self.tr("Prescribed flux"), 'neumann')
        self.modelPotElecIm.addItem(self.tr("Prescribed flux  (user law)"),
                                    'neumann_formula')

        self.potElecIm = 'elec_pot_i'
        self.modelPotElecImLabel = ComboModel(self.comboBoxPotElecIm, 1, 1)
        self.modelPotElecImLabel.addItem(self.tr(self.potElecIm),
                                         self.potElecIm)
        self.modelPotElecImLabel.setItem(str_model=self.potElecIm)

        self.modelPotVector.addItem(self.tr("Prescribed value  (user law)"),
                                    'dirichlet_formula')
        self.modelPotVector.addItem(self.tr("Null flux"), 'neumann')
        self.modelPotVector.addItem(self.tr("Implicit flux"),
                                    'neumann_implicit')

        self.potVect = 'vec_potential'
        self.modelPotVectLabel = ComboModel(self.comboBoxPotVector, 1, 1)
        self.modelPotVectLabel.addItem(self.tr('vec_potential'),
                                       'vec_potential')
        self.modelPotVectLabel.setItem(str_model=self.potVect)

        if self.__model.getElectricalModel() == 'joule':
            if self.__model.getJouleModel() == 'three-phase' or \
               self.__model.getJouleModel() == 'three-phase+Transformer':
                self.groupBoxPotElecIm.show()
        elif self.__model.getElectricalModel() == 'arc':
            self.groupBoxPotVector.show()

            self.species = ""

            if self.nature == 'inlet':
                if self.__model.getGasNumber() > 1:
                    self.groupBoxMixture.show()
                    self.modelSpecies = ComboModel(self.comboBoxSpecies, 1, 1)
                    self.species_list = self.__model.getSpeciesLabelsList()
                    for species in self.species_list:
                        self.modelSpecies.addItem(self.tr(species), species)
                    self.species = self.species_list[0]
                    self.modelSpecies.setItem(str_model=self.species)

        self.initializeVariables()

    def initializeVariables(self):
        """
        Initialize widget
        """
        self.lineEditValuePotElec.hide()
        self.lineEditValuePotElecIm.hide()
        self.lineEditValuePotVector.hide()
        self.labelValuePotVector.hide()
        self.labelValuePotElec.hide()
        self.labelValuePotElecIm.hide()

        self.pushButtonPotVectorFormula.setEnabled(False)
        self.pushButtonPotVectorFormula.setStyleSheet("background-color: None")
        self.pushButtonPotElecFormula.setEnabled(False)
        self.pushButtonPotElecFormula.setStyleSheet("background-color: None")
        self.pushButtonPotElecImFormula.setEnabled(False)
        self.pushButtonPotElecImFormula.setStyleSheet("background-color: None")

        # Initialize electric potential
        self.potElec_type = self.__b.getElecScalarChoice(self.potElec)
        self.modelPotElec.setItem(str_model=self.potElec_type)

        if self.potElec_type == 'dirichlet' or self.potElec_type == 'neumann':
            self.lineEditValuePotElec.show()
            self.labelValuePotElec.show()
            v = self.__b.getElecScalarValue(self.potElec, self.potElec_type)
            self.lineEditValuePotElec.setText(str(v))
        elif '_formula' in self.potElec_type:
            self.labelValuePotElec.show()
            self.pushButtonPotElecFormula.setEnabled(True)
            exp = self.__b.getElecScalarFormula(self.potElec,
                                                self.potElec_type)
            if exp:
                self.pushButtonPotElecFormula.setStyleSheet(
                    "background-color: green")
                self.pushButtonPotElecFormula.setToolTip(exp)
            else:
                self.pushButtonPotElecFormula.setStyleSheet(
                    "background-color: red")

        # Initialize imaginary electric potential
        if self.__model.getElectricalModel() == 'joule':
            if self.__model.getJouleModel() == 'three-phase' or \
               self.__model.getJouleModel() == 'three-phase+Transformer':
                self.potElecIm_type = self.__b.getElecScalarChoice(
                    self.potElecIm)
                self.modelPotElecIm.setItem(str_model=self.potElecIm_type)

                if self.potElecIm_type == 'dirichlet' or self.potElecIm_type == 'neumann':
                    self.lineEditValuePotElecIm.show()
                    self.labelValuePotElecIm.show()
                    v = self.__b.getElecScalarValue(self.potElecIm,
                                                    self.potElecIm_type)
                    self.lineEditValuePotElecIm.setText(str(v))
                elif '_formula' in self.potElecIm_type:
                    self.labelValuePotElec.show()
                    self.pushButtonPotElecFormula.setEnabled(True)
                    exp = self.__b.getElecScalarFormula(
                        self.potElecIm, self.potElecIm_type)
                    if exp:
                        self.pushButtonPotElecImFormula.setStyleSheet(
                            "background-color: green")
                        self.pushButtonPotElecImFormula.setToolTip(exp)
                    else:
                        self.pushButtonPotElecImFormula.setStyleSheet(
                            "background-color: red")

        # Initialize potential vector
        if self.__model.getElectricalModel() == 'arc':
            self.potVec_type = self.__b.getPotentialVectorChoice(self.potVect)
            self.modelPotVector.setItem(str_model=self.potVec_type)

            if self.potVec_type == 'dirichlet_formula':
                self.pushButtonPotVectorFormula.setEnabled(True)
                exp = self.__b.getElecScalarFormula(self.potVect,
                                                    self.potVec_type)
                if exp:
                    self.pushButtonPotVectorFormula.setStyleSheet(
                        "background-color: green")
                    self.pushButtonPotVectorFormula.setToolTip(exp)
                else:
                    self.pushButtonPotVectorFormula.setStyleSheet(
                        "background-color: red")

            # Initialize species
            if self.species:
                v = self.__b.getElecScalarValue(self.species, 'dirichlet')
                self.lineEditValueSpecies.setText(str(v))

    @pyqtSlot(str)
    def slotPotElecChoice(self, text):
        """
        INPUT choice for electric potential type
        """
        potElec_type = self.modelPotElec.dicoV2M[str(text)]
        self.__b.setElecScalarChoice(self.potElec, potElec_type)
        self.initializeVariables()

    @pyqtSlot(str)
    def slotPotElecImChoice(self, text):
        """
        INPUT choice for imaginary electric potential type
        """
        potElecIm_type = self.modelPotElecIm.dicoV2M[str(text)]
        self.__b.setElecScalarChoice(self.potElecIm, potElecIm_type)
        self.initializeVariables()

    @pyqtSlot(str)
    def slotPotVectorChoice(self, text):
        """
        INPUT choice for potential vector type
        """
        potVec_choice = self.modelPotVector.dicoV2M[str(text)]
        self.__b.setPotentialVectorChoice(self.potVect, potVec_choice)
        self.initializeVariables()

    @pyqtSlot(str)
    def slotSpeciesChoice(self, text):
        """
        INPUT species choice
        """
        self.species = self.modelSpecies.dicoV2M[str(text)]
        self.initializeVariables()

    @pyqtSlot(str)
    def slotPotVectorComponentChoice(self, text):
        """
        INPUT potential vector component choice
        """
        self.potVect = self.modelPotVectLabel.dicoV2M[str(text)]
        self.initializeVariables()

    @pyqtSlot(str)
    def slotPotElec(self, var):
        """
        """
        if self.sender().validator().state == QValidator.Acceptable:
            value = from_qvariant(var, float)
            self.__b.setElecScalarValue(self.potElec, self.potElec_type, value)

    @pyqtSlot(str)
    def slotPotElecIm(self, var):
        """
        """
        if self.sender().validator().state == QValidator.Acceptable:
            value = from_qvariant(var, float)
            self.__b.setElecScalarValue(self.potElecIm, self.potElecIm_type,
                                        value)

    @pyqtSlot(str)
    def slotSpecies(self, var):
        """
        """
        if self.sender().validator().state == QValidator.Acceptable:
            value = from_qvariant(var, float)
            self.__b.setElecScalarValue(self.species, 'dirichlet', value)

    def getScalarFormula(self, variable_name, exp_type, exp):
        """
        """
        result = None

        exa = """#example: """
        if exp_type == 'dirichlet_formula':
            req = [(variable_name, str(variable_name))]
        elif exp_type == 'neumann_formula':
            req = [("flux", "flux")]
        elif exp_type == 'exchange_coefficient_formula':
            req = [(variable_name, str(variable_name)),
                   ("hc", "heat coefficient")]

        sym = [('x', "X face's gravity center"),
               ('y', "Y face's gravity center"),
               ('z', "Z face's gravity center"), ('dt', 'time step'),
               ('t', 'current time'), ('iter', 'number of iteration'),
               ('surface', 'Boundary zone surface')]

        for (nme, val) in self.notebook.getNotebookList():
            sym.append((nme, 'value (notebook) = ' + str(val)))

        c = self.__boundary.getScalarChoice(variable_name)
        dialog = QMegEditorView(parent=self,
                                function_type='bnd',
                                zone_name=self.__boundary._label,
                                variable_name=variable_name,
                                expression=exp,
                                required=req,
                                symbols=sym,
                                condition=c,
                                examples=exa)

        if dialog.exec_():
            result = dialog.get_result()
            log.debug("slotSpeciesFormula -> %s" % str(result))
            self.__b.setElecScalarFormula(variable_name, exp_type, str(result))

        return result

    @pyqtSlot()
    def slotPotElecFormula(self):
        """
        """
        exp = self.__b.getElecScalarFormula(self.potElec, self.potElec_type)
        if self.getScalarFormula(self.potElec, self.potElec_type, exp):
            self.pushButtonPotElecFormula.setStyleSheet(
                "background-color: green")
            self.pushButtonPotElecFormula.setToolTip(exp)

    @pyqtSlot()
    def slotPotElecImFormula(self):
        """
        """
        exp = self.__b.getElecScalarFormula(self.potElec, self.potElec_type)
        if self.getScalarFormula(self.potElec, self.potElec_type, exp):
            self.pushButtonPotElecImFormula.setStyleSheet(
                "background-color: green")
            self.pushButtonPotElecImFormula.setToolTip(exp)

    @pyqtSlot()
    def slotPotVectorFormula(self):
        """
        """
        exp = self.__b.getElecScalarFormula(self.potVect, self.potVec_type)
        exa = """#example: """

        if not exp:
            exp = self.potVect + "[0] = 0;\n" + \
                  self.potVect + "[1] = 0;\n" + \
                  self.potVect + "[2] = 0;\n"

        req = [(self.potVect + "[0]", 'vector potential X'),
               (self.potVect + "[1]", 'vector potential Y'),
               (self.potVect + "[2]", 'vector potential Z')]

        sym = [('x', "X cell's gravity center"),
               ('y', "Y cell's gravity center"),
               ('z', "Z cell's gravity center"), ('dt', 'time step'),
               ('t', 'current time'), ('iter', 'number of iteration')]

        for (nme, val) in self.notebook.getNotebookList():
            sym.append((nme, 'value (notebook) = ' + str(val)))

        c = self.__b.getElecScalarChoice(self.potVect)

        dialog = QMegEditorView(parent=self,
                                function_type='bnd',
                                zone_name=self.__boundary._label,
                                variable_name=self.potVect,
                                expression=exp,
                                required=req,
                                symbols=sym,
                                condition=c,
                                examples=exa)

        if dialog.exec_():
            result = dialog.get_result()
            log.debug("slotPotVectorFormula -> %s" % str(result))
            self.__b.setElecScalarFormula(self.potVect, self.potVec_type,
                                          str(result))
            self.pushButtonPotVectorFormula.setToolTip(result)
            self.pushButtonPotVectorFormula.setStyleSheet(
                "background-color: green")

    def showWidget(self, b):
        """
        Show the widget.
        """
        self.__b = b
        if self.__model.getElectricalModel() != 'off':
            label = b.getLabel()
            nature = "joule_" + b.getNature()
            self.__b = Boundary(nature, label, self.case)
            self.__setBoundary(b)

            self.show()
        else:
            self.hideWidget()

    def hideWidget(self):
        """
        Hide all.
        """
        self.hide()
예제 #27
0
class BoundaryConditionsTurbulenceInletView(QWidget, Ui_BoundaryConditionsTurbulenceInletForm):
    """
    Boundary condition for turbulence
    """
    def __init__(self, parent):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_BoundaryConditionsTurbulenceInletForm.__init__(self)
        self.setupUi(self)


    def setup(self, case):
        """
        Setup the widget
        """
        self.case = case
        self.__boundary = None

        self.case.undoStopGlobal()
        self.notebook = NotebookModel(self.case)

        self.comboBoxTurbulence.activated[str].connect(self.__slotChoiceTurbulence)

        self.__modelTurbulence = ComboModel(self.comboBoxTurbulence, 2, 1)
        self.__modelTurbulence.addItem(self.tr("Calculation by hydraulic diameter"), 'hydraulic_diameter')
        self.__modelTurbulence.addItem(self.tr("Calculation by turbulent intensity"), 'turbulent_intensity')
        self.__modelTurbulence.addItem(self.tr("Calculation by formula"), 'formula')

        self.lineEditDiameter.textChanged[str].connect(self.__slotDiam)
        self.lineEditIntensity.textChanged[str].connect(self.__slotIntensity)
        self.lineEditDiameterIntens.textChanged[str].connect(self.__slotDiam)
        self.pushButtonTurb.clicked.connect(self.__slotTurbulenceFormula)

        validatorDiam = DoubleValidator(self.lineEditDiameter, min=0.)
        validatorDiam.setExclusiveMin(True)
        validatorIntensity = DoubleValidator(self.lineEditIntensity, min=0.)

        self.lineEditDiameter.setValidator(validatorDiam)
        self.lineEditDiameterIntens.setValidator(validatorDiam)
        self.lineEditIntensity.setValidator(validatorIntensity)

        self.case.undoStartGlobal()


    def showWidget(self, boundary):
        """
        Show the widget
        """
        self.__boundary = boundary

        if TurbulenceModel(self.case).getTurbulenceVariable():
            turb_choice = boundary.getTurbulenceChoice()
            self.__modelTurbulence.setItem(str_model=turb_choice)
            self.pushButtonTurb.setEnabled(False)
            self.pushButtonTurb.setStyleSheet("background-color: None")
            if turb_choice == "hydraulic_diameter":
                self.frameTurbDiameter.show()
                self.frameTurbIntensity.hide()
                d = boundary.getHydraulicDiameter()
                self.lineEditDiameter.setText(str(d))
            elif turb_choice == "turbulent_intensity":
                self.frameTurbIntensity.show()
                self.frameTurbDiameter.hide()
                i = boundary.getTurbulentIntensity()
                d = boundary.getHydraulicDiameter()
                self.lineEditIntensity.setText(str(i))
                self.lineEditDiameterIntens.setText(str(d))
            elif turb_choice == "formula":
                self.frameTurbIntensity.hide()
                self.frameTurbDiameter.hide()
                self.pushButtonTurb.setEnabled(True)
                exp = self.__boundary.getTurbFormula()
                if exp:
                    self.pushButtonTurb.setStyleSheet("background-color: green")
                    self.pushButtonTurb.setToolTip(exp)
                else:
                    self.pushButtonTurb.setStyleSheet("background-color: red")
            self.show()
        else:
예제 #28
0
class OutputVolumicVariablesView(QWidget, Ui_OutputVolumicVariablesForm):
    """
    """
    def __init__(self, parent, case):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_OutputVolumicVariablesForm.__init__(self)
        self.setupUi(self)

        self.case = case
        self.parent = parent
        self.case.undoStopGlobal()
        self.info_turb_name = []

        self.mdl = OutputVolumicVariablesModel(self.case)

        self.modelOutput = VolumicOutputStandardItemModel(
            parent, self.case, self.mdl)
        self.treeViewOutput.setModel(self.modelOutput)
        self.treeViewOutput.setAlternatingRowColors(True)
        self.treeViewOutput.setSelectionBehavior(QAbstractItemView.SelectItems)
        self.treeViewOutput.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        self.treeViewOutput.setEditTriggers(QAbstractItemView.DoubleClicked)
        self.treeViewOutput.expandAll()
        self.treeViewOutput.setDragEnabled(False)

        labelDelegate = LabelDelegate(self.treeViewOutput, self.mdl)
        self.treeViewOutput.setItemDelegateForColumn(0, labelDelegate)

        self.treeViewOutput.resizeColumnToContents(0)
        self.treeViewOutput.resizeColumnToContents(1)

        if self.case.xmlRootNode().tagName == "NEPTUNE_CFD_GUI":

            self.groupBox_2.hide()

        elif self.case.xmlRootNode().tagName == "Code_Saturne_GUI":

            self.correctionEstimator = ComboModel(self.comboBoxIescor, 3, 1)
            self.correctionEstimator.addItem(self.tr("off"), '0')
            self.correctionEstimator.addItem(
                self.tr("without volume contribution"), '1')
            self.correctionEstimator.addItem(
                self.tr("with volume contribution"), '2')

            self.driftEstimator = ComboModel(self.comboBoxIesder, 3, 1)
            self.driftEstimator.addItem(self.tr("off"), '0')
            self.driftEstimator.addItem(self.tr("without volume contribution"),
                                        '1')
            self.driftEstimator.addItem(self.tr("with volume contribution"),
                                        '2')

            self.predictionEstimator = ComboModel(self.comboBoxIespre, 3, 1)
            self.predictionEstimator.addItem(self.tr("off"), '0')
            self.predictionEstimator.addItem(
                self.tr("without volume contribution"), '1')
            self.predictionEstimator.addItem(
                self.tr("with volume contribution"), '2')

            self.totalEstimator = ComboModel(self.comboBoxIestot, 3, 1)
            self.totalEstimator.addItem(self.tr("off"), '0')
            self.totalEstimator.addItem(self.tr("without volume contribution"),
                                        '1')
            self.totalEstimator.addItem(self.tr("with volume contribution"),
                                        '2')

            self.comboBoxIescor.activated[str].connect(
                self.slotCorrectionEstimator)
            self.comboBoxIesder.activated[str].connect(self.slotDriftEstimator)
            self.comboBoxIespre.activated[str].connect(
                self.slotPredictionEstimator)
            self.comboBoxIestot.activated[str].connect(self.slotTotalEstimator)

            modelIescor = self.mdl.getEstimatorModel("Correction")
            self.correctionEstimator.setItem(str_model=modelIescor)

            modelIesder = self.mdl.getEstimatorModel("Drift")
            self.driftEstimator.setItem(str_model=modelIesder)

            modelIespre = self.mdl.getEstimatorModel("Prediction")
            self.predictionEstimator.setItem(str_model=modelIespre)

            modelIestot = self.mdl.getEstimatorModel("Total")
            self.totalEstimator.setItem(str_model=modelIestot)

        self.case.undoStartGlobal()

    def initializeView(self):
        """
        """
        self.modelOutput = VolumicOutputStandardItemModel(
            self.parent, self.case, self.mdl)
        self.treeViewOutput.setModel(self.modelOutput)
        self.treeViewOutput.expandAll()

    @pyqtSlot(str)
    def slotCorrectionEstimator(self, text):
        """
        Private slot.
        Input ITURB.
        """
        model = self.correctionEstimator.dicoV2M[str(text)]
        self.mdl.setEstimatorModel("Correction", model)
        self.mdl.updateList()

        self.initializeView()

    @pyqtSlot(str)
    def slotDriftEstimator(self, text):
        """
        Private slot.
        Input ITURB.
        """
        model = self.driftEstimator.dicoV2M[str(text)]
        self.mdl.setEstimatorModel("Drift", model)
        self.mdl.updateList()

        self.initializeView()

    @pyqtSlot(str)
    def slotPredictionEstimator(self, text):
        """
        Private slot.
        Input ITURB.
        """
        model = self.predictionEstimator.dicoV2M[str(text)]
        self.mdl.setEstimatorModel("Prediction", model)
        self.mdl.updateList()

        self.initializeView()

    @pyqtSlot(str)
    def slotTotalEstimator(self, text):
        """
        Private slot.
        Input ITURB.
        """
        model = self.totalEstimator.dicoV2M[str(text)]
        self.mdl.setEstimatorModel("Total", model)
        self.mdl.updateList()

        self.initializeView()
class OpenTurnsDialogView(QDialog, Ui_OpenTurnsDialogForm):
    """
    OpenTurns Page viewer class
    """
    def __init__(self, parent, case):
        """
        Constructor
        """
        QDialog.__init__(self, parent)

        Ui_OpenTurnsDialogForm.__init__(self)
        self.setupUi(self)

        self.case = case
        self.parent = parent

        title = self.tr("OpenTURNS parameters")
        self.setWindowTitle(title)

        self.case.undoStopGlobal()

        case_is_saved = not self.case.isModified()

        self.mdl = OpenTurnsModel(case)
        if not self.mdl.getHostName():
            self.mdl.setDefaultOptions()

        # Combo model
        config = configparser.ConfigParser()
        config.read(self.case['package'].get_configfiles())
        self.nmodes = 1

        dist_hosts = None
        if config.has_section('distant_hosts'):
            if len(config.options('distant_hosts')) != 0:
                dist_hosts = config.options('distant_hosts')
                self.nmodes += len(dist_hosts)

        self.modelOtStudyHosts = ComboModel(self.comboBoxStudyMode,
                                            self.nmodes, 1)
        self.modelOtStudyHosts.addItem(self.tr("Localhost"), 'localhost')

        self.hosts_bmgr = {}
        if config.has_option('install', 'batch'):
            self.hosts_bmgr['localhost'] = (config.get('install',
                                                       'batch')).lower()
        else:
            self.hosts_bmgr['localhost'] = 'none'

        # Check for distant builds:
        # Hosts are stored in the form <batch_rm>_<host_name> hence the split
        # used hereafter to determine the "real" host name
        self.hosts_binpath = {}
        self.hosts_binpath['localhost'] = 'default'

        self.distant_host_builds = None
        if dist_hosts != None:
            self.distant_host_builds = {}
            for key in dist_hosts:
                host_name = key.split('_')[1]
                self.hosts_bmgr[host_name] = key.split('_')[0]

                self.hosts_binpath[host_name] = config.get(
                    'distant_hosts', key)

                self.addDistantBuilds(host_name)

                dh_not_found = False
                if self.distant_host_builds[host_name] is None:
                    self.distant_host_builds[host_name] = ['none found']
                    dh_not_found = True

                host_tag = 'distant : ' + host_name
                self.modelOtStudyHosts.addItem(self.tr(host_tag),
                                               host_name,
                                               warn=dh_not_found)
                if dh_not_found:
                    self.modelOtStudyHosts.disableItem(str_model=host_name)

        # ---------------------------------------
        # Connections:
        self.comboBoxStudyMode.activated[str].connect(self.slotOtStudyMode)
        self.comboBoxDistantBuilds.activated[str].connect(self.slotBuildChoice)

        self.lineEditDistWorkDir.textChanged[str].connect(self.slotOtDistWdir)

        self.spinBoxNumberNodes.valueChanged[int].connect(
            self.slotUpdateNodesNumber)
        self.spinBoxNumberTasks.valueChanged[int].connect(
            self.slotUpdateTasksNumber)
        self.spinBoxNumberThreads.valueChanged[int].connect(
            self.slotUpdateThreadsNumber)

        self.spinBoxNumberDays.valueChanged[int].connect(self.slotUpdateWCDays)
        self.spinBoxNumberHours.valueChanged[int].connect(
            self.slotUpdateWCHours)
        self.spinBoxNumberMinutes.valueChanged[int].connect(
            self.slotUpdateWCMinutes)
        self.spinBoxNumberSeconds.valueChanged[int].connect(
            self.slotUpdateWCSeconds)
        self.lineEditWCKEY.textChanged[str].connect(self.slotUpdateWckey)

        self.pushButtonLaunchOT.clicked.connect(self.slotLaunchCsOt)

        self.pushButtonCancel.clicked.connect(self.slotCancel)

        # ---------------------------------------
        # Hide/Show initial elements
        if self.nmodes == 1:
            self.groupBoxLocalLaunch.show()
            self.groupBoxDistantLaunch.hide()
            self.setAvailableBuildsList('localhost')
        else:
            self.setAvailableBuildsList(self.mdl.getHostName())
            if self.mdl.getHostName() == "localhost":
                self.groupBoxLocalLaunch.show()
                self.groupBoxDistantLaunch.hide()
            else:
                self.groupBoxLocalLaunch.hide()
                self.groupBoxDistantLaunch.show()

        # ---------------------------------------
        # Initial values
        if dist_hosts != None:
            self.modelOtStudyHosts.setItem(str_model=self.mdl.host_name)
        else:
            self.modelOtStudyHosts.setItem(str_model='localhost')

        self.spinBoxLocalProcs.setValue(int(self.mdl.nprocs))
        self.spinBoxLocalThreads.setValue(1)

        self.spinBoxNumberNodes.setValue(int(self.mdl.nnodes))
        self.spinBoxNumberTasks.setValue(int(self.mdl.ntasks))
        self.spinBoxNumberThreads.setValue(int(self.mdl.nthreads))

        wct = self.mdl.getWallClockTime()
        self.spinBoxNumberDays.setValue(int(wct[0]))
        self.spinBoxNumberHours.setValue(int(wct[1]))
        self.spinBoxNumberMinutes.setValue(int(wct[2]))
        self.spinBoxNumberSeconds.setValue(int(wct[3]))

        self.lineEditWCKEY.setText(self.mdl.getWCKEY())

        self.case.undoStartGlobal()

    @pyqtSlot(str)
    def slotOtStudyMode(self, text):
        """
        Host type: localhost or a distant one (defined in code_saturne.cfg).
        """
        host_name = self.modelOtStudyHosts.dicoV2M[str(text)]

        self.mdl.setHostName(host_name)
        self.mdl.setBatchManager(self.hosts_bmgr[host_name])

        if host_name != 'localhost':
            self.groupBoxDistantLaunch.show()
        else:
            self.groupBoxDistantLaunch.hide()

        self.setAvailableBuildsList(host_name)

        self.mdl.arch_path = self.hosts_binpath[host_name]

    @pyqtSlot(str)
    def slotBuildChoice(self, text):
        """
        Sets the hostname
        """
        self.mdl.setBuildName(text)

    @pyqtSlot(str)
    def slotOtDistWdir(self, text):
        """
        Set the distant workdir path
        """
        self.mdl.setDistWorkdir(text)

    @pyqtSlot(int)
    def slotUpdateNodesNumber(self, v):
        """
        Update the number of required computation nodes
        """

        n = int(self.spinBoxNumberNodes.text())
        self.mdl.setClusterParams(nnodes=n)

    @pyqtSlot(int)
    def slotUpdateNprocs(self, v):
        """
        Update the number of required processes
        """

        n = int(self.spinBoxLocalProcs.text())
        self.mdl.setNprocs(n)

    @pyqtSlot(int)
    def slotUpdateTasksNumber(self, v):
        """
        Update the number of required mpi tasks per node
        """

        n = int(self.spinBoxNumberTasks.text())
        self.mdl.setClusterParams(ntasks=n)

    @pyqtSlot(int)
    def slotUpdateThreadsNumber(self, v):
        """
        Update the number of required threads per processor
        """

        n = int(self.spinBoxNumberThreads.text())
        self.mdl.setClusterParams(nthreads=n)

    @pyqtSlot(int)
    def slotUpdateWCDays(self, v):
        """
        Update the wall clock days value
        """

        d, h, m, s = self.mdl.getWallClockTime()
        d = str(int(self.spinBoxNumberDays.text()))

        self.mdl.setWallClockTime(d, h, m, s)

    @pyqtSlot(int)
    def slotUpdateWCHours(self, v):
        """
        Update the wall clock hours value
        """

        d, h, m, s = self.mdl.getWallClockTime()
        h = str(int(self.spinBoxNumberHours.text()))

        self.mdl.setWallClockTime(d, h, m, s)

    @pyqtSlot(int)
    def slotUpdateWCMinutes(self, v):
        """
        Update the wall clock minutes value
        """

        d, h, m, s = self.mdl.getWallClockTime()
        m = str(int(self.spinBoxNumberMinutes.text()))

        self.mdl.setWallClockTime(d, h, m, s)

    @pyqtSlot(int)
    def slotUpdateWCSeconds(self, v):
        """
        Update the wall clock seconds value
        """

        d, h, m, s = self.mdl.getWallClockTime()
        s = str(int(self.spinBoxNumberSeconds.text()))

        self.mdl.setWallClockTime(d, h, m, s)

    @pyqtSlot(str)
    def slotUpdateWckey(self, text):
        """
        Update the WCKEY variable
        """

        self.mdl.setWCKEY(text)

    @pyqtSlot()
    def slotLaunchCsOt(self):
        """
        Translate the Code_Sature reference case and study into an OpenTurs
        physical model and study
        """
        QDialog.accept(self)

        if self.case['salome']:
            import salome_ot

            # Update the study cfg file
            self.mdl.update_cfg_file()

            # Generating OpenTurns _exec function
            self.create_cs_exec_function()

            # Load the code_saturne case as Physical model and launch
            # OpenTurns GUI
            cs_exec_script_name = os.path.join(self.mdl.otstudy_path,
                                               'cs_execute_job.py')
            salome_ot.loadYacsPyStudy(cs_exec_script_name)

        else:
            print(
                "This option is only available within the SALOME_CFD platform")

    @pyqtSlot()
    def slotCancel(self):
        """
        Close dialog with no modifications
        """

        QDialog.accept(self)

    def addDistantBuilds(self, host_name):
        """
        Search for the distant builds of code_saturne for the given distant
        host.
        """

        host_path = self.hosts_binpath[host_name]

        builds_list = __getListOfDistantBuilds__(host_name, host_path)

        self.distant_host_builds[host_name] = builds_list

    def setAvailableBuildsList(self, host_name):
        """
        Set the list of available builds per host
        """

        if host_name == 'localhost':

            self.groupBoxDistantLaunch.hide()
            self.groupBoxLocalLaunch.show()

            self.comboBoxDistantBuilds.hide()
            self.labelDistantBuilds.hide()
            return

        else:
            self.groupBoxDistantLaunch.show()
            self.groupBoxLocalLaunch.hide()

            self.comboBoxDistantBuilds.show()
            self.labelDistantBuilds.show()

            dist_builds_list = self.distant_host_builds[host_name]
            self.modelOtDistantBuilds = ComboModel(self.comboBoxDistantBuilds,
                                                   len(dist_builds_list), 1)
            for db in dist_builds_list:
                self.modelOtDistantBuilds.addItem(self.tr(db), db)

    def create_cs_exec_function(self):
        """
        This function generates the _exec function needed by OpenTurns for a study
        using distant launching on clusters.
        Takes as input:
            - code_saturne study path
            - OT_params.cfg name
            - list of OTurns input variables
            - list of OTurns output variables
            - the requested cluster name
            - the result file name which contains the output values
        """

        cluster = self.mdl.host_name

        exec_file_name = os.path.join(self.mdl.otstudy_path,
                                      'cs_execute_job.py')

        f = open(exec_file_name, 'w')

        script_cmd = "\n"
        script_cmd += "# ============================================================================== \n"
        script_cmd += "# OPENTURNS EXEC FUNCTION WHICH LAUNCHES CODE_SATURNE ON A DISTANT CLUSTER \n"
        script_cmd += "# ============================================================================== \n"

        script_cmd += "\n\n"

        nvars = len(self.mdl.input_variables)

        script_cmd = 'def _exec('
        vars_dict = '{'

        toffset = '    '
        cmd1 = 'cfd_eval = cfd_openturns_study('
        loffset1 = toffset
        for i in range(len(cmd1)):
            loffset1 += ' '

        loffset2 = '           '

        iv = -1
        for i in range(nvars):
            if i == 0:
                script_cmd += self.mdl.input_variables[i]
                vars_dict += '"' + self.mdl.input_variables[i] + '":'
                vars_dict += self.mdl.input_variables[i]
            else:
                script_cmd += ", " + self.mdl.input_variables[i]
                vars_dict += ', \n'
                vars_dict += loffset1 + loffset2 + '   '
                vars_dict += '"' + self.mdl.input_variables[i] + '":'
                vars_dict += self.mdl.input_variables[i]

        script_cmd += '):\n\n'
        vars_dict += '}'

        script_cmd += toffset + "import sys\n"

        salome_pydir = os.path.join(self.case['package'].dirs['pythondir'],
                                    'salome')
        script_cmd += toffset
        script_cmd += "sys.path.insert(-1, '%s')\n\n" % salome_pydir
        script_cmd += toffset + "from CFDSTUDYOTURNS_StudyInterface import cfd_openturns_study"
        script_cmd += "\n\n"

        script_cmd += toffset + cmd1 + 'study_path = "' + self.mdl.otstudy_path + '",\n'
        script_cmd += loffset1 + 'study_cfg  = "openturns_study.cfg",\n'
        script_cmd += loffset1 + 'vars_dico  = ' + vars_dict + ')\n\n'

        script_cmd += toffset + 'cfd_eval.study2code() \n\n'
        script_cmd += toffset + 'cfd_eval.run() \n\n'

        n_vals = len(self.mdl.output_variables)
        vals_list = ""
        for i in range(n_vals):
            if i != 0:
                vals_list += ', '
            vals_list += self.mdl.output_variables[i]

        cmd_m1 = '(%s,) = cfd_eval.code2study(n_values=%d)\n' % (vals_list,
                                                                 n_vals)
        script_cmd += toffset + cmd_m1

        script_cmd += '\n'

        script_cmd += toffset + 'return '
        script_cmd += vals_list + '\n'

        f.write(script_cmd)
        f.close()
class TurbulenceView(QWidget, Ui_Turbulence):
    """
    Main fields layout.
    """
    def __init__(self, parent, case):
        """
        Constructor
        """
        QWidget.__init__(self, parent)

        Ui_Turbulence.__init__(self)
        self.setupUi(self)

        self.case = case
        self.case.undoStopGlobal()
        self.mdl = TurbulenceModel(self.case)

        # Dico
        self.dicoM2V = {
            "none": 'none',
            "mixing_length": 'mixing length',
            "k-epsilon": 'k-epsilon',
            "rij-epsilon_ssg": 'Rij-epsilon SSG',
            "rij-epsilon_ebrsm": 'Rij-epsilon EBRSM',
            "k-epsilon_linear_production": 'k-epsilon linear production',
            "les_smagorinsky": 'LES (Smagorinsky)',
            "les_wale": 'LES (WALE)',
            "tchen": 'Tchen',
            "q2-q12": 'Q2-Q12',
            "r2-q12": 'R2-Q12',
            "r2-r12-tchen": 'R2-R12 Tchen',
            "separate_phase": 'separate phase',
            "separate_phase_cond": 'separate phase cond',
            "small_inclusions": 'small inclusions',
            "large_inclusions": 'large inclusions',
            "sgdh": 'SGDH',
            "ggdh": 'GGDH'
        }

        self.dicoV2M = {
            "none": 'none',
            "mixing length": 'mixing_length',
            "k-epsilon": 'k-epsilon',
            "Rij-epsilon SSG": 'rij-epsilon_ssg',
            "Rij-epsilon EBRSM": 'rij-epsilon_ebrsm',
            "k-epsilon linear production": 'k-epsilon_linear_production',
            "LES (Smagorinsky)": 'les_smagorinsky',
            "LES (WALE)": 'les_wale',
            "Tchen": 'tchen',
            "Q2-Q12": 'q2-q12',
            "R2-Q12": 'r2-q12',
            "R2-R12 Tchen": 'r2-r12-tchen',
            "separate phase": 'separate_phase',
            "separate phase cond": 'separate_phase_cond',
            "small inclusions": 'small_inclusions',
            "large inclusions": 'large_inclusions',
            "SGDH": 'sgdh',
            "GGDH": 'ggdh'
        }

        # Validators
        validatorMix = DoubleValidator(self.lineEditMixingLength, min=0.0)
        validatorMix.setExclusiveMin(False)
        self.lineEditMixingLength.setValidator(validatorMix)

        self.tableModelTurbulence = StandardItemModelTurbulence(
            self.mdl, self.case, self.dicoM2V, self.dicoV2M)
        self.tableViewTurbulence.setModel(self.tableModelTurbulence)
        self.tableViewTurbulence.resizeColumnsToContents()
        self.tableViewTurbulence.resizeRowsToContents()
        if QT_API == "PYQT4":
            self.tableViewTurbulence.verticalHeader().setResizeMode(
                QHeaderView.ResizeToContents)
            self.tableViewTurbulence.horizontalHeader().setResizeMode(
                QHeaderView.ResizeToContents)
            self.tableViewTurbulence.horizontalHeader().setResizeMode(
                0, QHeaderView.Stretch)
        elif QT_API == "PYQT5":
            self.tableViewTurbulence.verticalHeader().setSectionResizeMode(
                QHeaderView.ResizeToContents)
            self.tableViewTurbulence.horizontalHeader().setSectionResizeMode(
                QHeaderView.ResizeToContents)
            self.tableViewTurbulence.horizontalHeader().setSectionResizeMode(
                0, QHeaderView.Stretch)
        self.tableViewTurbulence.setSelectionBehavior(
            QAbstractItemView.SelectRows)
        self.tableViewTurbulence.setSelectionMode(
            QAbstractItemView.SingleSelection)

        delegateTurbulence = TurbulenceDelegate(self.tableViewTurbulence,
                                                self.mdl, self.dicoM2V,
                                                self.dicoV2M)
        delegateTurbFlux = TurbFluxDelegate(self.tableViewTurbulence, self.mdl,
                                            self.dicoM2V, self.dicoV2M)
        delegateCoupling = CouplingDelegate(self.tableViewTurbulence, self.mdl,
                                            self.dicoM2V, self.dicoV2M)
        self.tableViewTurbulence.setItemDelegateForColumn(
            2, delegateTurbulence)
        self.tableViewTurbulence.setItemDelegateForColumn(3, delegateTurbFlux)
        self.tableViewTurbulence.setItemDelegateForColumn(4, delegateCoupling)

        # Combo models
        self.modelContinuousCoupling = ComboModel(
            self.comboBoxContinuousCoupling, 1, 1)
        self.modelContinuousCoupling.addItem(self.tr('none'), 'none')
        if self.mdl.getHeatMassTransferStatus() == "off":
            self.modelContinuousCoupling.addItem(self.tr("separate phases"),
                                                 "separate_phase")
        else:
            self.modelContinuousCoupling.addItem(
                self.tr("separate phases + cond"), "separate_phase_cond")

        # hide groupBoxMixingLength
        self.groupBoxMixingLength.hide()

        # Connect signals to slots
        self.tableModelTurbulence.dataChanged.connect(self.dataChanged)
        self.lineEditMixingLength.textChanged[str].connect(
            self.slotMixingLength)
        self.tableViewTurbulence.clicked.connect(self.slotChangeSelection)
        self.comboBoxContinuousCoupling.activated[str].connect(
            self.slotContinuousCoupling)

        # hide/show groupBoxContinuousCoupling
        if len(self.mdl.getContinuousFieldList()) >= 2:
            self.groupBoxContinuousCoupling.show()
            model = self.mdl.getContinuousCouplingModel()
            self.modelContinuousCoupling.setItem(str_model=model)
        else:
            self.groupBoxContinuousCoupling.hide()

        for fieldId in self.mdl.getFieldIdList():
            self.tableModelTurbulence.newItem(fieldId)

        self.case.undoStartGlobal()

    def slotChangeSelection(self, text=None):
        """
        detect change selection to update
        """
        row = self.tableViewTurbulence.currentIndex().row()
        self.update(row)

    def dataChanged(self, topLeft, bottomRight):
        self.tableViewTurbulence.resizeColumnsToContents()
        self.tableViewTurbulence.resizeRowsToContents()
        if QT_API == "PYQT4":
            self.tableViewTurbulence.horizontalHeader().setResizeMode(
                0, QHeaderView.Stretch)
        elif QT_API == "PYQT5":
            self.tableViewTurbulence.horizontalHeader().setSectionResizeMode(
                0, QHeaderView.Stretch)

        row = self.tableViewTurbulence.currentIndex().row()
        self.update(row)

    def update(self, row):
        """
        show groupBoxMixingLength if necessary
        """
        fieldId = row + 1
        if fieldId != 0:
            turbModel = self.mdl.getTurbulenceModel(fieldId)
            if turbModel == "mixing_length":
                self.groupBoxMixingLength.show()
                self.lineEditMixingLength.setText(
                    str(self.mdl.getMixingLength(fieldId)))
            else:
                self.groupBoxMixingLength.hide()
                # If the user chose GGDH for a RSM turbulence model, we set
                # the thermal fluxes model back to SGDH for consistency
                if 'rij-epsilon' not in turbModel and \
                        self.mdl.getThermalTurbulentFlux(fieldId) == 'ggdh':
                    self.mdl.setThermalTurbulentFlux(fieldId, 'sgdh')

    @pyqtSlot(str)
    def slotMixingLength(self, text):
        """
        Update the mixing length
        """
        fieldId = self.tableViewTurbulence.currentIndex().row() + 1
        if self.lineEditMixingLength.validator(
        ).state == QValidator.Acceptable:
            mix = from_qvariant(text, float)
            self.mdl.setMixingLength(fieldId, mix)

    @pyqtSlot(str)
    def slotContinuousCoupling(self, text):
        """
        define continuous/continuous coupling modele
        """
        value = self.modelContinuousCoupling.dicoV2M[text]
        log.debug("slotContinuousCoupling -> %s" % value)
        self.mdl.setContinuousCouplingModel(value)