Salome HOME
Merge branch 'BR_PY3'
authorYoann AUDOUIN <B61570@dsp0851742.postes.calibre.edf.fr>
Tue, 3 Mar 2020 08:24:28 +0000 (09:24 +0100)
committerYoann AUDOUIN <B61570@dsp0851742.postes.calibre.edf.fr>
Tue, 3 Mar 2020 08:24:28 +0000 (09:24 +0100)
1  2 
src/HYDROGUI/BndConditionsDialog.py

index 7c393be0ea271af339b916881b6370b3288e368b,474b4be4f3ae3bb33ba13868d161f3fee4b72720..b9c3924c6c06ab46f3f96a8c4270c55c77721176
mode 100644,100755..100755
  import os
  import sys
  
- from PyQt4 import QtCore, QtGui, uic
+ from PyQt5.QtCore import *
+ from PyQt5.QtGui import *
+ from PyQt5.QtWidgets import *
+ from PyQt5 import uic
  
  from MEDLoader import MEDFileMesh
  
  # TODO: get rid of sys.path.append() ?
- hydro_solver_root = os.path.join(os.environ['HYDROSOLVER_ROOT_DIR'], 'lib', 'python2.7', 'site-packages', 'salome')
- sys.path.append(os.path.join(hydro_solver_root, 'salome', 'hydrotools'))
+ import sysconfig
+ pythonVersion = 'python' + sysconfig.get_python_version()
+ hydro_solver_root = os.path.join(os.environ['HYDROSOLVER_ROOT_DIR'], 'lib', pythonVersion, 'site-packages', 'salome')
  
- import boundaryConditions
from salome.hydro import boundaryConditions
  
  ROW_PROPERTY_NAME = "row"
  
@@@ -35,202 -39,201 +39,201 @@@ def get_med_groups_on_edges(file_path)
      try:
          med_file_mesh = MEDFileMesh.New(file_path)
          groups = list(med_file_mesh.getGroupsOnSpecifiedLev(-1))
-     except:
+     except Exception as e:
+         print(e.what())
          return []
-           
      return groups
  
- """Get preset name corresponding to the given values of LIHBOR, LIUBOR, LIVBOR and LITBOR"""    
+ """Get preset name corresponding to the given values of LIHBOR, LIUBOR, LIVBOR and LITBOR"""
  def get_preset_name(presets, lihbor, liubor, livbor, litbor):
-     name = ''
-     
-     for preset_name in presets:
-         values = presets[preset_name]
-         
-         p_lihbor = values[0]
-         p_liubor = values[1]
-         p_livbor = values[2]
-         p_litbor = values[3]
-         
-         if not p_lihbor or p_lihbor == lihbor:
-             if not p_liubor or p_liubor == liubor:
-                 if not p_livbor or p_livbor == livbor:
-                     if not p_litbor or p_litbor == litbor:
-                         name = preset_name
-                         
+     name = 'Custom'
+     res = (lihbor, liubor, livbor, litbor)
+     for key, val in presets.items():
+       if val == res:
+         name = key
+         break
      return name
  
- """Convert string to integer, return None if conversion is not possible"""    
+ """Convert string to integer, return None if conversion is not possible"""
  def get_int(str):
-     value = None
-     
+     value = ''
      if str.isdigit():
          value = int(str)
-             
      return value
  
- """Item delegate for LIHBOR, LIUBOR, LIVBOR and LITBOR columns"""    
- class ValueDelegate(QtGui.QStyledItemDelegate):
-     
+ """Item delegate for LIHBOR, LIUBOR, LIVBOR and LITBOR columns"""
+ class ValueDelegate(QStyledItemDelegate):
      def __init__(self, parent = None):
-         QtGui.QStyledItemDelegate.__init__(self, parent)
-         
+         QStyledItemDelegate.__init__(self, parent)
      def createEditor(self, parent, option, index):
-         line_edit = QtGui.QLineEdit(parent)
-         
-         validator = QtGui.QIntValidator(parent)
+         line_edit = QLineEdit(parent)
+         validator = QIntValidator(parent)
          validator.setRange(0, 6)
-         
          line_edit.setValidator(validator)
  
          return line_edit
