]> SALOME platform Git repositories - modules/paravis.git/blob - test/VisuPrs/Util/paravistest.py
Salome HOME
Porting to PV5.0.1
[modules/paravis.git] / test / VisuPrs / Util / paravistest.py
1 # Copyright (C) 2010-2016  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 # Auxiliary variables
33
34 # Data directory
35 samples_dir = os.getenv("DATA_DIR")
36 datadir = None
37 tablesdir = None
38 texturesdir = None
39 if samples_dir is not None:
40     samples_dir = os.path.normpath(samples_dir)
41     datadir = samples_dir + "/MedFiles/"
42     tablesdir = samples_dir + "/Tables/"
43     texturesdir = samples_dir + "/Textures/"
44
45 # Graphics files extension
46 pictureext = os.getenv("PIC_EXT")
47 if pictureext == None:
48     pictureext = "png"
49
50
51 # Auxiliary classes
52 class RepresentationType:
53     """
54     Types of representation.
55     """
56     OUTLINE = 0
57     POINTS = 1
58     WIREFRAME = 2
59     SURFACE = 3
60     SURFACEEDGES = 4
61     VOLUME = 5
62     POINTSPRITE = 6
63
64     _type2name = {OUTLINE: 'Outline',
65                   POINTS: 'Points',
66                   WIREFRAME: 'Wireframe',
67                   SURFACE: 'Surface',
68                   SURFACEEDGES: 'Surface With Edges',
69                   VOLUME: 'Volume',
70                   POINTSPRITE: 'Point Sprite'}
71
72     @classmethod
73     def get_name(cls, type):
74         """Return paraview representation type by the primitive type."""
75         return cls._type2name[type]
76
77
78 # Auxiliary functions
79 def test_values(value, et_value, check_error=0):
80     """Test values."""
81     error = 0
82     length = len(value)
83     et_length = len(et_value)
84     if (length != et_length):
85         err_msg = "ERROR!!! There is different number of created " + str(length) + " and etalon " + str(et_length) + " values!!!"
86         print err_msg
87         error = error + 1
88     else:
89         for i in range(et_length):
90             if abs(et_value[i]) > 1:
91                 max_val = abs(0.001 * et_value[i])
92                 if abs(et_value[i] - value[i]) > max_val:
93                     err_msg = "ERROR!!! Got value " + str(value[i]) + " is not equal to etalon value " + str(ret_value[i]) + "!!!"
94                     print err_msg
95                     error = error + 1
96             else:
97                 max_val = 0.001
98                 if abs(et_value[i] - value[i]) > max_val:
99                     err_msg = "ERROR!!! Got value " + value[i] + " is not equal to etalon value " + et_value[i] + "!!!"
100                     error = error + 1
101     if check_error and error > 0:
102         err_msg = ("There is(are) some error(s) was(were) found... "
103                    "For more info see ERRORs above...")
104         raise RuntimeError(err_msg)
105     return error
106
107
108 def get_picture_dir(subdir):
109     res_dir = os.getenv("PARAVIS_TEST_PICS")
110     if not res_dir:
111         # Add username and current date to unify the directory
112         cur_user = getpass.getuser()
113         cur_date = date.today().strftime("%Y%m%d")
114         res_dir = tempfile.gettempdir() + \
115             "/pic_" + cur_user + \
116             "/test_" + cur_date
117     # Add subdirectory for the case to the directory path
118     res_dir += "/" + subdir
119     # Create the directory if doesn't exist
120     res_dir = os.path.normpath(res_dir)
121     if not os.path.exists(res_dir):
122         os.makedirs(res_dir)
123     else:
124         # Clean the directory
125         for root, dirs, files in os.walk(res_dir):
126             for f in files:
127                 os.remove(os.path.join(root, f))
128
129     return res_dir
130
131
132 def call_and_check(prs, property_name, value, do_raise=1, compare_toler=-1.0):
133     """Utility function for 3D viewer test for common check of different
134     types of presentation parameters set"""
135     if property_name == 'Representation':
136         if value in prs.GetProperty('RepresentationTypesInfo'):
137             prs.SetPropertyWithName(property_name, value)
138             error_string = None
139         else:
140             error_string = (str(value) + " value of " + property_name + " is not available for this type of presentations")
141     else:
142         try:
143             prs.SetPropertyWithName(property_name, value)
144         except ValueError:
145             error_string = (str(value) + "value of " + property_name + " is not available for this type of presentations")
146         else:
147             error_string = None
148     is_good = (error_string is None)
149     if not is_good:
150         if do_raise:
151             raise RuntimeError(error_string)
152         else:
153             print error_string
154     else:
155         # compare just set value and the one got from presentation
156         really_set_value = prs.GetPropertyValue(property_name)
157         is_equal = 1
158         if compare_toler > 0:
159             is_equal = (fabs(really_set_value - value) < compare_toler)
160         else:
161             is_equal = (really_set_value == value)
162         if not is_equal:
163             msg = str(really_set_value) + " has been set instead"
164             if do_raise:
165                 raise RuntimeError(msg)
166             else:
167                 print msg
168                 is_good = False
169
170     return is_good
171
172
173 def compare_lists(value, et_value, check_error=0, eps=1e-04):
174     """
175     Compare two lists: the same length and equality of corresponding items
176     param value - list to be compared
177     param et_value - etalon list
178     param check_error - flag to catch exception if errors>0
179     check_error=0 no exception, check_error !=0 catch exception
180     param eps - defines tolerance for comparison
181     return error - number of errors
182     """
183
184     error=0
185     length = len(value)
186     et_length = len(et_value)
187     if length != et_length:
188         print "ERROR!!! There is different number of items in created ", length, " and etalon ", et_length, " lists!!!"
189         error=error+1
190     else:
191         for i in range(et_length):
192             if abs(et_value[i]) > 1:
193                 MAX = abs(eps*et_value[i])
194             else:
195                 MAX = eps
196             if abs(et_value[i] - value[i])> MAX:
197                 print "ERROR!!!", i, "-th  item", value[i], " is not equal to etalon item", et_value[i], "!!!"
198                 error=error+1
199     if check_error and error > 0:
200         raise RuntimeError, "There is(are) some error(s) was(were) found... For more info see ERRORs above..."
201     return error
202
203
204 def setShaded(view, shading):
205     """Utility function to set shaded mode in view"""
206     if shading == 0:
207         view.LightDiffuseColor = [1, 1, 1]
208     if shading == 1:
209         view.LightDiffuseColor = [0, 0, 0]
210
211
212 def TimeStampId(proxy):
213     """Return tuple for the given MED proxy: (mesh_name, {field_name: [entity, timestamp_id]})
214     Originally defined in KERNEL_TEST/Tools/CommonFunctions file.
215     """
216     import presentations
217     mesh_name = presentations.get_mesh_full_names(proxy).pop()
218     iterations = {}
219
220     # get list of field names
221     all_fields = proxy.GetProperty("FieldsTreeInfo")[::2]
222
223     # get timestamps
224     timestamps = proxy.TimestepValues.GetData()
225     timestamp_nb = len(timestamps)
226
227     for field in all_fields:
228         entity = presentations.get_field_entity(field)
229         field_short_name = presentations.get_field_short_name(field)
230
231         iterations[field_short_name] = [entity, timestamp_nb]
232
233     return mesh_name, iterations
234
235
236 def Import_Med_Field(filename, field_names, check_errors=0, prs=[]):
237     """Builds presentations on the given fields of the MED file.
238     Originally defined in VISU_TEST/Grids/visu/ImportMedField/begin file.
239
240     Arguments:
241       filename     : the full path to med file
242       field_names  : the list of field names (for ex: ["pression","temperature","vitesse"])
243       prs          : [[0,1,...], [], []]; empty list (sublist(s)) is ignored
244                      0-VISU.TGAUSSPOINTS
245                      1-VISU.TSCALARMAP
246                      2-VISU.TISOSURFACE
247                      3-VISU.TCUTPLANES
248                      4-VISU.TCUTLINES
249                      5-VISU.TDEFORMEDSHAPE
250                      6-VISU.TVECTORS
251                      7-VISU.TSTREAMLINES
252                      8-VISU.TPLOT3D
253                      9-VISU.TSCALARMAPONDEFORMEDSHAPE
254     """
255     import presentations
256
257     nb_errors = 0
258
259     print "File: ", filename
260
261     # check the file accessibility
262     if not os.access(filename, os.F_OK):
263         msg = "File " + filename + " does not exist!!!"
264         raise RuntimeError, msg
265
266     # import MED file
267     import pvsimple
268     pvsimple.OpenDataFile(filename)
269     proxy = presentations.pvs.GetActiveSource()
270     if proxy is None:
271         raise RuntimeError, "ERROR!!! Can't import file!!!"
272
273     for i in range(len(field_names)):
274         print "Name of the field: ", field_names[i]
275
276         if len(prs) != 0:
277             if len(prs[i]) != 0:
278                 mesh_name, iterations = TimeStampId(proxy)
279
280                 if iterations.has_key(field_names[i]):
281                     entity = iterations[field_names[i]][0]
282                     iteration = iterations[field_names[i]][1]
283                 else:
284                     msg="There is no information about TimeStampId of the " + field_names[i] + " field!!!"
285                     raise RuntimeError, msg
286
287                 err = nb_errors
288
289                 for type in prs[i]:
290                     try:
291                         if type==0:
292                             if presentations.GaussPointsOnField(proxy, entity, field_names[i], iteration) is None:
293                                 print "ERROR!!! Created GaussPoints presentation is None!!!"; nb_errors+=1
294                         if type==1:
295                             if presentations.ScalarMapOnField(proxy, entity, field_names[i], iteration) is None:
296                                 print "ERROR!!! Created ScalarMap presentation is None!!!"; nb_errors+=1
297                         if type==2:
298                             if presentations.IsoSurfacesOnField(proxy, entity, field_names[i], iteration) is None:
299                                 print "ERROR!!! Created IsoSurfaces presentation is None!!!"; nb_errors+=1
300                         if type==3:
301                             if presentations.CutPlanesOnField(proxy, entity, field_names[i], iteration) is None:
302                                 print "ERROR!!! Created CutPlanes presentation is None!!!"; nb_errors+=1
303                         if type==4:
304                             if presentations.CutLinesOnField(proxy, entity, field_names[i], iteration) is None:
305                                 print "ERROR!!! Created CutLines presentation is None!!!"; nb_errors+=1
306                         if type==5:
307                             if presentations.DeformedShapeOnField(proxy, entity, field_names[i], iteration) is None:
308                                 print "ERROR!!! Created DeformedShape presentation is None!!!"; nb_errors+=1
309                         if type==6:
310                             if presentations.VectorsOnField(proxy, entity, field_names[i], iteration) is None:
311                                 print "ERROR!!! Created Vectors presentation is None!!!"; nb_errors+=1
312                         if type==7:
313                             if presentations.StreamLinesOnField(proxy, entity, field_names[i], iteration) is None:
314                                 print "ERROR!!! Created StreamLines presentation is None!!!"; nb_errors+=1
315                         if type==8:
316                             if presentations.Plot3DOnField(proxy, entity, field_names[i], iteration) is None:
317                                 print "ERROR!!! Created Plot3D presentation is None!!!"; nb_errors+=1
318                         if type==9:
319                             if presentations.DeformedShapeAndScalarMapOnField(proxy, entity, field_names[i], iteration) is None:
320                                 print "ERROR!!! Created ScalarMapOnDeformedShape presentation is None!!!"; nb_errors+=1
321                     except ValueError:
322                         """ This exception comes from get_nb_components(...) function.
323                             The reason of exception is an implementation of MEDReader
324                             activating the first leaf when reading MED file (refer to
325                             MEDFileFieldRepresentationTree::activateTheFirst() and
326                             MEDFileFieldRepresentationTree::getTheSingleActivated(...) methods).
327                         """
328                         print "ValueError exception is catched"
329                         continue
330
331                 # check if number of errors has increased
332                 if err == nb_errors:
333                     print "Presentation(s) creation...OK"
334
335     if nb_errors > 0 and check_errors:
336         raise RuntimeError, "Errors occured!!! For more information see ERRORs above..."
337     else:
338         return nb_errors
339
340 def delete_with_inputs(obj):
341     """Deletes the given object with all its inputs"""
342     import pvsimple
343
344     obj_to_delete = obj
345     while obj_to_delete is not None:
346         tmp_obj = obj_to_delete
347         obj_to_delete = None
348         if hasattr(tmp_obj, 'Input'):
349             obj_to_delete = tmp_obj.Input
350
351         pvsimple.Delete(tmp_obj)