Salome HOME
660b76c736f8fe5747967c74b82bbbfcc4297db9
[modules/homard.git] / src / tests / Test / test_4.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2011-2022  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 """Python script for HOMARD - Test test_4"""
21 __revision__ = "V4.01"
22
23 import os
24 import sys
25 import numpy as np
26
27 import salome
28 import SHAPERSTUDY
29 import SMESH
30 import HOMARD
31 import medcoupling as mc
32 import MEDLoader as ml
33
34 from salome.shaper import model
35 from salome.smesh import smeshBuilder
36 from MEDCouplingRemapper import MEDCouplingRemapper
37
38 # ==================================
39 PATH_HOMARD = os.getenv('HOMARD_ROOT_DIR')
40 # Repertoire des scripts utilitaires
41 REP_PYTHON = os.path.join(PATH_HOMARD, "bin", "salome", "test", "HOMARD")
42 REP_PYTHON = os.path.normpath(REP_PYTHON)
43 sys.path.append(REP_PYTHON)
44 from test_util import get_dir
45 from test_util import test_results
46 # ==================================
47
48 #========================================================================
49 TEST_NAME = "test_4"
50 DEBUG = False
51 N_ITER_TEST_FILE = 3
52 DX = 600.
53 DY = 400.
54 DZ = 200.
55 # Répertoires pour ce test
56 REP_DATA, DIRCASE = get_dir(PATH_HOMARD, TEST_NAME, DEBUG)
57 #========================================================================
58
59 salome.salome_init()
60
61 #========================================================================
62 def create_cao_smesh ():
63   """CAO and mesh"""
64
65   structure_sh = create_cao ()
66
67   error, mesh_file = create_mesh (structure_sh)
68
69   return error, mesh_file
70 #========================================================================
71
72 #========================================================================
73 def create_cao ():
74   """CAO"""
75
76   model.begin()
77   partset = model.moduleDocument()
78
79   part_1 = model.addPart(partset)
80   part_1_doc = part_1.document()
81
82   structure_sh = model.addBox(part_1_doc, DX, DY, DZ,)
83   structure_sh.setName(TEST_NAME)
84   structure_sh.result().setName(TEST_NAME)
85
86   model.end()
87
88   return structure_sh
89 #========================================================================
90
91 #========================================================================
92 def create_mesh (structure_sh):
93   """Mesh"""
94   error = 0
95   mesh_file = os.path.join(DIRCASE, 'maill.00.med')
96   while not error :
97
98 # 1. Importation to the study
99 # ===========================
100     model.publishToShaperStudy()
101     l_aux = SHAPERSTUDY.shape(model.featureStringId(structure_sh))
102
103 # 2. Creation of the mesh
104 # =======================
105     smesh = smeshBuilder.New()
106     structure_m = smesh.Mesh(l_aux[0])
107
108 # Creation of the hypotheses
109     regular_1d = structure_m.Segment()
110     smesh.SetName(regular_1d.GetAlgorithm(), 'Regular_1D')
111     length = min(DX, DY, DZ) / 5.
112     local_length = regular_1d.LocalLength(length, None, 1e-07)
113     smesh.SetName(local_length, 'Local Length')
114
115     quadrangle_2d = structure_m.Quadrangle(algo=smeshBuilder.QUADRANGLE)
116     smesh.SetName(quadrangle_2d.GetAlgorithm(), 'Quadrangle_2D')
117
118     hexa_3d = structure_m.Hexahedron(algo=smeshBuilder.Hexa)
119     smesh.SetName(hexa_3d.GetAlgorithm(), 'Hexa_3D')
120
121 # Computation
122     isDone = structure_m.Compute()
123     if not isDone :
124       error = 1
125       break
126
127 # MED exportation
128     try:
129       structure_m.ExportMED(mesh_file)
130     except IOError as eee:
131       error = 2
132       raise Exception('ExportMED() failed. ' + str(eee))
133
134     break
135
136   return error, mesh_file
137 #========================================================================
138
139 #========================================================================
140 def field_exec(niter):
141   """Python script for MEDCoupling"""
142   error = 0
143
144   while not error :
145
146 # 1. The mesh
147 # ===========
148     ficmed = os.path.join(DIRCASE, 'maill.%02d.med' % niter)
149     meshMEDFileRead = ml.MEDFileMesh.New(ficmed)
150     meshRead0 = meshMEDFileRead.getMeshAtLevel(0)
151 # 2. Values of the field
152 # ======================
153     nbNodes = meshRead0.getNumberOfNodes()
154     valeur = mc.DataArrayDouble(nbNodes)
155     for iaux, taux in enumerate(meshRead0.getCoords()) :
156       #ligne   = "x = %f" % taux[0]
157       #ligne  += ", y = %f" % taux[1]
158       #ligne  += ", z = %f" % taux[2]
159       #print ligne
160       #distance = (taux[0]-DX*0.2)**2 + (taux[1]-DY*0.2)**2 + (taux[2]-DZ*0.4)**2
161       distance = min(abs(taux[0]-DX*0.4), abs(taux[1]-DY*0.2), abs(taux[2]-DZ*0.4))
162       valeur[iaux] = 1.e0 / max ( 1.e-5, np.sqrt(distance) )
163     #print ". valeur", valeur
164     nparr = valeur.toNumPyArray()
165     print(". mini/maxi {}/{}".format(nparr.min(),nparr.max()))
166
167 # 3. Creation of the field
168 # ========================
169     field = ml.MEDCouplingFieldDouble(ml.ON_NODES, ml.ONE_TIME)
170     field.setArray(valeur)
171     field.setMesh(meshRead0)
172     field.setName("DISTANCE")
173
174     fMEDFile_ch = ml.MEDFileField1TS()
175     fMEDFile_ch.setFieldNoProfileSBT(field)     # No profile desired on the field, Sort By Type
176     fMEDFile_ch.write(ficmed, 0) # 0 to indicate that we *append* (and no overwrite) to the MED file
177
178     break
179
180   return error
181
182 #========================================================================
183
184 #========================================================================
185 def homard_exec(mesh_file):
186   """Python script for HOMARD"""
187   error = 0
188
189   while not error :
190
191 # 1. Creation of the zones
192 # ========================
193 # Creation of the box zone_4_1
194     epsilon = min(DX, DY, DZ) / 100.
195     _ = HOMARD.CreateZoneBox('Zone_4_1', -epsilon, DX/3.+epsilon, DY/4.-epsilon, 3.*DY/4.+epsilon, 4.*DZ/5.-epsilon, DZ+epsilon)
196
197 # Creation of the sphere zone_4_2
198     rayon = min(DX, DY, DZ) / 4.
199     _ = HOMARD.CreateZoneSphere('Zone_4_2', DX/3., DY*0.3, DZ*0.6, rayon)
200
201 # 2. Creation of the hypotheses
202 # =============================
203     error, hyponame = homard_exec_hypo ()
204     if error :
205       break
206
207 # 3. Creation of the cases
208 # ========================
209     # Creation of the case
210     print("-------- Creation of the case {}".format(TEST_NAME))
211     case_test_4 = HOMARD.CreateCase(TEST_NAME, TEST_NAME, mesh_file)
212     case_test_4.SetDirName(DIRCASE)
213
214 # 4. Creation of the iterations
215 # =============================
216     error = homard_exec_iter(case_test_4, hyponame)
217
218     break
219
220   return error
221
222 #========================================================================
223
224 #========================================================================
225 def homard_exec_hypo():
226   """Python script for HOMARD - Creation of the hypotheses"""
227
228   error = 0
229   while not error :
230
231     dico = dict()
232     dico["1"] = "raffinement"
233     dico["-1"] = "deraffinement"
234     hyponame = list()
235
236 # 1. Creation of the hypothesis hypo_4_1
237 # ======================================
238     hyponame.append("Zone_1")
239     print("-------- Creation of the hypothesis {}".format(hyponame[0]))
240     hypo_4_1 = HOMARD.CreateHypothesis(hyponame[0])
241     hypo_4_1.AddZone('Zone_4_1', 1)
242     hypo_4_1.SetExtraOutput(2)
243     laux = hypo_4_1.GetZones()
244     nbzone = len(laux) // 2
245     jaux = 0
246     for _ in range(nbzone) :
247       print(hyponame[0], " : ", dico[laux[jaux+1]], "sur la zone", laux[jaux])
248       jaux += 2
249 # 2. Creation of the hypothesis hypo_4_2
250 # ======================================
251     hyponame.append("Zone_2")
252     print("-------- Creation of the hypothesis {}".format(hyponame[1]))
253     hypo_4_2 = HOMARD.CreateHypothesis(hyponame[1])
254     hypo_4_2.AddZone('Zone_4_2', 1)
255     hypo_4_2.SetExtraOutput(2)
256     laux = hypo_4_2.GetZones()
257     nbzone = len(laux) // 2
258     jaux = 0
259     for _ in range(nbzone) :
260       print(hyponame[1], " : ", dico[laux[jaux+1]], "sur la zone", laux[jaux])
261       jaux += 2
262 # 3. Creation of the hypothesis DISTANCE INVERSE
263 # ==============================================
264     hyponame.append("DISTANCE INVERSE")
265     print("-------- Creation of the hypothesis {}".format(hyponame[2]))
266     hypo_4_3 = HOMARD.CreateHypothesis(hyponame[2])
267     hypo_4_3.SetField('DISTANCE')
268     hypo_4_3.SetUseComp(0)
269     hypo_4_3.SetRefinThr(1, 0.3)
270     hypo_4_3.SetUnRefThr(1, 0.2)
271     hypo_4_3.AddFieldInterp('DISTANCE')
272     hypo_4_3.SetExtraOutput(2)
273     print(hyponame[2], " : zones utilisées : {}".format(hypo_4_3.GetZones()))
274     print(hyponame[2], " : champ utilisé : {}".format(hypo_4_3.GetFieldName()))
275     print(hyponame[2], " : composantes utilisées : {}".format(hypo_4_3.GetComps()))
276     if len (hypo_4_3.GetFieldName()):
277       print(".. caractéristiques de l'adaptation : {}".format(hypo_4_3.GetField()))
278     print(hyponame[2], " : champs interpolés : {}".format(hypo_4_3.GetFieldInterps()))
279
280     break
281
282   return error, hyponame
283
284 #========================================================================
285
286 #========================================================================
287 def homard_exec_iter(case_test_4, hyponame):
288   """Python script for HOMARD - Creation of the iterations"""
289
290   error = 0
291   while not error :
292
293 # 1. Creation of the iteration 1
294     iter_name = "I_" + TEST_NAME + "_1"
295     print("-------- Creation of the iteration", iter_name)
296     iter_test_4_1 = case_test_4.NextIteration(iter_name)
297     iter_test_4_1.AssociateHypo(hyponame[0])
298     print(". Hypothese :", hyponame[0])
299     iter_test_4_1.SetMeshName('M1')
300     iter_test_4_1.SetMeshFile(os.path.join(DIRCASE, 'maill.01.med'))
301     error = iter_test_4_1.Compute(1, 2)
302     if error :
303       error = 1
304       break
305
306 # 2. Creation of the iteration 2
307     iter_name = "I_" + TEST_NAME + "_2"
308     print("-------- Creation of the iteration", iter_name)
309     iter_test_4_2 = iter_test_4_1.NextIteration(iter_name)
310     iter_test_4_2.AssociateHypo(hyponame[1])
311     print(". Hypothese :", hyponame[1])
312     iter_test_4_2.SetMeshName('M2')
313     iter_test_4_2.SetMeshFile(os.path.join(DIRCASE, 'maill.02.med'))
314     error = iter_test_4_2.Compute(1, 2)
315     if error :
316       error = 2
317       break
318
319 # 3. Creation of the iteration 3
320
321     error = field_exec(2)
322     if error :
323       error = 30
324       break
325
326     iter_name = "I_" + TEST_NAME + "_3"
327     print("-------- Creation of the iteration", iter_name)
328     iter_test_4_3 = iter_test_4_2.NextIteration(iter_name)
329     iter_test_4_3.AssociateHypo(hyponame[2])
330     print(". Hypothese :", hyponame[2])
331     iter_test_4_3.SetMeshName('M3')
332     iter_test_4_3.SetFieldFile(os.path.join(DIRCASE, 'maill.02.med'))
333     iter_test_4_3.SetMeshFile(os.path.join(DIRCASE, 'maill.03.med'))
334     error = iter_test_4_3.Compute(1, 2)
335     if error :
336       error = 3
337       break
338
339     break
340
341   return error
342
343 #========================================================================
344
345 # CAO and Mesh
346
347 try :
348   ERROR, MESH_FILE = create_cao_smesh()
349   if ERROR :
350     raise Exception('Pb in create_cao_smesh')
351 except RuntimeError as eee:
352   raise Exception('Pb in create_cao_smesh: '+str(eee.message))
353
354 HOMARD = salome.lcc.FindOrLoadComponent('FactoryServer', 'HOMARD')
355 assert HOMARD is not None, "Impossible to load homard engine"
356 HOMARD.SetLanguageShort("fr")
357
358 # Exec of HOMARD-SALOME
359
360 try :
361   ERROR = homard_exec(MESH_FILE)
362   if ERROR :
363     raise Exception('Pb in homard_exec at iteration %d' %ERROR )
364 except RuntimeError as eee:
365   raise Exception('Pb in homard_exec: '+str(eee.message))
366
367 # Test of the results
368
369 N_REP_TEST_FILE = N_ITER_TEST_FILE
370 DESTROY_DIR = not DEBUG
371 test_results(REP_DATA, TEST_NAME, DIRCASE, N_ITER_TEST_FILE, N_REP_TEST_FILE, DESTROY_DIR)
372
373 if salome.sg.hasDesktop():
374   salome.sg.updateObjBrowser()