-         
-     def setEditorData(self, editor, index):
-         value, is_ok = index.model().data(index, QtCore.Qt.EditRole).toInt()
  
-         if is_ok:
-             editor.setText(str(value))
+     def setEditorData(self, editor, index):
+         value = index.model().data(index, Qt.EditRole)
+         if value.isdigit():
+             editor.setText(value)
          else:
              editor.setText('')
-     
      def setModelData(self, editor, model, index):
-         model.setData(index, editor.text(), QtCore.Qt.EditRole)
+         model.setData(index, editor.text(), Qt.EditRole)
  
      def updateEditorGeometry(self, editor, option, index):
          editor.setGeometry(option.rect)
-     
- """Boundary conditions definition dialog"""    
- class BoundaryConditionsDialog(QtGui.QDialog):
+ """Boundary conditions definition dialog"""
+ class BoundaryConditionsDialog(QDialog):
  
      def __init__(self, parent = None, modal = 0):
-         QtGui.QDialog.__init__(self, parent)
+         QDialog.__init__(self, parent)
          uic.loadUi(os.path.join(hydro_solver_root, 'BndConditionsDialog.ui'), self )
-                                                       
          # Connections
          self.medFileButton.clicked.connect(self.on_med_file_browse)
          self.bndConditionsFileButton.clicked.connect(self.on_bnd_file_browse)
          self.resultBndConditionsFileButton.clicked.connect(self.on_result_file_browse)
-         
          self.sameAsInputCB.toggled.connect(self.resultBndConditionsFileEdit.setDisabled)
          self.sameAsInputCB.toggled.connect(self.resultBndConditionsFileButton.setDisabled)
-         
          self.boundaryConditionsTable.cellChanged.connect(self.on_cell_changed)
-         
          self.applyAndCloseButton.clicked.connect(self.on_apply_and_close)
          self.applyButton.clicked.connect(self.on_apply)
          self.closeButton.clicked.connect(self.reject)
          self.helpButton.clicked.connect(self.on_help)
-         
          # Set widgets properties
          self.init_widgets()
-       
          # Input conditions
          self.input_conditions = {}
-       
          # Init presets
          self.presets = {}
          self.init_presets()
-     
      """Initialize presets"""
      def init_presets(self):
          # TODO: determine another presets path
-         presets_data_root = os.path.join(os.environ['HYDROSOLVER_ROOT_DIR'], 'lib', 'python2.7', 'site-packages', 'salome', 'tests', 'data')
+         presets_data_root = os.path.join(os.environ['HYDROSOLVER_ROOT_DIR'], 'lib', pythonVersion, 'site-packages', 'salome', 'tests', 'data')
          file_path = os.path.join(presets_data_root, 'bnd_conditions_presets.txt')
          reader = boundaryConditions.PresetReader(file_path)
          self.presets = reader.read()
-     
      """Initialize widget properties"""
      def init_widgets(self):
          self.medFileEdit.setReadOnly(True)
          self.bndConditionsFileEdit.setReadOnly(True)
          self.resultBndConditionsFileEdit.setReadOnly(True)
-         
          delegate = ValueDelegate(self.boundaryConditionsTable)
          self.boundaryConditionsTable.setItemDelegateForColumn(1, delegate)
          self.boundaryConditionsTable.setItemDelegateForColumn(2, delegate)
          self.boundaryConditionsTable.setItemDelegateForColumn(3, delegate)
          self.boundaryConditionsTable.setItemDelegateForColumn(4, delegate)
-     
      """Process cell data changes"""
      def on_cell_changed(self, row, column):
+         #print "on_cell_changed"
          lihbor = liubor = livbor = litbor = None
-         
          item = self.boundaryConditionsTable.item(row, 1)
          if item:
              lihbor = get_int(str(item.text()))
-         
          item = self.boundaryConditionsTable.item(row, 2)
          if item:
              liubor = get_int(str(item.text()))
-             
          item = self.boundaryConditionsTable.item(row, 3)
          if item:
              livbor = get_int(str(item.text()))
-             
          item = self.boundaryConditionsTable.item(row, 4)
          if item:
              litbor = get_int(str(item.text()))
