Salome HOME
correction on interpolz dialog
[modules/hydrosolver.git] / src / salome_hydro / interpolz_gui.py
1
2 import sys, os
3 import string
4 import sysconfig
5 pythonVersion = 'python' + sysconfig.get_python_version()
6 hydro_solver_root = os.path.join(os.environ['HYDROSOLVER_ROOT_DIR'], 'lib', pythonVersion, 'site-packages', 'salome', 'salome', 'hydro')
7
8 import salome
9 salome.salome_init()
10
11 import SMESH
12 from salome.smesh import smeshBuilder
13 smesh = smeshBuilder.New()
14
15 #import MEDLoader
16 import HYDROPy
17
18 from PyQt5.QtWidgets import QDialog, QFileDialog, QTableWidgetItem, QComboBox, QMessageBox
19 from PyQt5 import uic
20
21 import SalomePyQt
22 import libSALOME_Swig
23 salome_gui = libSALOME_Swig.SALOMEGUI_Swig()
24
25 from .generate_interpolz import generate, generate_B
26
27 def get_med_groups( file_path ):
28     #print "get_med_groups", file_path
29     try:
30         #meshes = MEDLoader.GetMeshNames(file_path)
31         (meshes, status) = smesh.CreateMeshesFromMED(file_path)
32     except:
33         print('No meshes found')
34         return []
35     if len(meshes)==0:
36         print('No mesh found')
37         return []
38     mesh1 = meshes[0]
39     print('Found mesh:', mesh1)
40     try:
41         #groups = list(MEDLoader.GetMeshGroupsNames(file_path, mesh1))
42         grps = mesh1.GetGroups()
43         groups = [grp.GetName() for grp in grps if grp.GetType() == SMESH.FACE]
44         if len(groups) == 0:
45           print("Problem! There are no groups of faces in the mesh!")
46           print("Please create at least the groups of faces corresponding to each region of the HYDRO case")
47           return []
48         print('Found groups:', groups)
49     except:
50         print('No groups found')
51         return []
52     return groups
53
54 def get_hydro_regions( calc_case_name ):
55     #aStudyId = salome.myStudyId
56     doc = HYDROPy.HYDROData_Document.Document()
57     case = doc.FindObjectByName( calc_case_name )
58     if isinstance(case, HYDROPy.HYDROData_CalculationCase):
59       regions = case.GetRegions()
60       regions_names = []
61       for r in regions:
62         rname = r.GetName()
63         regions_names.append( str(rname) )
64
65 #       shape_groups = case.GetGeometryGroups()
66 #       for sg in shape_groups:
67 #           sgname = sg.GetName()
68 #           regions_names.append( sgname )
69
70       return regions_names
71     else:
72       return []
73
74 def get_selected_calc_case():
75     ind = SalomePyQt.SalomePyQt.getObjectBrowser().selectionModel().selectedIndexes()
76     #aStudyId = salome.myStudyId
77     doc = HYDROPy.HYDROData_Document.Document()
78     for i in ind:
79         if i.column()==0:
80             name = str(i.data())
81             case = doc.FindObjectByName( name )
82             if isinstance(case, HYDROPy.HYDROData_CalculationCase):
83                 return name
84     return None
85
86 def get_selected_bathy():
87     ind = SalomePyQt.SalomePyQt.getObjectBrowser().selectionModel().selectedIndexes()
88     #aStudyId = salome.myStudyId
89     doc = HYDROPy.HYDROData_Document.Document()
90     for i in ind:
91         if i.column()==0:
92             name = str(i.data())
93             case = doc.FindObjectByName( name )
94             if isinstance(case, HYDROPy.HYDROData_Bathymetry):
95                 return name
96     return None
97
98 class InterpolzDlg( QDialog ):
99     def __init__(self, parent = None):
100         QDialog.__init__( self, parent )
101         p = hydro_solver_root
102         uic.loadUi( p+'/interpolz.ui', self )
103         self.setWindowTitle( 'Generate interpolz script' )
104         SalomePyQt.SalomePyQt.getObjectBrowser().selectionChanged.connect(self.onSelectionChanged)
105         self.btnOutputPath.clicked.connect(self.onOutputFile)
106         self.btnMEDFile.clicked.connect(self.onMEDFile)
107         self.CalcCase.textChanged.connect(self.onCalcCaseChanged)
108         #self.BathyName.textChanged.connect(self.onBathyNameChanged)
109         self.MEDFile.textChanged.connect(self.onMEDChanged)
110         self.UndefZ.setRange( -100000, 100000 )
111         self.UndefZ.setValue( -9999 )
112         self.UndefZ_B.setRange( -100000, 100000 )
113         self.UndefZ_B.setValue( -9999 )
114         self.InterpMethod_B.addItem( "Interpolation at the nearest point" )
115         self.InterpMethod_B.addItem( "Linear interpolation on a cloud triangulation" )
116         self.InterpMethod.addItem( "Interpolation at the nearest point" )
117         self.InterpMethod.addItem( "Linear interpolation on a cloud triangulation" )
118         self.InterpMethod.currentIndexChanged.connect(self.onInterpChanged)
119         self.ApplyClose.clicked.connect(self.onApplyClose)
120         self.Apply.clicked.connect(self.onApply)
121         self.Close.clicked.connect(self.onClose)
122         self.Help.clicked.connect(self.onHelp)
123         self.onSelectionChanged()
124         self.tabWidget.setCurrentIndex(0)
125         self.regions = [] #to avoid attrib error
126
127     def onSelectionChanged( self ):
128         calc_case_name = get_selected_calc_case()
129         if calc_case_name is not None:
130           self.CalcCase.setText( calc_case_name )
131         bathy_name = get_selected_bathy()
132         if bathy_name is not None:
133           self.BathyName.setText( bathy_name )
134
135     def onOutputFile( self ):
136       caption = "Python file"
137       mask = "*.py"
138       fname, filt = QFileDialog.getSaveFileName( self, caption, ".", mask )
139       if fname!=None and fname!="":
140         if fname.split('.')[-1] != 'py':
141           fname += '.py'
142         self.OutputPath.setText( fname )
143
144     def onMEDFile( self ):
145       caption = "MED file"
146       mask = "*.med"
147       fname, filt = QFileDialog.getOpenFileName( self, caption, ".", mask )
148       if fname!=None and fname!="":
149         self.MEDFile.setText( fname )
150
151     def onCalcCaseChanged( self ):
152       self.regions = get_hydro_regions( str(self.CalcCase.text()) )
153       self.onMEDChanged()
154           
155         #def onBathyNameChanged( self ):
156     #  #self.regions = get_hydro_regions( str(self.CalcCase.text()) )
157     #  self.onMEDChanged()
158
159     def onMEDChanged( self ):
160       self.med_groups = get_med_groups( str(self.MEDFile.text()) )
161       print(self.med_groups)
162       n = len( self.med_groups )
163       self.Groups.setRowCount( n )
164       self.medGroupNames.clear()
165       for i in range( 0, n ):
166         self.medGroupNames.addItem(self.med_groups[i])
167
168       for i in range( 0, n ):
169         if self.Groups.item( i, 0 ) is None:
170           self.Groups.setItem( i, 0, QTableWidgetItem() )
171           self.Groups.setItem( i, 1, QTableWidgetItem() )
172           self.Groups.setItem( i, 2, QTableWidgetItem() )
173         self.Groups.item( i, 0 ).setText( self.med_groups[i] )
174
175         cb = QComboBox( self.Groups )
176         cb.addItem( 'None' )
177         for r in self.regions:
178           cb.addItem( r )
179         self.Groups.setCellWidget( i, 1, cb )
180
181         icb = QComboBox( self.Groups )
182         icb.addItem( 'Interpolation at the nearest point' )
183         icb.addItem( 'Linear interpolation on a cloud triangulation' )
184         self.Groups.setCellWidget( i, 2, icb )
185         icb.currentIndexChanged.connect(self.onCBInterpChanged)
186         
187
188     def onCBInterpChanged( self ):
189       ind_set = set()
190       for i in range( 0, self.Groups.rowCount() ):
191         ind_set.add( self.Groups.cellWidget( i, 2 ).currentIndex() )
192       if len(ind_set) == 2:
193         self.InterpMethod.setStyleSheet("QComboBox { background-color: grey; }")
194       elif len(ind_set) == 1:
195         self.InterpMethod.setStyleSheet("")
196
197     def onInterpChanged( self ):
198       n = self.Groups.rowCount()
199       for i in range( 0, n ):
200         icb = self.Groups.cellWidget(i, 2)
201         icb.setCurrentIndex(self.InterpMethod.currentIndex())
202  
203     def onApplyClose( self ):
204         if self.onApply():
205             self.onClose()
206
207     def onApply( self ):
208         path = str(self.OutputPath.text())
209         med_file = str(self.MEDFile.text())
210         print('current  TAB = ', self.tabWidget.currentIndex())
211         isScriptExec = self.cb_scriptExec.isChecked()
212
213         if self.tabWidget.currentIndex() == 0: #calc case tab
214             calc_case = str(self.CalcCase.text())
215             med_groups_regions = {}
216             regions_interp_method = {}
217             for i in range( 0, self.Groups.rowCount() ):
218                 med_group = str( self.Groups.item( i, 0 ).text() )
219                 hydro_reg = str( self.Groups.cellWidget( i, 1 ).currentText() )
220                 if len(med_group)>0 and len(hydro_reg)>0 and hydro_reg != 'None' :
221                     med_groups_regions[med_group] = hydro_reg
222                 interp_ind = str( self.Groups.cellWidget( i, 2 ).currentIndex() )
223                 regions_interp_method[hydro_reg] = interp_ind
224             z_undef = self.UndefZ.value()
225             #interp = str(self.InterpMethod.currentText())
226         
227             msg = ""
228             if len(path)==0:
229                 msg = "Please input the output path"
230             elif len(calc_case)==0:
231                 msg = "Please choose the calculation case"
232             elif len(med_file)==0:
233                 msg = "Please choose the MED file"
234             elif len(med_groups_regions)==0:
235                 msg = "Please fill groups table"
236             #elif len(interp)==0:
237             #    msg = "Please choose interpolation method"
238         
239             result = False
240             if len(msg)==0:
241                 #iinterp = 0
242                 #if 'Linear' in interp:
243                 #  iinterp = 1
244                 #generate( path, calc_case, med_file, med_groups_regions, z_undef, iinterp )
245                 generate( path, calc_case, med_file, med_groups_regions, z_undef, regions_interp_method )
246                 msg = "InterpolZ script is successfully generated"                
247                 result = True
248                 
249                 if isScriptExec:
250                     msg = msg + " and executed"
251                     exec(open(path).read())
252         
253             QMessageBox.information( self, "", msg )
254             return result
255             
256         elif self.tabWidget.currentIndex() == 1: #bathymetry tab
257             bathy_name = str(self.BathyName.text())
258             group_name = str(self.medGroupNames.currentText())
259             interp = str(self.InterpMethod_B.currentText())
260             z_undef = self.UndefZ_B.value()
261
262             msg = ""
263             if len(path)==0:
264                 msg = "Please input the output path"
265             elif len(bathy_name)==0:
266                 msg = "Please choose the bathymetry"
267             elif len(med_file)==0:
268                 msg = "Please choose the MED file"
269             elif len(group_name)==0:
270                 msg = "Please choose MED group"
271             elif len(interp)==0:
272                 msg = "Please choose interpolation method"
273         
274             result = False
275             
276             if len(msg)==0:
277                 iinterp = 0
278                 if 'Linear' in interp:
279                     iinterp = 1
280                 generate_B( path, bathy_name, med_file, group_name, z_undef, iinterp )
281                 msg = "InterpolZ_B script is successfully generated"
282                 result = True
283                 
284                 if isScriptExec:
285                     msg = msg + " and executed"
286                     exec(open(path).read())
287         
288             QMessageBox.information( self, "", msg )
289             return result
290
291     def onClose( self ):
292         self.close()
293
294     """Shows help page"""
295     def onHelp( self ):
296         msg = """
297         <h1>Interpolz dialog</h1>
298
299         This dialog is a tool for generation and execution of the script <b>interpolz.py</b>.
300
301         <h3>Input MED file</h3>
302         The path to MED file where MED groups are extracted.
303
304         <h2>TAB: Calculation Case</h2>
305
306         <ol><h3>Calculation case</h3>
307         The name of the calculation case. It can be filled automatically on the base of selection or can be set by user.
308
309         <h3>Method</h3>
310         The interpolation method (interpolation at the nearest point and linear interpolation from a triangulation of the cloud of points).
311
312         <h3>Undefined Z</h3>
313         The Z value for nodes outside the regions.
314
315         <h3>Table</h3>
316         The table with MED groups and regions names.</ol>
317
318         <h2>TAB: MED group bathymetry</h2>
319         
320         <ol><h3>Bathymetry</h3>
321         The name of the bathymetry. It can be filled automatically on the base of selection or can be set by user.
322
323         <h3>MED Group</h3>
324         Select the face group on which to apply the new bathymetry.
325         
326         <h3>Method</h3>
327         The interpolation method (interpolation at the nearest point and linear interpolation from a triangulation of the cloud of points).
328
329         <h3>Undefined Z</h3>
330         The Z value for nodes outside the regions.</ol>
331
332         <h3>Script output path</h3>
333         The path for the output, i.e. the path of the target script interpolz.
334
335         <h3>Execute the script</h3>
336         Execute the script on Apply if checked, or just keep it for later use.
337
338         When the data is set, the user clicks on "Apply" or "Apply and Close" button to perform the script generation.
339         """
340         QMessageBox.about(self, self.tr("About bathymetry interpolation dialog"), msg);
341
342
343 if __name__=='__main__':
344   dlg = InterpolzDlg()
345   dlg.show()