Salome HOME
d01a04303100464476a64df94edba95d8b71b478
[modules/hydrosolver.git] / src / salome_hydro / interpolz_gui.py
1
2 import sys, os
3 import string
4 #sys.path.append(os.path.join(os.environ['MEDFILE_ROOT_DIR'], 'lib/python2.7/site-packages/med'))
5 #sys.path.append(os.path.join(os.environ['MEDFICHIER_INSTALL_DIR'], 'lib/python2.7/site-packages/med'))
6 hydro_solver_root = os.path.join(os.environ['HYDROSOLVER_ROOT_DIR'], 'lib', 'python2.7', 'site-packages', 'salome', 'salome', 'hydro')
7 #sys.path.append(hydro_solver_root)
8
9 import salome
10 salome.salome_init()
11
12 import SMESH
13 from salome.smesh import smeshBuilder
14 smesh = smeshBuilder.New(salome.myStudy)
15
16 #import MEDLoader
17 import HYDROPy
18
19 from PyQt5.QtWidgets import QDialog, QFileDialog, QTableWidgetItem, QComboBox, QMessageBox
20 from PyQt5 import uic
21
22 import SalomePyQt
23 import libSALOME_Swig
24 salome_gui = libSALOME_Swig.SALOMEGUI_Swig()
25
26 from generate_interpolz import generate
27
28 def get_med_groups( file_path ):
29     #print "get_med_groups", file_path
30     try:
31         #meshes = MEDLoader.GetMeshNames(file_path)
32         (meshes, status) = smesh.CreateMeshesFromMED(file_path)
33     except:
34         print 'No meshes found'
35         return []
36     if len(meshes)==0:
37         print 'No mesh found'
38         return []
39     mesh1 = meshes[0]
40     print 'Found mesh:', mesh1
41     try:
42         #groups = list(MEDLoader.GetMeshGroupsNames(file_path, mesh1))
43         grps = mesh1.GetGroups()
44         groups = [grp.GetName() for grp in grps if grp.GetType() == SMESH.FACE]
45         if len(groups) == 0:
46           print "Problem! There are no groups of faces in the mesh!"
47           print "Please create at least the groups of faces corresponding to each region of the HYDRO case"
48           return []
49         print 'Found groups:', groups
50     except:
51         print 'No groups found'
52         return []
53     return groups
54
55 def get_hydro_regions( calc_case_name ):
56     aStudyId = salome.myStudyId
57     doc = HYDROPy.HYDROData_Document.Document( aStudyId )
58     case = doc.FindObjectByName( calc_case_name )
59     if isinstance(case, HYDROPy.HYDROData_CalculationCase):
60       regions = case.GetRegions()
61       regions_names = []
62       for r in regions:
63         rname = r.GetName()
64         regions_names.append( str(rname) )
65
66 #       shape_groups = case.GetGeometryGroups()
67 #       for sg in shape_groups:
68 #           sgname = sg.GetName()
69 #           regions_names.append( sgname )
70
71       return regions_names
72     else:
73       return []
74
75 def get_selected_calc_case():
76     ind = SalomePyQt.SalomePyQt.getObjectBrowser().selectionModel().selectedIndexes()
77     aStudyId = salome.myStudyId
78     doc = HYDROPy.HYDROData_Document.Document( aStudyId )
79     for i in ind:
80         if i.column()==0:
81             name = str(i.data())
82             case = doc.FindObjectByName( name )
83             if isinstance(case, HYDROPy.HYDROData_CalculationCase):
84                 return name
85     return None
86
87 class InterpolzDlg( QDialog ):
88     def __init__(self, parent = None):
89         QDialog.__init__( self, parent )
90         p = hydro_solver_root
91         uic.loadUi( p+'/interpolz.ui', self )
92         self.setWindowTitle( 'Generate interpolz script' )
93         SalomePyQt.SalomePyQt.getObjectBrowser().selectionChanged.connect(self.onSelectionChanged)
94         self.btnOutputPath.clicked.connect(self.onOutputFile)
95         self.btnMEDFile.clicked.connect(self.onMEDFile)
96         self.CalcCase.textChanged.connect(self.onCalcCaseChanged)
97         self.MEDFile.textChanged.connect(self.onMEDChanged)
98         self.UndefZ.setRange( -100000, 100000 )
99         self.UndefZ.setValue( -9999 )
100         self.InterpMethod.addItem( "Interpolation at the nearest point" )
101         self.InterpMethod.addItem( "Linear interpolation on a cloud triangulation" )
102         self.InterpMethod.currentIndexChanged.connect(self.onInterpChanged)
103         self.ApplyClose.clicked.connect(self.onApplyClose)
104         self.Apply.clicked.connect(self.onApply)
105         self.Close.clicked.connect(self.onClose)
106         self.Help.clicked.connect(self.onHelp)
107         self.onSelectionChanged()
108
109     def onSelectionChanged( self ):
110         calc_case_name = get_selected_calc_case()
111         if calc_case_name is not None:
112           self.CalcCase.setText( calc_case_name )
113
114     def onOutputFile( self ):
115       caption = "Python file"
116       mask = "*.py"
117       fname, filt = QFileDialog.getSaveFileName( self, caption, ".", mask )
118       if fname!=None and fname!="":
119         if string.split(fname, '.')[-1] != 'py':
120           fname += '.py'
121         self.OutputPath.setText( fname )
122
123     def onMEDFile( self ):
124       caption = "MED file"
125       mask = "*.med"
126       fname, filt = QFileDialog.getOpenFileName( self, caption, ".", mask )
127       if fname!=None and fname!="":
128         self.MEDFile.setText( fname )
129
130     def onCalcCaseChanged( self ):
131       self.regions = get_hydro_regions( str(self.CalcCase.text()) )
132       self.onMEDChanged()
133
134     def onMEDChanged( self ):
135       self.med_groups = get_med_groups( str(self.MEDFile.text()) )
136       print self.med_groups
137       n = len( self.med_groups )
138       self.Groups.setRowCount( n )
139       for i in range( 0, n ):
140         if self.Groups.item( i, 0 ) is None:
141           self.Groups.setItem( i, 0, QTableWidgetItem() )
142           self.Groups.setItem( i, 1, QTableWidgetItem() )
143           self.Groups.setItem( i, 2, QTableWidgetItem() )
144         self.Groups.item( i, 0 ).setText( self.med_groups[i] )
145
146         cb = QComboBox( self.Groups )
147         cb.addItem( 'None' )
148         for r in self.regions:
149           cb.addItem( r )
150         self.Groups.setCellWidget( i, 1, cb )
151
152         icb = QComboBox( self.Groups )
153         icb.addItem( 'Interpolation at the nearest point' )
154         icb.addItem( 'Linear interpolation on a cloud triangulation' )
155         self.Groups.setCellWidget( i, 2, icb )
156         icb.currentIndexChanged.connect(self.onCBInterpChanged)
157                 
158     def onCBInterpChanged( self ):
159       ind_set = set()
160       for i in range( 0, self.Groups.rowCount() ):
161         ind_set.add( self.Groups.cellWidget( i, 2 ).currentIndex() )
162       if len(ind_set) == 2:
163         self.InterpMethod.setStyleSheet("QComboBox { background-color: grey; }")
164       elif len(ind_set) == 1:
165         self.InterpMethod.setStyleSheet("")
166
167     def onInterpChanged( self ):
168       n = self.Groups.rowCount()
169       for i in range( 0, n ):
170         icb = self.Groups.cellWidget(i, 2)
171         icb.setCurrentIndex(self.InterpMethod.currentIndex())
172  
173     def onApplyClose( self ):
174         if self.onApply():
175             self.onClose()
176
177     def onApply( self ):
178         path = str(self.OutputPath.text())
179         calc_case = str(self.CalcCase.text())
180         med_file = str(self.MEDFile.text())
181         med_groups_regions = {}
182         regions_interp_method = {}
183         for i in range( 0, self.Groups.rowCount() ):
184             med_group = str( self.Groups.item( i, 0 ).text() )
185             hydro_reg = str( self.Groups.cellWidget( i, 1 ).currentText() )
186             if len(med_group)>0 and len(hydro_reg)>0 and hydro_reg != 'None' :
187                 med_groups_regions[med_group] = hydro_reg
188             interp_ind = str( self.Groups.cellWidget( i, 2 ).currentIndex() )
189             regions_interp_method[hydro_reg] = interp_ind
190         z_undef = self.UndefZ.value()
191         #interp = str(self.InterpMethod.currentText())
192
193         msg = ""
194         if len(path)==0:
195             msg = "Please input the output path"
196         elif len(calc_case)==0:
197             msg = "Please choose the calculation case"
198         elif len(med_file)==0:
199             msg = "Please choose the MED file"
200         elif len(med_groups_regions)==0:
201             msg = "Please fill groups table"
202         #elif len(interp)==0:
203         #    msg = "Please choose interpolation method"
204
205         result = False
206         if len(msg)==0:
207             iinterp = 0
208             #if 'Linear' in interp:
209             #  iinterp = 1
210             #generate( path, calc_case, med_file, med_groups_regions, z_undef, iinterp )
211             generate( path, calc_case, med_file, med_groups_regions, z_undef, regions_interp_method )
212             msg = "InterpolZ script is successfully generated"
213             result = True
214
215         QMessageBox.information( self, "", msg )
216         return result
217
218     def onClose( self ):
219         self.close()
220
221     """Shows help page"""
222     def onHelp( self ):
223         msg = """
224         <h2>Interpolz dialog</h2>
225
226         This dialog is a tool for automation the writing of the script <b>interpolz.py</b>.
227
228         <h3>Calculation case</h3>
229         The name of the calculation case. It can be filled automatically on the base of selection or can be input by user.
230
231         <h3>Output path</h3>
232         The path for the output, i.e. the path of the target script interpolz.
233
234         <h3>MED file</h3>
235         The path to MED file where MED groups are extracted.
236
237         <h3>Method</h3>
238         The interpolation method (interpolation at the nearest point and linear interpolation from a triangulation of the cloud of points).
239
240         <h3>Undefined Z</h3>
241         The Z value for nodes outside the regions.
242
243         <h3>Table</h3>
244         The table with MED groups and regions names.
245
246         When the data is input, the user clicks on "Apply" or "Apply and Close" button to perform the script generation.
247         """
248         QMessageBox.about(self, self.tr("About boundary conditions dialog"), msg);
249
250
251 if __name__=='__main__':
252   dlg = InterpolzDlg()
253   dlg.show()