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