]> SALOME platform Git repositories - modules/paravis.git/blob - test/VisuPrs/Util/paravistest.py
Salome HOME
Copyrights update 2015.
[modules/paravis.git] / test / VisuPrs / Util / paravistest.py
1 # Copyright (C) 2010-2015  CEA/DEN, EDF R&D
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 #
19
20 """
21 This module provides auxiliary classes, functions and variables for testing.
22 """
23
24 #from __future__ import print_function
25
26 from math import fabs
27 import os
28 import tempfile
29 import getpass
30 from datetime import date
31
32 import salome
33
34
35 # Auxiliary variables
36
37 # Data directory
38 samples_dir = os.getenv("DATA_DIR")
39 datadir = None
40 tablesdir = None
41 if samples_dir is not None:
42     samples_dir = os.path.normpath(samples_dir)
43     datadir = samples_dir + "/MedFiles/"
44     tablesdir = samples_dir + "/Tables/"
45
46 # Graphics files extension
47 pictureext = os.getenv("PIC_EXT")
48 if pictureext == None:
49     pictureext = "png"
50
51
52 # Auxiliary classes
53 class RepresentationType:
54     """
55     Types of representation.
56     """
57     OUTLINE = 0
58     POINTS = 1
59     WIREFRAME = 2
60     SURFACE = 3
61     SURFACEEDGES = 4
62     VOLUME = 5
63     POINTSPRITE = 6
64
65     _type2name = {OUTLINE: 'Outline',
66                   POINTS: 'Points',
67                   WIREFRAME: 'Wireframe',
68                   SURFACE: 'Surface',
69                   SURFACEEDGES: 'Surface With Edges',
70                   VOLUME: 'Volume',
71                   POINTSPRITE: 'Point Sprite'}
72
73     @classmethod
74     def get_name(cls, type):
75         """Return paraview representation type by the primitive type."""
76         return cls._type2name[type]
77
78
79 class SalomeSession(object):
80     def __init__(self):
81         import runSalome
82         import sys
83         if "INGUI" in sys.argv:
84             sys.argv += ["--gui"]
85             sys.argv += ["--show-desktop=1"]
86             sys.argv += ["--splash=0"]
87             #sys.argv += ["--standalone=study"]
88             #sys.argv += ["--embedded=SalomeAppEngine,cppContainer,registry,moduleCatalog"]
89         else:
90             sys.argv += ["--terminal"]
91         sys.argv += ["--modules=MED,PARAVIS"]
92         clt, d = runSalome.main()
93         port = d['port']
94         self.port = port
95         return
96
97     #VTN: workaround for crash on CentOS.6.3.64
98     #def __del__(self):
99         #os.system('killSalomeWithPort.py {0}'.format(self.port))
100         #os.system('killSalomeWithPort.py ' + self.port)
101         #import killSalomeWithPort
102         #killSalomeWithPort.killMyPort(self.port)
103         #return
104     pass
105
106
107 # Auxiliary functions
108 def test_values(value, et_value, check_error=0):
109     """Test values."""
110     error = 0
111     length = len(value)
112     et_length = len(et_value)
113     if (length != et_length):
114         err_msg = "ERROR!!! There is different number of created " + str(length) + " and etalon " + str(et_length) + " values!!!"
115         print err_msg
116         error = error + 1
117     else:
118         for i in range(et_length):
119             if abs(et_value[i]) > 1:
120                 max_val = abs(0.001 * et_value[i])
121                 if abs(et_value[i] - value[i]) > max_val:
122                     err_msg = "ERROR!!! Got value " + str(value[i]) + " is not equal to etalon value " + str(ret_value[i]) + "!!!"
123                     print err_msg
124                     error = error + 1
125             else:
126                 max_val = 0.001
127                 if abs(et_value[i] - value[i]) > max_val:
128                     err_msg = "ERROR!!! Got value " + value[i] + " is not equal to etalon value " + et_value[i] + "!!!"
129                     error = error + 1
130     if check_error and error > 0:
131         err_msg = ("There is(are) some error(s) was(were) found... "
132                    "For more info see ERRORs above...")
133         raise RuntimeError(err_msg)
134     return error
135
136
137 def get_picture_dir(subdir):
138     res_dir = os.getenv("PARAVIS_TEST_PICS")
139     if not res_dir:
140         # Add username and current date to unify the directory
141         cur_user = getpass.getuser()
142         cur_date = date.today().strftime("%Y%m%d")
143         res_dir = tempfile.gettempdir() + \
144             "/pic_" + cur_user + \
145             "/test_" + cur_date
146     # Add subdirectory for the case to the directory path
147     res_dir += "/" + subdir
148     # Create the directory if doesn't exist
149     res_dir = os.path.normpath(res_dir)
150     if not os.path.exists(res_dir):
151         os.makedirs(res_dir)
152     else:
153         # Clean the directory
154         for root, dirs, files in os.walk(res_dir):
155             for f in files:
156                 os.remove(os.path.join(root, f))
157
158     return res_dir
159
160
161 def call_and_check(prs, property_name, value, do_raise=1, compare_toler=-1.0):
162     """Utility function for 3D viewer test for common check of different
163     types of presentation parameters set"""
164     if property_name == 'Representation':
165         if value in prs.GetProperty('RepresentationTypesInfo'):
166             prs.SetPropertyWithName(property_name, value)
167             error_string = None
168         else:
169             error_string = (str(value) + " value of " + property_name + " is not available for this type of presentations")
170     else:
171         try:
172             prs.SetPropertyWithName(property_name, value)
173         except ValueError:
174             error_string = (str(value) + "value of " + property_name + " is not available for this type of presentations")
175         else:
176             error_string = None
177     is_good = (error_string is None)
178     if not is_good:
179         if do_raise:
180             raise RuntimeError(error_string)
181         else:
182             print error_string
183     else:
184         # compare just set value and the one got from presentation
185         really_set_value = prs.GetPropertyValue(property_name)
186         is_equal = 1
187         if compare_toler > 0:
188             is_equal = (fabs(really_set_value - value) < compare_toler)
189         else:
190             is_equal = (really_set_value == value)
191         if not is_equal:
192             msg = str(really_set_value) + " has been set instead"
193             if do_raise:
194                 raise RuntimeError(msg)
195             else:
196                 print msg
197                 is_good = False
198
199     return is_good
200
201
202 def compare_lists(value, et_value, check_error=0, eps=1e-04):
203     """
204     Compare two lists: the same length and equality of corresponding items
205     param value - list to be compared
206     param et_value - etalon list
207     param check_error - flag to catch exception if errors>0
208     check_error=0 no exception, check_error !=0 catch exception
209     param eps - defines tolerance for comparison
210     return error - number of errors
211     """
212
213     error=0
214     length = len(value)
215     et_length = len(et_value)
216     if length != et_length:
217         print "ERROR!!! There is different number of items in created ", length, " and etalon ", et_length, " lists!!!"
218         error=error+1
219     else:
220         for i in range(et_length):
221             if abs(et_value[i]) > 1:
222                 MAX = abs(eps*et_value[i])           
223             else:
224                 MAX = eps
225             if abs(et_value[i] - value[i])> MAX:
226                 print "ERROR!!!", i, "-th  item", value[i], " is not equal to etalon item", et_value[i], "!!!"
227                 error=error+1
228     if check_error and error > 0:
229         raise RuntimeError, "There is(are) some error(s) was(were) found... For more info see ERRORs above..."
230     return error
231
232
233 def setShaded(view, shading):
234     """Utility function to set shaded mode in view"""
235     if shading == 0:
236         view.LightDiffuseColor = [1, 1, 1]
237     if shading == 1:
238         view.LightDiffuseColor = [0, 0, 0]
239
240
241 def TimeStampId(proxy):
242     """Return tuple for the given MED proxy: (mesh_name, {field_name: [entity, timestamp_id]})
243     Originally defined in KERNEL_TEST/Tools/CommonFunctions file.
244     """
245     import presentations
246     mesh_name = presentations.get_mesh_full_names(proxy).pop()
247     iterations = {}
248
249     # get list of field names
250     all_fields = proxy.GetProperty("FieldsTreeInfo")[::2]
251
252     # get timestamps
253     timestamps = proxy.TimestepValues.GetData()
254     timestamp_nb = len(timestamps)
255
256     for field in all_fields:
257         entity = presentations.get_field_entity(field)
258         field_short_name = presentations.get_field_short_name(field)
259
260         iterations[field_short_name] = [entity, timestamp_nb]
261
262     return mesh_name, iterations
263     
264     
265 def Import_Med_Field(paravis, file, field_names, check_errors=0, prs=[]):
266     """Builds presentations on the given fields of the MED file.
267     Originally defined in VISU_TEST/Grids/visu/ImportMedField/begin file.
268     
269     Arguments:
270       paravis      : PARAVIS instance     
271       file_name    : the full path to med file
272       field_names  : the list of field names (for ex: ["pression","temperature","vitesse"])
273       prs          : [[0,1,...], [], []]; empty list (sublist(s)) is ignored
274                      0-VISU.TGAUSSPOINTS
275                      1-VISU.TSCALARMAP
276                      2-VISU.TISOSURFACE
277                      3-VISU.TCUTPLANES
278                      4-VISU.TCUTLINES
279                      5-VISU.TDEFORMEDSHAPE
280                      6-VISU.TVECTORS
281                      7-VISU.TSTREAMLINES
282                      8-VISU.TPLOT3D
283                      9-VISU.TSCALARMAPONDEFORMEDSHAPE
284     """
285     import presentations
286     
287     nb_errors = 0
288     
289     print "File: ", file
290     
291     # check the file accessibility
292     if not os.access(file, os.F_OK):
293         msg = "File " + file + " does not exist!!!"
294         raise RuntimeError, msg
295
296     # import MED file
297     paravis.ImportFile(file)
298     proxy = presentations.pvs.GetActiveSource()
299     if proxy is None:
300         raise RuntimeError, "ERROR!!! Can't import file!!!"  
301     
302     for i in range(len(field_names)):
303         print "Name of the field: ", field_names[i]
304         
305         if len(prs) != 0:
306             if len(prs[i]) != 0:
307                 mesh_name, iterations = TimeStampId(proxy)
308                 
309                 if iterations.has_key(field_names[i]):
310                     entity = iterations[field_names[i]][0]
311                     iteration = iterations[field_names[i]][1]
312                 else:
313                     msg="There is no information about TimeStampId of the " + field_names[i] + " field!!!"
314                     raise RuntimeError, msg
315
316                 err = nb_errors
317                 
318                 for type in prs[i]:
319                     if type==0:
320                         if presentations.GaussPointsOnField(proxy, entity, field_names[i], iteration) is None:
321                             print "ERROR!!! Created GaussPoints presentation is None!!!"; nb_errors+=1
322                     if type==1:
323                         if presentations.ScalarMapOnField(proxy, entity, field_names[i], iteration) is None:
324                             print "ERROR!!! Created ScalarMap presentation is None!!!"; nb_errors+=1
325                     if type==2:
326                         if presentations.IsoSurfacesOnField(proxy, entity, field_names[i], iteration) is None:
327                             print "ERROR!!! Created IsoSurfaces presentation is None!!!"; nb_errors+=1
328                     if type==3:
329                         if presentations.CutPlanesOnField(proxy, entity, field_names[i], iteration) is None:
330                             print "ERROR!!! Created CutPlanes presentation is None!!!"; nb_errors+=1
331                     if type==4:
332                         if presentations.CutLinesOnField(proxy, entity, field_names[i], iteration) is None:
333                             print "ERROR!!! Created CutLines presentation is None!!!"; nb_errors+=1
334                     if type==5:
335                         if presentations.DeformedShapeOnField(proxy, entity, field_names[i], iteration) is None:
336                             print "ERROR!!! Created DeformedShape presentation is None!!!"; nb_errors+=1
337                     if type==6:
338                         if presentations.VectorsOnField(proxy, entity, field_names[i], iteration) is None:
339                             print "ERROR!!! Created Vectors presentation is None!!!"; nb_errors+=1
340                     if type==7:
341                         if presentations.StreamLinesOnField(proxy, entity, field_names[i], iteration) is None:
342                             print "ERROR!!! Created StreamLines presentation is None!!!"; nb_errors+=1
343                     if type==8:
344                         if presentations.Plot3DOnField(proxy, entity, field_names[i], iteration) is None:
345                             print "ERROR!!! Created Plot3D presentation is None!!!"; nb_errors+=1
346                     if type==9:
347                         if presentations.DeformedShapeAndScalarMapOnField(proxy, entity, field_names[i], iteration) is None:
348                             print "ERROR!!! Created ScalarMapOnDeformedShape presentation is None!!!"; nb_errors+=1
349                             
350                 # check if number of errors has increased
351                 if err == nb_errors:
352                     print "Presentation(s) creation...OK"
353
354     if nb_errors > 0 and check_errors:
355         raise RuntimeError, "There are some errors were occured!!! For more information see ERRORs above..."
356     else:
357         return nb_errors
358
359 def delete_with_inputs(obj):
360     """Deletes the given object with all its inputs"""
361     import pvsimple
362     
363     obj_to_delete = obj
364     while obj_to_delete is not None:
365         tmp_obj = obj_to_delete
366         obj_to_delete = None
367         if hasattr(tmp_obj, 'Input'):
368             obj_to_delete = tmp_obj.Input
369         
370         pvsimple.Delete(tmp_obj)
371
372 # Run Salome
373 salome_session = SalomeSession()
374 salome.salome_init()
375 session_server = salome.naming_service.Resolve('/Kernel/Session')
376 if session_server:
377     session_server.emitMessage("connect_to_study")
378     session_server.emitMessage("activate_viewer/ParaView")
379     pass
380