1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2011-2023 CEA, EDF
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.
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.
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
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 """Python script for HOMARD - Test test_4"""
21 __revision__ = "V4.01"
31 import medcoupling as mc
32 import MEDLoader as ml
34 from salome.shaper import model
35 from salome.smesh import smeshBuilder
36 from MEDCouplingRemapper import MEDCouplingRemapper
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 # ==================================
48 #========================================================================
55 # Répertoires pour ce test
56 REP_DATA, DIRCASE = get_dir(PATH_HOMARD, TEST_NAME, DEBUG)
57 #========================================================================
59 salome.salome_init_without_session()
61 #========================================================================
62 def create_cao_smesh ():
65 structure_sh = create_cao ()
67 error, mesh_file = create_mesh (structure_sh)
69 return error, mesh_file
70 #========================================================================
72 #========================================================================
77 partset = model.moduleDocument()
79 part_1 = model.addPart(partset)
80 part_1_doc = part_1.document()
82 structure_sh = model.addBox(part_1_doc, DX, DY, DZ,)
83 structure_sh.setName(TEST_NAME)
84 structure_sh.result().setName(TEST_NAME)
89 #========================================================================
91 #========================================================================
92 def create_mesh (structure_sh):
95 mesh_file = os.path.join(DIRCASE, 'maill.00.med')
98 # 1. Importation to the study
99 # ===========================
100 model.publishToShaperStudy()
101 l_aux = SHAPERSTUDY.shape(model.featureStringId(structure_sh))
103 # 2. Creation of the mesh
104 # =======================
105 smesh = smeshBuilder.New()
106 structure_m = smesh.Mesh(l_aux[0])
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')
115 quadrangle_2d = structure_m.Quadrangle(algo=smeshBuilder.QUADRANGLE)
116 smesh.SetName(quadrangle_2d.GetAlgorithm(), 'Quadrangle_2D')
118 hexa_3d = structure_m.Hexahedron(algo=smeshBuilder.Hexa)
119 smesh.SetName(hexa_3d.GetAlgorithm(), 'Hexa_3D')
122 isDone = structure_m.Compute()
129 structure_m.ExportMED(mesh_file)
130 except IOError as eee:
132 raise Exception('ExportMED() failed. ' + str(eee))
136 return error, mesh_file
137 #========================================================================
139 #========================================================================
140 def field_exec(niter):
141 """Python script for MEDCoupling"""
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]
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()))
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")
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
182 #========================================================================
184 #========================================================================
185 def homard_exec(mesh_file):
186 """Python script for HOMARD"""
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)
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)
201 # 2. Creation of the hypotheses
202 # =============================
203 error, hyponame = homard_exec_hypo ()
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)
214 # 4. Creation of the iterations
215 # =============================
216 error = homard_exec_iter(case_test_4, hyponame)
222 #========================================================================
224 #========================================================================
225 def homard_exec_hypo():
226 """Python script for HOMARD - Creation of the hypotheses"""
232 dico["1"] = "raffinement"
233 dico["-1"] = "deraffinement"
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
246 for _ in range(nbzone) :
247 print(hyponame[0], " : ", dico[laux[jaux+1]], "sur la zone", laux[jaux])
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
259 for _ in range(nbzone) :
260 print(hyponame[1], " : ", dico[laux[jaux+1]], "sur la zone", laux[jaux])
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()))
282 return error, hyponame
284 #========================================================================
286 #========================================================================
287 def homard_exec_iter(case_test_4, hyponame):
288 """Python script for HOMARD - Creation of the iterations"""
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)
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)
319 # 3. Creation of the iteration 3
321 error = field_exec(2)
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)
343 #========================================================================
348 ERROR, MESH_FILE = create_cao_smesh()
350 raise Exception('Pb in create_cao_smesh')
351 except RuntimeError as eee:
352 raise Exception('Pb in create_cao_smesh: '+str(eee.message))
354 HOMARD = salome.lcc.FindOrLoadComponent('FactoryServer', 'HOMARD')
355 assert HOMARD is not None, "Impossible to load homard engine"
356 HOMARD.SetLanguageShort("fr")
358 # Exec of HOMARD-SALOME
361 ERROR = homard_exec(MESH_FILE)
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))
367 # Test of the results
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)
373 if salome.sg.hasDesktop():
374 salome.sg.updateObjBrowser()