Salome HOME
Mise à jour SHAPER et medcoupling
[modules/homard.git] / src / tests / Test / test_5.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2011-2020  CEA/DEN, EDF R&D
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 """
21 Python script for HOMARD
22 Specific conditions for Code_Saturne
23 Test test_5
24 """
25 __revision__ = "V2.05"
26
27 import os
28 import sys
29 import numpy as np
30
31 import salome
32 import HOMARD
33 import medcoupling as mc
34 import MEDLoader as ml
35
36 # ==================================
37 PATH_HOMARD = os.getenv('HOMARD_ROOT_DIR')
38 # Repertoire des scripts utilitaires
39 REP_PYTHON = os.path.join(PATH_HOMARD, "bin", "salome", "test", "HOMARD")
40 REP_PYTHON = os.path.normpath(REP_PYTHON)
41 sys.path.append(REP_PYTHON)
42 from test_util import get_dir
43 from test_util import test_results
44 # ==================================
45
46 #========================================================================
47 TEST_NAME = "test_5"
48 DEBUG = False
49 VERBOSE = False
50 N_ITER_TEST_FILE = 3
51 NBCELL_X = 10
52 NBCELL_Y = 10
53 NBCELL_Z = 10
54 LG_X = 360.
55 LG_Y = 240.
56 LG_Z = 160.
57 MESH_NAME = "MESH"
58 # Répertoires pour ce test
59 REP_DATA, DIRCASE = get_dir(PATH_HOMARD, TEST_NAME, DEBUG)
60 #========================================================================
61
62 salome.salome_init()
63
64 #========================================================================
65 def mesh_exec():
66   """Python script for MED"""
67   error = 0
68
69   while not error :
70
71 # Creation of the mesh
72 # ====================
73     maillage_3d = ml.MEDCouplingUMesh(MESH_NAME, 2)
74     maillage_3d.setMeshDimension(3)
75
76 # Creation of the nodes
77 # ====================
78
79     nbno_x = NBCELL_X + 1
80     nbno_y = NBCELL_Y + 1
81     nbno_z = NBCELL_Z + 1
82
83     delta_x = LG_X / float(NBCELL_X)
84     delta_y = LG_Y / float(NBCELL_Y)
85     delta_z = LG_Z / float(NBCELL_Z)
86
87     coordinates = list()
88     coo_z = -0.5*LG_Z
89     for _ in range(nbno_z) :
90       coo_y = -0.5*LG_Y
91       for _ in range(nbno_y) :
92         coo_x = -0.5*LG_X
93         for _ in range(nbno_x) :
94           coordinates.append(coo_x)
95           coordinates.append(coo_y)
96           coordinates.append(coo_z)
97           coo_x += delta_x
98         coo_y += delta_y
99       coo_z += delta_z
100
101     nbno = nbno_x*nbno_y*nbno_z
102     les_coords = ml.DataArrayDouble(coordinates, nbno, 3)
103     maillage_3d.setCoords(les_coords)
104
105 # Creation of the cells
106 # =====================
107
108     nbr_cell_3d = NBCELL_X*NBCELL_Y*NBCELL_Z
109     maillage_3d.allocateCells(nbr_cell_3d)
110
111     decala_z = nbno_x*nbno_y
112 #   kaux = numero de la tranche en z
113     for kaux in range(1, nbno_z) :
114
115       #print ". Tranche en z numero %d" % kaux
116       decala = decala_z*(kaux-1)
117 #     jaux = numero de la tranche en y
118       for jaux in range(1, nbno_y) :
119
120         #print ". Tranche en y numero %d" % jaux
121 #       iaux = numero de la tranche en x
122         for iaux in range(1, nbno_x) :
123
124           #print ". Tranche en x numero %d" % iaux
125           nref = decala+iaux-1
126           laux = [nref, nref+nbno_x, nref+1+nbno_x, nref+1, nref+decala_z, nref+nbno_x+decala_z, nref+1+nbno_x+decala_z, nref+1+decala_z]
127           if VERBOSE:
128             if ( ( iaux==1 and jaux==1 and kaux==1 ) or ( iaux==(nbno_x-1) and jaux==(nbno_y-1) and kaux==(nbno_z-1) ) ) :
129               print (". Maille {} : {}".format((iaux*jaux*kaux),laux))
130           maillage_3d.insertNextCell(ml.NORM_HEXA8, 8, laux)
131
132         decala += nbno_x
133
134     maillage_3d.finishInsertingCells()
135
136 # Agregation into a structure of MEDLoader
137 # ========================================
138
139     meshMEDFile3D = ml.MEDFileUMesh()
140     meshMEDFile3D.setName(MESH_NAME)
141
142     meshMEDFile3D.setMeshAtLevel(0, maillage_3d)
143
144     meshMEDFile3D.rearrangeFamilies()
145
146 # MED exportation
147 # ===============
148     try:
149       ficmed = os.path.join(DIRCASE, 'maill.00.med')
150       #print "Ecriture du maillage dans le fichier", ficmed
151       meshMEDFile3D.write(ficmed, 2)
152     except IOError as eee:
153       error = 2
154       raise Exception('MEDFileUMesh.write() failed. ' + str(eee))
155
156     break
157
158   return error
159
160 #========================================================================
161
162 #========================================================================
163 def field_exec(niter):
164   """
165 Python script for MEDCoupling
166   """
167   error = 0
168
169   while not error :
170
171 # The mesh
172 # ========
173     ficmed = os.path.join(DIRCASE, 'maill.%02d.med' % niter)
174     meshMEDFileRead = ml.MEDFileMesh.New(ficmed)
175     mesh_read0 = meshMEDFileRead.getMeshAtLevel(0)
176 # Barycenter of the cells
177 # =======================
178     cg_hexa_ml = mesh_read0.computeIsoBarycenterOfNodesPerCell()
179     cg_hexa = cg_hexa_ml.toNumPyArray()
180 # Target
181 # ======
182     xyz_p = np.zeros(3, dtype=np.float)
183     xyz_p[0] = -0.20*float(1-niter) * LG_X
184     xyz_p[1] = -0.15*float(1-niter) * LG_Y
185     xyz_p[2] = -0.10*float(1-niter) * LG_Z
186 # Values of the field
187 # ===================
188     nbr_cell_3d = mesh_read0.getNumberOfCells()
189     valeur = mc.DataArrayDouble(nbr_cell_3d)
190     for num_mail in range(nbr_cell_3d) :
191       #ligne   = "x = %f" % cg_hexa[num_mail][0]
192       #ligne  += ", y = %f" % cg_hexa[num_mail][1]
193       #ligne  += ", z = %f" % cg_hexa[num_mail][2]
194       #print ligne
195       distance = np.linalg.norm(cg_hexa[num_mail]-xyz_p)
196       valeur[num_mail] = 1.e0 / max ( 1.e-5, distance)
197     #print ". valeur", valeur
198     nparr = valeur.toNumPyArray()
199     print(". mini/maxi {}/{}".format(nparr.min(),nparr.max()))
200
201 # Creation of the field
202 # =====================
203     field = ml.MEDCouplingFieldDouble(ml.ON_CELLS, ml.ONE_TIME)
204     field.setArray(valeur)
205     field.setMesh(mesh_read0)
206     field.setName("DISTANCE")
207
208     fMEDFile_ch = ml.MEDFileField1TS()
209     fMEDFile_ch.setFieldNoProfileSBT(field)     # No profile desired on the field, Sort By Type
210     fMEDFile_ch.write(ficmed, 0) # 0 to indicate that we *append* (and no overwrite) to the MED file
211
212     break
213
214   return error, ficmed
215
216 #========================================================================
217
218 #========================================================================
219 def homard_exec():
220   """Python script for HOMARD"""
221   error = 0
222
223   while not error :
224
225 # Creation of the hypothese DISTANCE INVERSE
226 # ==========================================
227     hyponame = "DISTANCE INVERSE"
228     print("-------- Creation of the hypothesis", hyponame)
229     hypo_5 = HOMARD.CreateHypothesis(hyponame)
230     hypo_5.SetField('DISTANCE')
231     hypo_5.SetUseComp(0)
232     hypo_5.SetRefinThr(1, 0.020)
233     hypo_5.SetUnRefThr(1, 0.015)
234     print(hyponame, " : champ utilisé :", hypo_5.GetFieldName())
235     print(".. caractéristiques de l'adaptation :", hypo_5.GetField())
236
237 # Creation of the cases
238 # =====================
239     print("-------- Creation of the case", TEST_NAME)
240     mesh_file = os.path.join(DIRCASE, 'maill.00.med')
241     case_test_5 = HOMARD.CreateCase(TEST_NAME, 'MESH', mesh_file)
242     case_test_5.SetDirName(DIRCASE)
243     case_test_5.SetConfType(1)
244     case_test_5.SetExtType(1)
245
246 # Creation of the iterations
247 # ==========================
248
249     for niter in range(N_ITER_TEST_FILE) :
250
251       s_niterp1 = "%02d" % (niter + 1)
252
253     # Creation of the indicator
254     #
255       error, ficmed_indic = field_exec(niter)
256       if error :
257         error = 10
258         break
259
260     # Creation of the iteration
261
262       iter_name = "I_" + TEST_NAME + "_" + s_niterp1
263       print("-------- Creation of the iteration", iter_name)
264       if ( niter == 0 ) :
265         iter_test_5 = case_test_5.NextIteration(iter_name)
266       else :
267         iter_test_5 = iter_test_5.NextIteration(iter_name)
268       iter_test_5.AssociateHypo(hyponame)
269       iter_test_5.SetFieldFile(ficmed_indic)
270       iter_test_5.SetMeshName(MESH_NAME+"_" + s_niterp1)
271       iter_test_5.SetMeshFile(os.path.join(DIRCASE, "maill."+s_niterp1+".med"))
272       error = iter_test_5.Compute(1, 2)
273       if error :
274         error = 20
275         break
276
277     break
278
279   return error
280
281 #========================================================================
282
283 # Geometry and Mesh
284
285 try :
286   ERROR = mesh_exec()
287   if ERROR :
288     raise Exception('Pb in mesh_exec')
289 except RuntimeError as eee:
290   raise Exception('Pb in mesh_exec: '+str(eee.message))
291
292 HOMARD = salome.lcc.FindOrLoadComponent('FactoryServer', 'HOMARD')
293 assert HOMARD is not None, "Impossible to load homard engine"
294 HOMARD.SetLanguageShort("fr")
295
296 # Exec of HOMARD-SALOME
297
298 try :
299   ERROR = homard_exec()
300   if ERROR :
301     raise Exception('Pb in homard_exec at iteration %d' %ERROR )
302 except RuntimeError as eee:
303   raise Exception('Pb in homard_exec: '+str(eee.message))
304
305 # Test of the results
306
307 N_REP_TEST_FILE = N_ITER_TEST_FILE
308 DESTROY_DIR = not DEBUG
309 test_results(REP_DATA, TEST_NAME, DIRCASE, N_ITER_TEST_FILE, N_REP_TEST_FILE, DESTROY_DIR)
310
311 if salome.sg.hasDesktop():
312   salome.sg.updateObjBrowser()