-             
          preset_name = get_preset_name(self.presets, lihbor, liubor, livbor, litbor)
-         
+         #print "on_cell_changed ", preset_name, lihbor, liubor, livbor, litbor
          combo = self.boundaryConditionsTable.cellWidget(row, 0)
-         if isinstance(combo, QtGui.QComboBox):
+         if isinstance(combo, QComboBox):
              ind = combo.findText(preset_name)
              if ind >= 0:
+                 combo.currentIndexChanged.disconnect(self.on_preset_changed)
                  combo.setCurrentIndex(ind)
-     
+                 combo.currentIndexChanged.connect(self.on_preset_changed)
      """Save the user data to boundary conditions file"""
      def on_apply(self):
          # Save boundary conditions file
          if not self.is_valid():
+             print('Not valid')
              return False
-         
-         file_path = self.get_output_path()
+         if self.sameAsInputCB.isChecked():
+           file_path = self.bndConditionsFileEdit.text()
+         else:
+           file_path = self.resultBndConditionsFileEdit.text()
+         print('File path:', file_path)
          writer = boundaryConditions.BoundaryConditionWriter(file_path)
-         
          conditions = []
-         for row_nb in xrange(0, self.boundaryConditionsTable.rowCount()):
+         for row_nb in range(0, self.boundaryConditionsTable.rowCount()):
              lihbor = str(self.boundaryConditionsTable.item(row_nb, 1).text())
              liubor = str(self.boundaryConditionsTable.item(row_nb, 2).text())
              livbor = str(self.boundaryConditionsTable.item(row_nb, 3).text())
              litbor = str(self.boundaryConditionsTable.item(row_nb, 4).text())
-             
-             if lihbor and liubor and livbor and litbor:
-                 group_name = str(self.boundaryConditionsTable.item(row_nb, 5).text())
-                 conditions.append(boundaryConditions.BoundaryCondition(lihbor, liubor, livbor, litbor, group_name))
-                 
+             group_name = str(self.boundaryConditionsTable.item(row_nb, 5).text())
+             if lihbor != "":
+               conditions.append(boundaryConditions.BoundaryCondition(lihbor, liubor, livbor, litbor, group_name))
          writer.write(conditions)
-                     
          return True
-     
      """Save the user data to boundary conditions file and close the dialog"""
      def on_apply_and_close(self):
          if self.on_apply():
              self.accept()
-        
      """Select MED file"""
      def on_med_file_browse(self):
          # Get file path
-         file_path = QtGui.QFileDialog.getOpenFileName(self, self.tr("Open MED file"), "", self.tr("MED files (*.med)"))
+         file_path, filt = QFileDialog.getOpenFileName(self, self.tr("Open MED file"), "", self.tr("MED files (*.med)"))
          if not file_path:
              return
-         
          # Get names of groups on edges
          groups = get_med_groups_on_edges(str(file_path))
-         
          if len(groups) > 0:
              # Display the path
              self.medFileEdit.setText(file_path)
-             
              # Update table
              self.set_groups(groups)
          else:
-             QtGui.QMessageBox.warning(self, self.tr("Warning"), self.tr("Can't get group names from the selected MED file."))
-     
+             QMessageBox.warning(self, self.tr("Warning"), self.tr("Can't get group names from the selected MED file."))
+         self.boundaryConditionsTable.resizeColumnsToContents()
      """Select boundary conditions file"""
      def on_bnd_file_browse(self):
-         file_path = QtGui.QFileDialog.getOpenFileName(self, self.tr("Open boundary conditions file"))
-         
+         file_path, filt = QFileDialog.getOpenFileName(self, self.tr("Open boundary conditions file"))
          if file_path:
              self.bndConditionsFileEdit.setText(file_path)
              reader = boundaryConditions.BoundaryConditionReader(file_path)
              self.input_conditions.clear()
              for cnd in conditions:
                  self.input_conditions[cnd.group] = (cnd.lihbor, cnd.liubor, cnd.livbor, cnd.litbor)
-             
              # Check read errors
              read_errors = reader.errors
              if len( read_errors ) > 0:
                  msg = "\n".join(read_errors)
