Salome HOME
updated copyright message
[modules/homard.git] / src / tests / Test / test_util.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2011-2023  CEA, EDF
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License, or (at your option) any later version.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20 """Python script for HOMARD
21
22 Utilitaires pour les tests
23 """
24 __revision__ = "V4.06"
25
26 import os
27 import tempfile
28 import MEDLoader as ml
29 import shutil
30 #========================================================================
31 #========================================================================
32 def get_dir(path_homard, test_name, debug=False) :
33   """
34 Get directories for the test.
35 Copyright EDF 2018
36   """
37 #
38 # Répertoire des données du test
39   rep_data = os.path.join(path_homard, "share", "salome", "homardsamples")
40   rep_data = os.path.normpath(rep_data)
41 #
42 # Répertoire des résultats
43   if debug :
44     dircase = os.path.join("/tmp", test_name)
45     if ( os.path.isdir(dircase) ) :
46       remove_dir(dircase)
47     os.mkdir(dircase)
48   else :
49     dircase = tempfile.mkdtemp(prefix=test_name+"_")
50 #
51   return rep_data, dircase
52 #
53 #========================================================================
54 #========================================================================
55 def remove_dir(directory) :
56   """
57 Empties, then removes a directory.
58 Copyright EDF-R&D 2013
59   """
60 #
61   l_aux = os.listdir(directory)
62   for fic in l_aux :
63     fic_a = os.path.join(directory, fic)
64     if os.path.isdir(fic_a) :
65       remove_dir(fic_a)
66     else :
67       os.remove(fic_a)
68   os.rmdir(directory)
69 #
70   return
71 #
72 #========================================================================
73 #========================================================================
74 def test_results(rep_test, test_name, dircase, n_iter_test_file, n_rep_test_file, destroy_dir = True) :
75   """
76 Test of the result
77 rep_test: repertoire des tests
78 test_name: nom du test
79 dircase: repertoire des resultats du test
80 n_iter_test_file: numero de l'iteration a tester
81 n_rep_test_file: numero du repertoire de l'iteration a tester
82 destroy_dir: destruction du repertoire de calcul
83 Copyright EDF-R&D 2014
84   """
85   #
86   test_file_suff = "apad.%02d.bilan" % n_iter_test_file
87   rep_test_file = "I%02d" % n_rep_test_file
88 #
89 # Existence du fichier de référence
90   #
91   test_file = os.path.join(rep_test, test_name + "." + test_file_suff)
92   mess_error_ref = "\nReference file: " + test_file
93   #print ("test_file = %s" % test_file)
94   try :
95     with open (test_file, "r") as fichier :
96       les_lignes_ref = fichier.readlines()
97   except :
98     mess_error = mess_error_ref + "\nThis file does not exist.\n"
99     destroy_dir = False
100     raise Exception(mess_error)
101 #
102 # Existence du fichier de l'exécution courante
103 #
104   test_file = os.path.join(dircase, rep_test_file, test_file_suff)
105   if os.path.isfile (test_file) :
106     with open (test_file, "r") as fichier :
107       les_lignes = fichier.readlines()
108   else :
109     mess_error  = "\nResult file: " + test_file
110     mess_error += "\nThis file does not exist.\n"
111     destroy_dir = False
112     raise Exception(mess_error)
113 #
114 # Nombre de lignes identiques
115 #
116   nblign = len(les_lignes_ref)
117   if ( len(les_lignes) != nblign ):
118     mess_error = mess_error_ref +  "\nResult file: " + test_file
119     mess_error += "\nThe number of lines of the files are not the same.\n"
120     destroy_dir = False
121     raise Exception(mess_error)
122 #
123 # Comparaison des lignes, à l'esception de la date
124 #
125   for num in range(nblign) :
126     if ( "creation" not in les_lignes_ref[num] ) :
127       if ( les_lignes_ref[num] != les_lignes[num] ) :
128         message_erreur = "\nRefe : " + les_lignes_ref[num]
129         message_erreur += "Test : " + les_lignes[num][:-1]
130         message_erreur += "\nThe test is different from the reference."
131         destroy_dir = False
132         raise Exception(message_erreur)
133 #
134 # Destruction éventuelle du répertoire du calcul
135 #
136   if destroy_dir:
137     remove_dir(dircase)
138 #
139   return
140 #
141 #========================================================================
142 #========================================================================
143 #
144 def saveGeometry( xao_file, name, author="" ):
145   """
146   Save the geometry in a XAO file
147   """
148   import salome
149   from salome.geom import geomBuilder
150   geompy = geomBuilder.New()
151   error = 0
152
153   # find an object having groups in GEOM component
154   component = salome.myStudy.FindObjectByPath("/Geometry")
155   it = salome.myStudy.NewChildIterator( component )
156   geomObj = None
157   l_groups = list()
158   while it.More():
159     so = it.Value()
160     it.Next()
161     go = so.GetObject()
162     #
163     if go:
164       if ( go.GetName() == name ) :
165         subIt = salome.myStudy.NewChildIterator( so )
166         while subIt.More():
167           subSO = subIt.Value()
168           subIt.Next()
169           if not subSO.GetName(): continue # a reference
170           gr = subSO.GetObject()
171           if gr and geompy.ShapeIdToType( gr.GetType() ) == "GROUP":
172             l_groups.append( gr )
173         geomObj = go
174         break
175
176   if not geomObj:
177     raise RuntimeError("Cant find a geometry object in the SALOME study with name = '%s'" % name)
178
179   # save the geom object in a XAO file
180   l_fields = list()
181   ok = geompy.ExportXAO( geomObj, l_groups, l_fields, author, xao_file, "" )
182   error = not ok
183
184   return error
185 #
186 #========================================================================
187 #========================================================================
188 #
189 def repositionnement (rep_calc, fic_med_brut, fic_med_new, xao_file, menage=True, verbose=False) :
190 #
191   """
192 Pilote le repositionnement des noeuds qui ont bougé
193 Entrées :
194   rep_calc : répertoire du calcul HOMARD qui est à traiter
195   fic_med_brut : fichier MED du calcul avec les coordonnées avant projection
196   fic_med_new  : fichier MED du calcul avec les coordonnées après projection
197   xao_file : fichier XAO de la géométrie
198   menage : Suppression du fichier fic_med_brut
199   """
200   if verbose :
201     ligne =    "rep_calc     = %s" % rep_calc
202     ligne += "\nfic_med_brut = %s" % fic_med_brut
203     ligne += "\nfic_med_new  = %s" % fic_med_new
204     ligne += "\nxao_file     = %s" % xao_file
205     ligne += "\nmenage       = %d" % menage
206     print(ligne)
207
208   message = ""
209   erreur = 0
210   while not erreur :
211 #
212 # 1. l_fr = liste des fichiers des lignes/surfaces a suivre
213 #
214     fic_hom_med = None
215     laux = os.listdir(rep_calc)
216     #print laux
217     l_fr = list()
218     icpt_1D = 0
219     icpt_2D = 0
220     for fic in laux :
221       #print "\t" + fic
222       if ( fic[:2] == 'fr' ) :
223         l_fr.append(os.path.join(rep_calc, fic))
224       elif ( fic[-4:] == '.med' ) :
225         fic_hom_med = os.path.join(rep_calc, fic)
226         #print "\t\treperage de fic_hom_med =", fic_hom_med
227 #
228 # 2. Lancement du post-traitement si des noeuds sont concernés
229 #
230     if l_fr :
231 #
232       if verbose :
233         print("l_fr =", l_fr)
234         print("fic_hom_med =", fic_hom_med)
235 #
236 # 2.1.  La fonction :
237 #    . prend le maillage brut dans le fichier fic_med_brut
238 #    . prend la liste des noeuds à bouger pour chaque groupe concerné
239 #    . prend la géométrie dans le fichier xao_file
240 #    . retourne le maillage transformé dans le fichier fic_med_new
241 #
242       from FrontTrack import FrontTrack
243       ft = FrontTrack()
244       ft.track( fic_med_brut, fic_med_new, l_fr, xao_file )
245 #
246 # 2.2. Transfert des coordonnées dans le fichier HOMARD MED
247 #
248       #if not fic_hom_med :
249         #message = "Impossible de trouver le fichier HOMARD MED dans %s" % rep_calc
250         #erreur = 12
251         #break
252 ##
253       #fic_coords = os.path.join(rep_calc, "coords")
254       #erreur, message = change_coords (fic_med_new, fic_coords, verbose)
255       ##erreur, message = change_coords_0 (fic_med_new, fic_hom_med, verbose)
256       #if erreur :
257         #break
258 #
259 # 2.3. Ménage éventuel de l'ancien fichier MED
260 #
261       if menage :
262 #
263         if ( fic_med_brut != fic_med_new ) :
264           if verbose :
265             print("Suppression du fichier %s" % fic_med_brut)
266           os.remove(fic_med_brut)
267 #
268 # 3. Renommage du fichier si aucun noeud n'est concerné
269 #
270     else :
271 #
272       if ( fic_med_brut != fic_med_new ) :
273         os.rename(fic_med_brut, fic_med_new)
274 #
275 # 4. Mise à jour des coordonnées dans le fichier historique HOMARD/MED si des noeuds sont concernés
276 #
277     if l_fr :
278 #
279       erreur, message = maj_coords (rep_calc, fic_med_new, verbose)
280 #
281     break
282 #
283   return erreur, message
284 #
285 #========================================================================
286 #========================================================================
287 #
288 def maj_coords (rep_calc, fic_med_calc, verbose=False) :
289 #
290   """
291 Met à jour les coordonnées du fichier de calcul vers le fichier HOMARD
292 Entrées :
293   rep_calc : répertoire du calcul HOMARD qui est à traiter
294   fic_med_calc  : fichier MED du calcul avec les coordonnées après projection
295   xao_file : fichier XAO de la géométrie
296   """
297   if verbose :
298     ligne =    "rep_calc     = %s" % rep_calc
299     ligne += "\nfic_med_calc = %s" % fic_med_calc
300     print(ligne)
301
302   message = ""
303   erreur = 0
304   while not erreur :
305 #
306 # 1. Recherche des inforamtions permanentes dans le fichier de configuration
307 #
308     fic_conf = os.path.join(rep_calc, "HOMARD.Configuration")
309     with open (fic_conf, "r") as fichier :
310       les_lignes = fichier.readlines()
311 #
312     ligne0 = ""
313     icpt = 0
314     for ligne in les_lignes :
315       #print "\t" + ligne
316       for saux in ( "HOMai", "CCNoM" ) :
317         if ( saux+"NP1" in ligne ) :
318           iaux = ligne.index(saux)
319           ligne0 += saux + "N__" + ligne[iaux+8:]
320           icpt += 1
321       if ( "NumeIter" in ligne ) :
322         iaux = ligne.index("NumeIter")
323         saux = ligne[iaux+8:-1]
324         iaux = int(saux) + 1
325         s_iter = "%02d" % iaux
326         ligne0 += "NumeIter %s\n" % s_iter
327         icpt += 1
328 #
329     if ( icpt != 3 ) :
330       message = "Erreur dans le décodage de %s\n" % fic_conf
331       message+= ligne0
332       erreur = 1
333       break
334 #
335 # 2. Création du fichier de configuration
336 #
337     fic_conf_sv = os.path.join(rep_calc, "HOMARD.Configuration.majc")
338 #
339     with open (fic_conf_sv, "w") as fichier :
340 #
341       ligne = ligne0
342       ligne += "ModeHOMA 5\n"
343       fic = os.path.join(rep_calc, "Liste.%s.maj_coords.log" % s_iter)
344       ligne += "ListeStd %s\n" % fic
345       ligne += "CCMaiN__ %s\n" % fic_med_calc
346       ligne += "RepeTrav %s\n" % rep_calc
347       ligne += "RepeInfo %s\n" % rep_calc
348       ligne += "Action   homa\n"
349       ligne += "CCAssoci med\n"
350       ligne += "EcriFiHO N_SANS_FRONTIERE\n"
351       ligne += "MessInfo 10\n"
352 #
353       fichier.write(ligne)
354 #
355 # 3. Mise à jour
356 # 3.1. Détermination de l'exécutable
357 #
358     if "HOMARD_REP_EXE_PRIVATE" in os.environ :
359       HOMARD_REP_EXE  = os.environ["HOMARD_REP_EXE_PRIVATE"]
360     else :
361       HOMARD_REP_EXE  = os.environ["HOMARD_REP_EXE"]
362 #
363     if "HOMARD_EXE_PRIVATE" in os.environ :
364       HOMARD_EXE  = os.environ["HOMARD_EXE_PRIVATE"]
365     else :
366       HOMARD_EXE  = os.environ["HOMARD_EXE"]
367 #
368     homard_exe = os.path.join(HOMARD_REP_EXE, HOMARD_EXE)
369     if verbose :
370       ligne = "homard_exe = %s" % homard_exe
371       print(ligne)
372 #
373     if not os.path.isfile(homard_exe) :
374       message = "homard_exe = %s" % homard_exe
375       message += "\nCe fichier executable n'existe pas."
376       erreur = 31
377       break
378 #
379 # 3.2. Lancement
380 #
381     fic_conf = os.path.join(rep_calc, "HOMARD.Configuration")
382     shutil.copyfile(fic_conf_sv, fic_conf)
383 #
384     os.chdir(rep_calc)
385     erreur = os.system (homard_exe)
386 #
387     break
388 #
389   return erreur, message
390 #
391 #========================================================================
392 #========================================================================
393 #