1 # -*- coding: utf-8 -*-
3 Example of use case of interpolZ with the default values:
5 # --- case name in HYDRO
8 # --- med file 2D(x,y) of the case produced by SMESH
9 fichierMaillage = '/home/B27118/projets/LNHE/garonne/inondation1.med'
11 # --- dictionary [med group name] = region name
12 dicoGroupeRegion= dict(litMineur = 'inondation1_litMineur',
13 litMajeurDroite = 'inondation1_riveDroite',
14 litMajeurGauche = 'inondation1_riveGauche',
16 # --- Z interpolation on the bathymety/altimetry on the mesh nodes
17 interpolZ(nomCas, fichierMaillage, dicoGroupeRegion)
19 __revision__ = "V3.01"
20 # -----------------------------------------------------------------------------
22 # -----------------------------------------------------------------------------
27 theStudy = salome.myStudy
28 theStudyId = salome.myStudyId
31 import MEDLoader as ml
32 import MEDCoupling as mc
34 # -----------------------------------------------------------------------------
36 from med import medfile
37 from med import medmesh
38 from med import medfield
39 from med import medenum
41 # -----------------------------------------------------------------------------
45 class MyInterpolator( HYDROPy.HYDROData_IInterpolator ):
53 def GetAltitudeForPoint( self, theCoordX, theCoordY ):
57 alt_obj = HYDROPy.HYDROData_IInterpolator.GetAltitudeObject( self )
58 z = alt_obj.GetAltitudeForPoint( theCoordX, theCoordY ) # Custom calculation takes the base value and changes it to test
63 # -----------------------------------------------------------------------------
66 def interpolZ(nomCas, fichierMaillage, dicoGroupeRegion, zUndef=90., regions_interp_method=None, m3d=True, xyzFile=False, verbose=False):
68 interpolZ takes a 2D (x,y) mesh and calls the active instance of module HYDRO
69 to interpolate the bathymetry/altimetry on the mesh nodes, to produce the Z value of each node.
72 nomCas: Calculation Case Name in module HYDRO
73 fichierMaillage: med file name produced by SMESH, corresponding to the HYDRO case
74 dicoGroupeRegion: python dictionary giving the correspondance of mesh groups to HYDRO regions.
76 Value: region name in the HYDRO Case
77 zUndef: Z value to use for nodes outside the regions (there must be none if the case is correct).
79 interpolMethod: integer value or dict
81 0 = nearest point on bathymetry
82 1 = linear interpolation
83 if dict : key is a region name, value is a type of interpolation (0 or 1)
84 if None : default type used (0)
85 m3d: True/False to produce a 3D mesh. Default is False.
86 xyzFile: True/False to write an ascii file with xyz for every node. Default is False.
88 statz: statistique for z
90 Value: (minz, maxz, meanz, stdz, v05z, v95z)
92 return <fichierMaillage>F.med : med file with Z value in a field "BOTTOM"
93 Option: Z value also in Z coordinate if m3D is true
94 return <fichierMaillage>.xyz : text file with X, Y, Z values
103 ligne = "nomCas: %s" % nomCas
104 ligne += "\ninterpolMethods: " % regions_interp_method
105 if (zUndef != None ):
106 ligne += "\nzUndef: %f" % zUndef
107 ligne += "\nm3d: %d" % m3d
110 doc = HYDROPy.HYDROData_Document.Document(theStudyId)
111 cas = doc.FindObjectByName(nomCas)
112 print ( "cas : ", cas)
113 custom_inter = MyInterpolator()
115 basename = fichierMaillage[:-4]
116 fichierFMaillage = basename + 'F.med'
118 print ("dicoGroupeRegion = ", dicoGroupeRegion)
119 ligne = "fichierMaillage = %s" % fichierMaillage
120 ligne += "\nfichierFMaillage = %s" % fichierFMaillage
122 fichierFonds = basename + '.xyz'
123 ligne += "\nfichierFonds = %s" % fichierFonds
128 meshMEDFileRead = ml.MEDFileMesh.New(fichierMaillage)
130 print (meshMEDFileRead)
132 # 2. Checks the names of the groups of faces
134 t_group_n = meshMEDFileRead.getGroupsNames()
135 dicoGroupeRegion_0 = dict()
137 for gr_face_name in dicoGroupeRegion:
138 saux = gr_face_name.strip()
139 if saux not in t_group_n:
140 message += "Group: '" + gr_face_name + "'\n"
143 dicoGroupeRegion_0[saux] = dicoGroupeRegion[gr_face_name]
145 ligne = "Number of problems: %d" % nb_pb
150 message += "This group does"
152 message += "These %d groups do" % nb_pb
153 message += " not belong to the mesh.\n"
154 message += "Please check the names of the group(s) of faces corresponding to each region of the HYDRO case.\n"
155 message += "Groups for this file:\n"
156 for group_n in t_group_n :
157 message += "'%s'\n" % group_n
161 # 3. Gets the information about the nodes
163 nbnodes = meshMEDFileRead.getNumberOfNodes()
165 ligne = "Number of nodes: %d" % nbnodes
168 coords = meshMEDFileRead.getCoords()
171 nb_comp = coords.getNumberOfComponents()
172 l_info = coords.getInfoOnComponents()
174 l_info_0=["X", "Y", "Z"]
175 for id_node in (0, 1, nbnodes-1):
176 ligne += "\nNode #%6d:" % id_node
177 for iaux in range(nb_comp):
181 saux = l_info_0[iaux]
182 ligne += " %s" % saux
183 ligne += "=%f" % coords[id_node, iaux]
186 # 4. Exploration of every group of faces
188 tb_aux = np.zeros(nbnodes, dtype=np.bool)
190 bathy = np.zeros(nbnodes, dtype=np.float)
193 for gr_face_name in dicoGroupeRegion_0:
195 # 4.1. Region connected to the group
197 nomreg = dicoGroupeRegion_0[gr_face_name]
198 ligne = "------- Region: '%s'" % nomreg
199 ligne += ", connected to group '%s'" % gr_face_name
201 region = doc.FindObjectByName(nomreg)
203 # 4.2. Mesh of the group
205 mesh_of_the_group = meshMEDFileRead.getGroup(0, gr_face_name, False)
206 nbr_cells = mesh_of_the_group.getNumberOfCells()
208 ligne = "\t. Number of cells: %d" % nbr_cells
211 # 4.3. Nodes of the meshes of the group
212 # Every node is flagged in tb_aux
215 for id_elem in range(nbr_cells):
216 l_nodes = mesh_of_the_group.getNodeIdsOfCell(id_elem)
218 for id_node in l_nodes:
219 tb_aux[id_node] = True
220 np_aux = tb_aux.nonzero()
223 ligne = "\t. Number of nodes for this group: %d" % len(np_aux[0])
225 #print ("np_aux:", np_aux)
227 # 4.4. Interpolation over the nodes of the meshes of the group
231 for nodeId in np_aux[0]:
232 vx.append(coords[nodeId, 0])
233 vy.append(coords[nodeId, 1])
238 if regions_interp_method is not None:
239 if isinstance(regions_interp_method, dict) and nomreg in regions_interp_method.keys():
240 interpolMethod = int(regions_interp_method[nomreg])
241 elif isinstance(regions_interp_method, int):
242 interpolMethod = regions_interp_method
244 #print ('interp', interpolMethod )
245 vz = cas.GetAltitudesForPoints(vx, vy, region, interpolMethod)
252 v05z = np.percentile(vz, 05)
253 v95z = np.percentile(vz, 95)
256 ligne = ".. Minimum: %f" % minz
257 ligne += ", maximum: %f" % maxz
258 ligne += ", mean: %f\n" % meanz
259 ligne += ".. stdeviation: %f" % stdz
260 ligne += ", v05z: %f" % v05z
261 ligne += ", v95z: %f" % v95z
264 # 4.5. Storage of the z and of the statistics for this region
266 statz[gr_face_name] = (minz, maxz, meanz, stdz, v05z, v95z)
268 for iaux, nodeId in enumerate(np_aux[0]):
269 bathy[nodeId] = vz[iaux]
272 # During the interpolation, if no value is available over a node, a default value
273 # is set: -9999. It has no importance for the final computation, but if the field
274 # or the mesh is displayed, it makes huge gap. To prevent this artefact, a more
275 # convenient "undefined" value is set. This new undefined value is given by the user.
277 # zUndefThreshold: the default value is -9000. It is tied with the value -9999. given
278 # by the interpolation when no value is defined.
280 zUndefThreshold = -9000.
282 ligne = "zUndefThreshold: %f" % zUndefThreshold
285 #print "bathy :\n", bathy
286 np_aux_z = (bathy < zUndefThreshold).nonzero()
288 ligne = ".. Number of nodes below the minimum: %d" % len(np_aux_z[0])
291 for iaux in np_aux_z[0]:
294 # 6. Option : xyz file
299 ligne = ".. Ecriture du champ de bathymétrie sur le fichier :\n%s" % fichierFonds
302 with open(fichierFonds, "w") as fo :
303 for nodeId in range(nbnodes):
304 ligne = "%11.3f %11.3f %11.3f\n" % (coords[nodeId, 0], coords[nodeId, 1], bathy[nodeId])
308 # 7.1. Transformation of the bathymetry as a double array
310 bathy_dd = mc.DataArrayDouble(np.asfarray(bathy, dtype='float'))
311 bathy_dd.setInfoOnComponents(["Z [m]"])
313 # 7.2. If requested, modification of the z coordinate
316 coords3D = ml.DataArrayDouble.Meld([coords[:,0:2], bathy_dd])
317 coords3D.setInfoOnComponents(["X [m]", "Y [m]", "Z [m]"])
318 #print "coords3D =\n", coords3D
319 meshMEDFileRead.setCoords(coords3D)
321 # 7.3. Writes the mesh
328 ligne = ".. Ecriture du maillage" + saux
329 ligne += " sur le fichier :\n%s" % fichierFMaillage
332 meshMEDFileRead.write(fichierFMaillage, 2)
334 # 7.4. Writes the field
336 med_field_name = "BOTTOM"
338 ligne = ".. Ecriture du champ '%s'" % med_field_name
341 #print "bathy_dd =\n", bathy_dd
342 fieldOnNodes = ml.MEDCouplingFieldDouble(ml.ON_NODES)
343 fieldOnNodes.setName(med_field_name)
344 fieldOnNodes.setMesh(meshMEDFileRead.getMeshAtLevel(0))
345 fieldOnNodes.setArray(bathy_dd)
346 # Ces valeurs d'instants sont mises pour assurer la lecture par TELEMAC
348 # numero d'itération : 0
349 # pas de numero d'ordre (-1)
350 fieldOnNodes.setTime(0.0, 0, -1)
352 fMEDFile_ch_d = ml.MEDFileField1TS()
353 fMEDFile_ch_d.setFieldNoProfileSBT(fieldOnNodes)
354 fMEDFile_ch_d.write(fichierFMaillage, 0)
364 def interpolZ_B(bathyName, fichierMaillage, gr_face_name, zUndef=90., interp_method=0, m3d=True, xyzFile=False, verbose=False):
366 interpolZ_B takes a 2D (x,y) mesh and calls the active instance of module HYDRO
367 to interpolate the bathymetry/altimetry on the mesh nodes, to produce the Z value of each node.
370 bathyName: Bathymetry Name in module HYDRO
371 fichierMaillage: med file name produced by SMESH, corresponding to the HYDRO case
372 gr_face_name: face group name
373 zUndef: Z value to use for nodes outside the regions (there must be none if the case is correct).
375 interp_method: interpolation method
376 0 = nearest point on bathymetry
377 1 = linear interpolation
378 m3d: True/False to produce a 3D mesh. Default is True.
379 xyzFile: True/False to write an ascii file with xyz for every node. Default is False.
381 if OK : statz_gr_face_name: statistic for z: (minz, maxz, meanz, stdz, v05z, v95z)
384 return <fichierMaillage>F.med : med file with Z value in a field "BOTTOM"
385 Option: Z value also in Z coordinate if m3D is true
386 return <fichierMaillage>.xyz : text file with X, Y, Z values
388 doc = HYDROPy.HYDROData_Document.Document(theStudyId)
389 bathy_obj = doc.FindObjectByName(bathyName)
390 print ( "bathy : ", bathy_obj)
391 if bathy_obj is None:
392 print ( "bathy is None")
395 basename = fichierMaillage[:-4]
396 fichierFMaillage = basename + 'F.med'
398 ligne = "fichierMaillage = %s" % fichierMaillage
399 ligne += "\nfichierFMaillage = %s" % fichierFMaillage
402 fichierFonds = basename + '.xyz'
403 ligne += "\nfichierFonds = %s" % fichierFonds
408 meshMEDFileRead = ml.MEDFileMesh.New(fichierMaillage)
410 print (meshMEDFileRead)
412 # 2. Checks the names of the groups of faces
414 t_group_n = meshMEDFileRead.getGroupsNames()
415 gr_face_name_tr = gr_face_name.strip()
416 if gr_face_name_tr not in t_group_n:
417 print "Group not found"
420 # 3. Gets the information about the nodes
422 nbnodes = meshMEDFileRead.getNumberOfNodes()
424 ligne = "Number of nodes: %d" % nbnodes
427 coords = meshMEDFileRead.getCoords()
430 nb_comp = coords.getNumberOfComponents()
431 l_info = coords.getInfoOnComponents()
433 l_info_0=["X", "Y", "Z"]
434 for id_node in (0, 1, nbnodes-1):
435 ligne += "\nNode #%6d:" % id_node
436 for iaux in range(nb_comp):
440 saux = l_info_0[iaux]
441 ligne += " %s" % saux
442 ligne += "=%f" % coords[id_node, iaux]
445 # 4. Exploration of every group of faces
447 tb_aux = np.zeros(nbnodes, dtype=np.bool)
449 bathy = np.zeros(nbnodes, dtype=np.float)
453 # 4.1. Mesh of the group
455 mesh_of_the_group = meshMEDFileRead.getGroup(0, gr_face_name_tr, False)
456 nbr_cells = mesh_of_the_group.getNumberOfCells()
458 ligne = "\t. Number of cells: %d" % nbr_cells
461 # 4.2. Nodes of the meshes of the group
462 # Every node is flagged in tb_aux
465 for id_elem in range(nbr_cells):
466 l_nodes = mesh_of_the_group.getNodeIdsOfCell(id_elem)
468 for id_node in l_nodes:
469 tb_aux[id_node] = True
470 np_aux = tb_aux.nonzero()
473 ligne = "\t. Number of nodes for this group: %d" % len(np_aux[0])
475 #print ("np_aux:", np_aux)
477 # 4.3. Interpolation over the nodes of the meshes of the group
481 for nodeId in np_aux[0]:
482 vx.append(coords[nodeId, 0])
483 vy.append(coords[nodeId, 1])
487 vz = bathy_obj.GetAltitudesForPoints(vx, vy, interp_method)
494 v05z = np.percentile(vz, 05)
495 v95z = np.percentile(vz, 95)
498 ligne = ".. Minimum: %f" % minz
499 ligne += ", maximum: %f" % maxz
500 ligne += ", mean: %f\n" % meanz
501 ligne += ".. stdeviation: %f" % stdz
502 ligne += ", v05z: %f" % v05z
503 ligne += ", v95z: %f" % v95z
506 # 4.4. Storage of the z and of the statistics for this region
508 statz_gr_face_name = (minz, maxz, meanz, stdz, v05z, v95z)
510 for iaux, nodeId in enumerate(np_aux[0]):
511 bathy[nodeId] = vz[iaux]
514 # During the interpolation, if no value is available over a node, a default value
515 # is set: -9999. It has no importance for the final computation, but if the field
516 # or the mesh is displayed, it makes huge gap. To prevent this artefact, a more
517 # convenient "undefined" value is set. This new undefined value is given by the user.
519 # zUndefThreshold: the default value is -9000. It is tied with the value -9999. given
520 # by the interpolation when no value is defined.
522 zUndefThreshold = -9000.
524 ligne = "zUndefThreshold: %f" % zUndefThreshold
527 #print "bathy :\n", bathy
528 np_aux_z = (bathy < zUndefThreshold).nonzero()
530 ligne = ".. Number of nodes below the minimum: %d" % len(np_aux_z[0])
533 for iaux in np_aux_z[0]:
536 # 6. Option : xyz file
540 ligne = ".. Ecriture du champ de bathymétrie sur le fichier :\n%s" % fichierFonds
543 with open(fichierFonds, "w") as fo :
544 for nodeId in range(nbnodes):
545 ligne = "%11.3f %11.3f %11.3f\n" % (coords[nodeId, 0], coords[nodeId, 1], bathy[nodeId])
549 # 7.1. Transformation of the bathymetry as a double array
551 bathy_dd = mc.DataArrayDouble(np.asfarray(bathy, dtype='float'))
552 bathy_dd.setInfoOnComponents(["Z [m]"])
554 # 7.2. If requested, modification of the z coordinate
557 coords3D = ml.DataArrayDouble.Meld([coords[:,0:2], bathy_dd])
558 coords3D.setInfoOnComponents(["X [m]", "Y [m]", "Z [m]"])
559 #print "coords3D =\n", coords3D
560 meshMEDFileRead.setCoords(coords3D)
562 # 7.3. Writes the mesh
569 ligne = ".. Ecriture du maillage" + saux
570 ligne += " sur le fichier :\n%s" % fichierFMaillage
573 meshMEDFileRead.write(fichierFMaillage, 2)
575 # 7.4. Writes the field
577 med_field_name = "BOTTOM"
579 ligne = ".. Ecriture du champ '%s'" % med_field_name
582 #print "bathy_dd =\n", bathy_dd
583 fieldOnNodes = ml.MEDCouplingFieldDouble(ml.ON_NODES)
584 fieldOnNodes.setName(med_field_name)
585 fieldOnNodes.setMesh(meshMEDFileRead.getMeshAtLevel(0))
586 fieldOnNodes.setArray(bathy_dd)
587 # Ces valeurs d'instants sont mises pour assurer la lecture par TELEMAC
589 # numero d'itération : 0
590 # pas de numero d'ordre (-1)
591 fieldOnNodes.setTime(0.0, 0, -1)
593 fMEDFile_ch_d = ml.MEDFileField1TS()
594 fMEDFile_ch_d.setFieldNoProfileSBT(fieldOnNodes)
595 fMEDFile_ch_d.write(fichierFMaillage, 0)
597 return statz_gr_face_name