-                 QtGui.QMessageBox.warning(self, self.tr("Warning"), msg)
-             
+                 QMessageBox.warning(self, self.tr("Warning"), msg)
              if len(self.input_conditions) > 0:
                  self.update_table()
              else:
-                 QtGui.QMessageBox.warning(self, self.tr("Warning"), self.tr("No conditions have been read from the file."))
-     
+                 QMessageBox.warning(self, self.tr("Warning"), self.tr("No conditions have been read from the file."))
      """Called on preset selection in the first column of the table"""
      def on_preset_changed(self):
+         #print"on_preset_changed"
          combo = self.sender()
-         
          preset = str(combo.currentText())
-        
-         if preset and self.presets.has_key(preset):
+         if preset and preset in self.presets:
              values = self.presets[preset]
-             row_nb, is_ok = combo.property(ROW_PROPERTY_NAME).toInt()
-             
-             if is_ok and row_nb >= 0 and row_nb < self.boundaryConditionsTable.rowCount():
+             row_nb = combo.property(ROW_PROPERTY_NAME)
+             if row_nb >= 0 and row_nb < self.boundaryConditionsTable.rowCount():
                  lihbor = values[0]
                  liubor = values[1]
                  livbor = values[2]
                  litbor = values[3]
-                 
-                 if lihbor:
-                     self.boundaryConditionsTable.item(row_nb, 1).setText(str(lihbor))
-                     
-                 if liubor:
-                     self.boundaryConditionsTable.item(row_nb, 2).setText(str(liubor))    
-                     
-                 if livbor:
-                     self.boundaryConditionsTable.item(row_nb, 3).setText(str(livbor))    
-                     
-                 if litbor:
-                     self.boundaryConditionsTable.item(row_nb, 4).setText(str(litbor))    
-         
+                 #print "on_preset_changed ", preset, lihbor, liubor, livbor, litbor
+                 #if lihbor is not None:
+                 self.boundaryConditionsTable.item(row_nb, 1).setText(str(lihbor))
+                 #if liubor is not None:
+                 self.boundaryConditionsTable.item(row_nb, 2).setText(str(liubor))
+                 #if livbor is not None:
+                 self.boundaryConditionsTable.item(row_nb, 3).setText(str(livbor))
+                 #if litbor is not None:
+                 self.boundaryConditionsTable.item(row_nb, 4).setText(str(litbor))
 -                
++
+         if isinstance(combo, QComboBox):
+             ind = combo.findText(preset)
+             if ind >= 0:
+                 combo.setCurrentIndex(ind)
      """Define result file path"""
      def on_result_file_browse(self):
-         file_path = QtGui.QFileDialog.getSaveFileName(self, self.tr("Select output file path"))
+         file_path, filt = QFileDialog.getSaveFileName(self, self.tr("Select output file path"))
+         #print file_path
          if file_path:
              self.resultBndConditionsFileEdit.setText(file_path)
-     
      """Set groups list"""
      def set_groups(self, groups):
+         #print "set_groups"
          self.boundaryConditionsTable.setRowCount(0)
          for group in groups:
              # Add row
              row_nb = self.boundaryConditionsTable.rowCount()
              self.boundaryConditionsTable.insertRow(row_nb)
-             
              # 'Preset' column
-             combo = QtGui.QComboBox(self)
-             combo.addItem('')
+             combo = QComboBox(self)
+             #combo.addItem('')
              if len(self.presets) > 0:
-                 combo.addItems(self.presets.keys())
-             
+                 items = list(self.presets.keys())
+                 items.sort()
+                 combo.addItems(items)
              combo.setProperty(ROW_PROPERTY_NAME, row_nb)
-             
              combo.currentIndexChanged.connect(self.on_preset_changed)
-                 
              self.boundaryConditionsTable.setCellWidget(row_nb, 0, combo)
-             
              # 'LIHBOR' column
-             self.boundaryConditionsTable.setItem(row_nb, 1, QtGui.QTableWidgetItem(''))
-             
+             self.boundaryConditionsTable.setItem(row_nb, 1, QTableWidgetItem(''))
              # 'LIUBOR' column
-             self.boundaryConditionsTable.setItem(row_nb, 2, QtGui.QTableWidgetItem(''))
-             
+             self.boundaryConditionsTable.setItem(row_nb, 2, QTableWidgetItem(''))
              # 'LIVBOR' column
-             self.boundaryConditionsTable.setItem(row_nb, 3, QtGui.QTableWidgetItem(''))
-             
+             self.boundaryConditionsTable.setItem(row_nb, 3, QTableWidgetItem(''))
              # 'LITBOR' column
-             self.boundaryConditionsTable.setItem(row_nb, 4, QtGui.QTableWidgetItem(''))
-             
+             self.boundaryConditionsTable.setItem(row_nb, 4, QTableWidgetItem(''))
              # 'Group' column
-             item = QtGui.QTableWidgetItem(group)
+             item = QTableWidgetItem(group)
              font = item.font()
              font.setBold(True)
              item.setFont(font)
-             item.setFlags(QtCore.Qt.ItemIsEnabled)
+             item.setFlags(Qt.ItemIsEnabled)
              self.boundaryConditionsTable.setItem(row_nb, 5, item)
-         
          self.update_table()
-     
      """Update conditions data in the table from the conditions input file"""
      def update_table(self):
+         #print "update_table"
          is_updated = False
-     
-         nb_rows = self.boundaryConditionsTable.rowCount()   
-         for row_nb in xrange(0, nb_rows):
+         nb_rows = self.boundaryConditionsTable.rowCount()
+         for row_nb in range(0, nb_rows):
              group_name = str(self.boundaryConditionsTable.item(row_nb, 5).text())
-             if self.input_conditions.has_key(group_name):
+             if group_name in self.input_conditions:
 -                
++
                  values = self.input_conditions[group_name]
-                 
+                 #print values
                  lihbor = str(values[0])
                  liubor = str(values[1])
                  livbor = str(values[2])
                  litbor = str(values[3])
-                 
+                 #print lihbor, liubor, livbor, litbor
                  self.boundaryConditionsTable.item(row_nb, 1).setText(lihbor)
                  self.boundaryConditionsTable.item(row_nb, 2).setText(liubor)
                  self.boundaryConditionsTable.item(row_nb, 3).setText(livbor)
                  self.boundaryConditionsTable.item(row_nb, 4).setText(litbor)
-                 
+ #                 combo = self.boundaryConditionsTable.cellWidget(row_nb, 0)
+ #                 if isinstance(combo, QComboBox):
+ #                     preset_name = get_preset_name(self.presets, lihbor, liubor, livbor, litbor)
+ #                     ind = combo.findText(preset_name)
+ #                     if ind >= 0:
+ #                         combo.setCurrentIndex(ind)
                  is_updated = True
-                 
          if not is_updated and nb_rows > 0 and len(self.input_conditions) > 0:
-             QtGui.QMessageBox.information(self, self.tr("Information"), self.tr("No one group name from the MED file is presented in the input list of conditions."))
-     
+             QMessageBox.information(self, self.tr("Information"), self.tr("No one group name from the MED file is presented in the input list of conditions."))
      """Get output file path"""
      def get_output_path(self):
          path = self.bndConditionsFileEdit.text()
-         
          if not self.sameAsInputCB.isChecked():
              path = self.resultBndConditionsFileEdit.text()
-         
          return path
-     
      """Check if the input data is valid"""
      def is_valid(self):
-         is_ok = False
-     
+         is_ok = True
          if self.boundaryConditionsTable.rowCount() < 1:
-             QtGui.QMessageBox.critical(self, self.tr("Insufficient input data"), self.tr("Boundary conditions list is empty."))
-         elif self.get_output_path().isEmpty():
-             QtGui.QMessageBox.critical(self, self.tr("Insufficient input data"), self.tr("Output file path is empty."))
+             QMessageBox.critical(self, self.tr("Insufficient input data"), self.tr("Boundary conditions list is empty."))
+         elif len(self.get_output_path())==0:
+             QMessageBox.critical(self, self.tr("Insufficient input data"), self.tr("Output file path is empty."))
          else:
-             has_incomplete_lines = False
-             is_table_empty = True
-             for row_nb in xrange(0, self.boundaryConditionsTable.rowCount()):
+             for row_nb in range(0, self.boundaryConditionsTable.rowCount()):
+                 has_empty_cells = True
                  lihbor = str(self.boundaryConditionsTable.item(row_nb, 1).text())
                  liubor = str(self.boundaryConditionsTable.item(row_nb, 2).text())
                  livbor = str(self.boundaryConditionsTable.item(row_nb, 3).text())
                  litbor = str(self.boundaryConditionsTable.item(row_nb, 4).text())
-               
-                 has_filled_cells = True if (lihbor or liubor or livbor or litbor) else False
+                 #print "test valid: ", lihbor, liubor, livbor, litbor
+                 if (lihbor != '') and (liubor != '')  and (livbor != '')  and (litbor != '') :
+                     has_empty_cells = False # Full lines are OK
+                     #print "valid: full line"
+                 if (lihbor == '') and (liubor == '') and (livbor == '') and (litbor == ''):
+                     has_empty_cells = False # Empty lines are OK
+                     #print "valid: empty line"
  
-                 if has_filled_cells:
-                   is_table_empty = False
-                 all_cells_filled  = True if (lihbor and liubor and livbor and litbor) else False
-                 if has_filled_cells and (not all_cells_filled):
-                     has_incomplete_lines = True
+                 if has_empty_cells:
+                     #print "not valid!"
+                     QMessageBox.critical(self, self.tr("Insufficient input data"), self.tr("Table has empty cell(s)."))
+                     is_ok = False
                      break
-             
-             if is_table_empty:
-                 QtGui.QMessageBox.critical(self, self.tr("Insufficient input data"), self.tr("Table is empty."))              
-             elif has_incomplete_lines:
-                 QtGui.QMessageBox.critical(self, self.tr("Insufficient input data"), self.tr("Table has incomplete line(s)."))
-             else:
-                 is_ok = True
-             
          return is_ok
-         
      """Shows help page"""
      def on_help(self):
          msg = """
          <h2>Boundary conditions dialog</h2>
-         
          This dialog is used to read and write boundary conditions files.
          Below is the description of the dialog controls.
-         
-         <h3>MED file</h3> 
-         This field allows selection of a med file (via the standard file open dialog). 
-         The file must contain groups of edges, if this is not the case a warning message appears. 
+         <h3>MED file</h3>
+         This field allows selection of a med file (via the standard file open dialog).
+         The file must contain groups of edges, if this is not the case a warning message appears.
          The filling of this field is mandatory.
  
-         <h3>Boundary conditions file</h3> 
-         This field allows selecting the file of boundary conditions (via the standard file open dialog). 
-         The data from this file is displayed in the table "Boundary conditions". 
+         <h3>Boundary conditions file</h3>
+         This field allows selecting the file of boundary conditions (via the standard file open dialog).
+         The data from this file is displayed in the table "Boundary conditions".
          This field is optional; if it is not selected the table will not be prefilled.
  
-         <h3>Result boundary conditions file</h3> 
-         This field allows selecting the file in which to save the data (via the standard file save dialog). 
+         <h3>Result boundary conditions file</h3>
+         This field allows selecting the file in which to save the data (via the standard file save dialog).
          This field is mandatory if the "Same as the input" check box is unchecked.
-          
-         <h3>Boundary conditions table</h3> 
+         <h3>Boundary conditions table</h3>
          Contains data representing the list of boundary conditions.
          The first column contains a list of presets.
          The last columns is read-only, it contains names of group of edges from the selected MED file.
          Other columns is for LIHBOR, LIUBOR, LIVBOR and LITBOR parameters, which can take a value ranging between 0 and 6.
          <br>
          <br>
-         When the table is filled and the output file is defined, the user clicks on "Apply" or "Apply and Close" button 
+         When the table is filled and the output file is defined, the user clicks on "Apply" or "Apply and Close" button
          to perform the data export to the file.
          Click on "Close" button does not lead to saving the data and just closes the dialog.
          """
-         QtGui.QMessageBox.about(self, self.tr("About boundary conditions dialog"), msg);
-         pass
+         QMessageBox.about(self, self.tr("About boundary conditions dialog"), msg);
+         pass