1 # Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 # File : smeshBuilder.py
20 # Author : Francis KLOSS, OCC
24 from salome.geom import geomBuilder
26 import SMESH # This is necessary for back compatibility
27 import omniORB # back compatibility
28 SMESH.MED_V2_1 = 11 #omniORB.EnumItem("MED_V2_1", 11) # back compatibility: use number > MED minor version
29 SMESH.MED_V2_2 = 12 #omniORB.EnumItem("MED_V2_2", 12) # back compatibility: latest minor will be used
30 SMESH.MED_MINOR_0 = 20 # back compatibility
31 SMESH.MED_MINOR_1 = 21 # back compatibility
32 SMESH.MED_MINOR_2 = 22 # back compatibility
33 SMESH.MED_MINOR_3 = 23 # back compatibility
34 SMESH.MED_MINOR_4 = 24 # back compatibility
35 SMESH.MED_MINOR_5 = 25 # back compatibility
36 SMESH.MED_MINOR_6 = 26 # back compatibility
37 SMESH.MED_MINOR_7 = 27 # back compatibility
38 SMESH.MED_MINOR_8 = 28 # back compatibility
39 SMESH.MED_MINOR_9 = 29 # back compatibility
42 from salome.smesh.smesh_algorithm import Mesh_Algorithm
49 # In case the omniORBpy EnumItem class does not fully support Python 3
50 # (for instance in version 4.2.1-2), the comparison ordering methods must be
54 SMESH.Entity_Triangle < SMESH.Entity_Quadrangle
56 def enumitem_eq(self, other):
58 if isinstance(other, omniORB.EnumItem):
59 if other._parent_id == self._parent_id:
60 return self._v == other._v
62 return self._parent_id == other._parent_id
64 return id(self) == id(other)
66 return id(self) == id(other)
68 def enumitem_lt(self, other):
70 if isinstance(other, omniORB.EnumItem):
71 if other._parent_id == self._parent_id:
72 return self._v < other._v
74 return self._parent_id < other._parent_id
76 return id(self) < id(other)
78 return id(self) < id(other)
80 def enumitem_le(self, other):
82 if isinstance(other, omniORB.EnumItem):
83 if other._parent_id == self._parent_id:
84 return self._v <= other._v
86 return self._parent_id <= other._parent_id
88 return id(self) <= id(other)
90 return id(self) <= id(other)
92 def enumitem_gt(self, other):
94 if isinstance(other, omniORB.EnumItem):
95 if other._parent_id == self._parent_id:
96 return self._v > other._v
98 return self._parent_id > other._parent_id
100 return id(self) > id(other)
102 return id(self) > id(other)
104 def enumitem_ge(self, other):
106 if isinstance(other, omniORB.EnumItem):
107 if other._parent_id == self._parent_id:
108 return self._v >= other._v
110 return self._parent_id >= other._parent_id
112 return id(self) >= id(other)
114 return id(self) >= id(other)
116 omniORB.EnumItem.__eq__ = enumitem_eq
117 omniORB.EnumItem.__lt__ = enumitem_lt
118 omniORB.EnumItem.__le__ = enumitem_le
119 omniORB.EnumItem.__gt__ = enumitem_gt
120 omniORB.EnumItem.__ge__ = enumitem_ge
123 class MeshMeta(type):
124 """Private class used to workaround a problem that sometimes isinstance(m, Mesh) returns False
126 def __instancecheck__(cls, inst):
127 """Implement isinstance(inst, cls)."""
128 return any(cls.__subclasscheck__(c)
129 for c in {type(inst), inst.__class__})
131 def __subclasscheck__(cls, sub):
132 """Implement issubclass(sub, cls)."""
133 return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
135 def DegreesToRadians(AngleInDegrees):
136 """Convert an angle from degrees to radians
139 return AngleInDegrees * pi / 180.0
141 import salome_notebook
142 notebook = salome_notebook.notebook
143 # Salome notebook variable separator
146 def ParseParameters(*args):
148 Return list of variable values from salome notebook.
149 The last argument, if is callable, is used to modify values got from notebook
155 if args and callable(args[-1]):
156 args, varModifFun = args[:-1], args[-1]
157 for parameter in args:
159 Parameters += str(parameter) + var_separator
161 if isinstance(parameter,str):
162 # check if there is an inexistent variable name
163 if not notebook.isVariable(parameter):
164 raise ValueError("Variable with name '" + parameter + "' doesn't exist!!!")
165 parameter = notebook.get(parameter)
168 parameter = varModifFun(parameter)
171 Result.append(parameter)
174 Parameters = Parameters[:-1]
175 Result.append( Parameters )
176 Result.append( hasVariables )
179 def ParseAngles(*args):
181 Parse parameters while converting variables to radians
183 return ParseParameters( *( args + (DegreesToRadians, )))
185 def __initPointStruct(point,*args):
187 Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
188 Parameters are stored in PointStruct.parameters attribute
190 point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
192 SMESH.PointStruct.__init__ = __initPointStruct
194 def __initAxisStruct(ax,*args):
196 Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
197 Parameters are stored in AxisStruct.parameters attribute
200 raise RuntimeError("Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args )))
201 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
203 SMESH.AxisStruct.__init__ = __initAxisStruct
205 smeshPrecisionConfusion = 1.e-07
206 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
207 """Compare real values using smeshPrecisionConfusion as tolerance
209 if abs(val1 - val2) < tol:
217 Return a name of an object
224 if isinstance(obj, SALOMEDS._objref_SObject):
228 ior = salome.orb.object_to_string(obj)
232 sobj = salome.myStudy.FindObjectIOR(ior)
234 return sobj.GetName()
235 if hasattr(obj, "GetName"):
236 # unknown CORBA object, having GetName() method
239 # unknown CORBA object, no GetName() method
242 if hasattr(obj, "GetName"):
243 # unknown non-CORBA object, having GetName() method
246 raise RuntimeError("Null or invalid object")
248 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
250 Print error message if a hypothesis was not assigned.
253 hypType = "algorithm"
255 hypType = "hypothesis"
258 if hasattr( status, "__getitem__" ):
259 status, reason = status[0], status[1]
260 if status == HYP_UNKNOWN_FATAL:
261 reason = "for unknown reason"
262 elif status == HYP_INCOMPATIBLE:
263 reason = "this hypothesis mismatches the algorithm"
264 elif status == HYP_NOTCONFORM:
265 reason = "a non-conform mesh would be built"
266 elif status == HYP_ALREADY_EXIST:
267 if isAlgo: return # it does not influence anything
268 reason = hypType + " of the same dimension is already assigned to this shape"
269 elif status == HYP_BAD_DIM:
270 reason = hypType + " mismatches the shape"
271 elif status == HYP_CONCURRENT :
272 reason = "there are concurrent hypotheses on sub-shapes"
273 elif status == HYP_BAD_SUBSHAPE:
274 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
275 elif status == HYP_BAD_GEOMETRY:
276 reason = "the algorithm is not applicable to this geometry"
277 elif status == HYP_HIDDEN_ALGO:
278 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
279 elif status == HYP_HIDING_ALGO:
280 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
281 elif status == HYP_NEED_SHAPE:
282 reason = "algorithm can't work without shape"
283 elif status == HYP_INCOMPAT_HYPS:
289 where = '"%s"' % geomName
291 meshName = GetName( mesh )
292 if meshName and meshName != NO_NAME:
293 where = '"%s" shape in "%s" mesh ' % ( geomName, meshName )
294 if status < HYP_UNKNOWN_FATAL and where:
295 print('"%s" was assigned to %s but %s' %( hypName, where, reason ))
297 print('"%s" was not assigned to %s : %s' %( hypName, where, reason ))
299 print('"%s" was not assigned : %s' %( hypName, reason ))
302 def AssureGeomPublished(mesh, geom, name=''):
304 Private method. Add geom (sub-shape of the main shape) into the study if not yet there
306 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
308 if not geom.GetStudyEntry():
310 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
311 # for all groups SubShapeName() return "Compound_-1"
312 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
314 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
316 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
319 def FirstVertexOnCurve(mesh, edge):
322 the first vertex of a geometrical edge by ignoring orientation
324 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
326 raise TypeError("Given object has no vertices")
327 if len( vv ) == 1: return vv[0]
328 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
329 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
330 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
331 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
334 dist1 += abs( xyz[i] - xyz1[i] )
335 dist2 += abs( xyz[i] - xyz2[i] )
344 smeshInst is a singleton
350 class smeshBuilder( SMESH._objref_SMESH_Gen, object ):
352 This class allows to create, load or manipulate meshes.
353 It has a set of methods to create, load or copy meshes, to combine several meshes, etc.
354 It also has methods to get infos and measure meshes.
357 # MirrorType enumeration
358 POINT = SMESH_MeshEditor.POINT
359 AXIS = SMESH_MeshEditor.AXIS
360 PLANE = SMESH_MeshEditor.PLANE
362 # Smooth_Method enumeration
363 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
364 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
366 PrecisionConfusion = smeshPrecisionConfusion
368 # TopAbs_State enumeration
369 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = list(range(4))
371 # Methods of splitting a hexahedron into tetrahedra
372 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
374 def __new__(cls, *args):
378 #print("==== __new__", engine, smeshInst, doLcc)
380 if smeshInst is None:
381 # smesh engine is either retrieved from engine, or created
383 # Following test avoids a recursive loop
385 if smeshInst is not None:
386 # smesh engine not created: existing engine found
390 # FindOrLoadComponent called:
391 # 1. CORBA resolution of server
392 # 2. the __new__ method is called again
393 #print("==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc)
394 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
396 # FindOrLoadComponent not called
397 if smeshInst is None:
398 # smeshBuilder instance is created from lcc.FindOrLoadComponent
399 #print("==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc)
400 smeshInst = super(smeshBuilder,cls).__new__(cls)
402 # smesh engine not created: existing engine found
403 #print("==== existing ", engine, smeshInst, doLcc)
405 #print("====1 ", smeshInst)
408 #print("====2 ", smeshInst)
411 def __init__(self, *args):
413 #print("--------------- smeshbuilder __init__ ---", created)
416 SMESH._objref_SMESH_Gen.__init__(self, *args)
419 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
421 Dump component to the Python script.
422 This method overrides IDL function to allow default values for the parameters.
425 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
427 def SetDumpPythonHistorical(self, isHistorical):
429 Set mode of DumpPython(), *historical* or *snapshot*.
430 In the *historical* mode, the Python Dump script includes all commands
431 performed by SMESH engine. In the *snapshot* mode, commands
432 relating to objects removed from the Study are excluded from the script
433 as well as commands not influencing the current state of meshes
436 if isHistorical: val = "true"
438 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
440 def init_smesh(self,geompyD = None):
442 Set Geometry component
445 self.UpdateStudy(geompyD)
446 notebook.myStudy = salome.myStudy
448 def Mesh(self, obj=0, name=0):
450 Create a mesh. This mesh can be either
452 * an empty mesh not bound to geometry, if *obj* == 0
453 * an empty mesh bound to geometry, if *obj* is GEOM.GEOM_Object
454 * a mesh wrapping a :class:`CORBA mesh <SMESH.SMESH_Mesh>` given as *obj* parameter.
459 1. a :class:`CORBA mesh <SMESH.SMESH_Mesh>` got by calling e.g.
462 salome.myStudy.FindObjectID("0:1:2:3").GetObject()
464 2. a geometrical object for meshing
466 name: the name for the new mesh.
469 an instance of class :class:`Mesh`.
472 if isinstance(obj,str):
474 return Mesh(self, self.geompyD, obj, name)
476 def EnumToLong(self,theItem):
478 Return a long value from enumeration
483 def ColorToString(self,c):
485 Convert SALOMEDS.Color to string.
486 To be used with filters.
489 c: color value (SALOMEDS.Color)
492 a string representation of the color.
496 if isinstance(c, SALOMEDS.Color):
497 val = "%s;%s;%s" % (c.R, c.G, c.B)
498 elif isinstance(c, str):
501 raise ValueError("Color value should be of string or SALOMEDS.Color type")
504 def GetPointStruct(self,theVertex):
506 Get :class:`SMESH.PointStruct` from vertex
509 theVertex (GEOM.GEOM_Object): vertex
512 :class:`SMESH.PointStruct`
515 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
516 return PointStruct(x,y,z)
518 def GetDirStruct(self,theVector):
520 Get :class:`SMESH.DirStruct` from vector
523 theVector (GEOM.GEOM_Object): vector
526 :class:`SMESH.DirStruct`
529 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
530 if(len(vertices) != 2):
531 print("Error: vector object is incorrect.")
533 p1 = self.geompyD.PointCoordinates(vertices[0])
534 p2 = self.geompyD.PointCoordinates(vertices[1])
535 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
536 dirst = DirStruct(pnt)
539 def MakeDirStruct(self,x,y,z):
541 Make :class:`SMESH.DirStruct` from a triplet of floats
544 x,y,z (float): vector components
547 :class:`SMESH.DirStruct`
550 pnt = PointStruct(x,y,z)
551 return DirStruct(pnt)
553 def GetAxisStruct(self,theObj):
555 Get :class:`SMESH.AxisStruct` from a geometrical object
558 theObj (GEOM.GEOM_Object): line or plane
561 :class:`SMESH.AxisStruct`
564 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
567 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
568 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
569 vertex1 = self.geompyD.PointCoordinates(vertex1)
570 vertex2 = self.geompyD.PointCoordinates(vertex2)
571 vertex3 = self.geompyD.PointCoordinates(vertex3)
572 vertex4 = self.geompyD.PointCoordinates(vertex4)
573 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
574 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
575 normal = [ v1[1]*v2[2]-v2[1]*v1[2], v1[2]*v2[0]-v2[2]*v1[0], v1[0]*v2[1]-v2[0]*v1[1] ]
576 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
577 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
578 elif len(edges) == 1:
579 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
580 p1 = self.geompyD.PointCoordinates( vertex1 )
581 p2 = self.geompyD.PointCoordinates( vertex2 )
582 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
583 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
584 elif theObj.GetShapeType() == GEOM.VERTEX:
585 x,y,z = self.geompyD.PointCoordinates( theObj )
586 axis = AxisStruct( x,y,z, 1,0,0,)
587 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
590 # From SMESH_Gen interface:
591 # ------------------------
593 def SetName(self, obj, name):
595 Set the given name to an object
598 obj: the object to rename
599 name: a new object name
602 if isinstance( obj, Mesh ):
604 elif isinstance( obj, Mesh_Algorithm ):
605 obj = obj.GetAlgorithm()
606 ior = salome.orb.object_to_string(obj)
607 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
609 def SetEmbeddedMode( self,theMode ):
614 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
616 def IsEmbeddedMode(self):
621 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
623 def UpdateStudy( self, geompyD = None ):
625 Update the current study. Calling UpdateStudy() allows to
626 update meshes at switching GEOM->SMESH
630 from salome.geom import geomBuilder
631 geompyD = geomBuilder.geom
633 geompyD = geomBuilder.New()
636 self.SetGeomEngine(geompyD)
637 SMESH._objref_SMESH_Gen.UpdateStudy(self)
638 sb = salome.myStudy.NewBuilder()
639 sc = salome.myStudy.FindComponent("SMESH")
641 sb.LoadWith(sc, self)
644 def SetEnablePublish( self, theIsEnablePublish ):
646 Set enable publishing in the study. Calling SetEnablePublish( False ) allows to
647 switch **off** publishing in the Study of mesh objects.
649 #self.SetEnablePublish(theIsEnablePublish)
650 SMESH._objref_SMESH_Gen.SetEnablePublish(self,theIsEnablePublish)
652 notebook = salome_notebook.NoteBook( theIsEnablePublish )
655 def CreateMeshesFromUNV( self,theFileName ):
657 Create a Mesh object importing data from the given UNV file
660 an instance of class :class:`Mesh`
663 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
664 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
667 def CreateMeshesFromMED( self,theFileName ):
669 Create a Mesh object(s) importing data from the given MED file
672 a tuple ( list of class :class:`Mesh` instances,
673 :class:`SMESH.DriverMED_ReadStatus` )
676 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
677 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
678 return aMeshes, aStatus
680 def CreateMeshesFromSAUV( self,theFileName ):
682 Create a Mesh object(s) importing data from the given SAUV file
685 a tuple ( list of class :class:`Mesh` instances, :class:`SMESH.DriverMED_ReadStatus` )
688 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
689 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
690 return aMeshes, aStatus
692 def CreateMeshesFromSTL( self, theFileName ):
694 Create a Mesh object importing data from the given STL file
697 an instance of class :class:`Mesh`
700 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
701 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
704 def CreateMeshesFromCGNS( self, theFileName ):
706 Create Mesh objects importing data from the given CGNS file
709 a tuple ( list of class :class:`Mesh` instances, :class:`SMESH.DriverMED_ReadStatus` )
712 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
713 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
714 return aMeshes, aStatus
716 def CreateMeshesFromGMF( self, theFileName ):
718 Create a Mesh object importing data from the given GMF file.
719 GMF files must have .mesh extension for the ASCII format and .meshb for
723 ( an instance of class :class:`Mesh`, :class:`SMESH.ComputeError` )
726 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
729 if error.comment: print("*** CreateMeshesFromGMF() errors:\n", error.comment)
730 return Mesh(self, self.geompyD, aSmeshMesh), error
732 def Concatenate( self, meshes, uniteIdenticalGroups,
733 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
736 Concatenate the given meshes into one mesh. All groups of input meshes will be
737 present in the new mesh.
740 meshes: :class:`meshes, sub-meshes, groups or filters <SMESH.SMESH_IDSource>` to combine into one mesh
741 uniteIdenticalGroups: if True, groups with same names are united, else they are renamed
742 mergeNodesAndElements: if True, equal nodes and elements are merged
743 mergeTolerance: tolerance for merging nodes
744 allGroups: forces creation of groups corresponding to every input mesh
745 name: name of a new mesh
748 an instance of class :class:`Mesh`
751 if not meshes: return None
752 for i,m in enumerate(meshes):
753 if isinstance(m, Mesh):
754 meshes[i] = m.GetMesh()
755 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
756 meshes[0].SetParameters(Parameters)
758 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
759 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
761 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
762 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
763 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
766 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
768 Create a mesh by copying a part of another mesh.
771 meshPart: a part of mesh to copy, either
772 :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`.
773 To copy nodes or elements not forming any mesh object,
774 pass result of :meth:`Mesh.GetIDSource` as *meshPart*
775 meshName: a name of the new mesh
776 toCopyGroups: to create in the new mesh groups the copied elements belongs to
777 toKeepIDs: to preserve order of the copied elements or not
780 an instance of class :class:`Mesh`
783 if (isinstance( meshPart, Mesh )):
784 meshPart = meshPart.GetMesh()
785 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
786 return Mesh(self, self.geompyD, mesh)
788 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
790 Return IDs of sub-shapes
793 theMainObject (GEOM.GEOM_Object): a shape
794 theListOfSubObjects: sub-shapes (list of GEOM.GEOM_Object)
796 the list of integer values
799 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
801 def GetPattern(self):
803 Create a pattern mapper.
806 an instance of :class:`SMESH.SMESH_Pattern`
808 :ref:`Example of Patterns usage <tui_pattern_mapping>`
811 return SMESH._objref_SMESH_Gen.GetPattern(self)
813 def SetBoundaryBoxSegmentation(self, nbSegments):
815 Set number of segments per diagonal of boundary box of geometry, by which
816 default segment length of appropriate 1D hypotheses is defined in GUI.
820 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
822 # Filtering. Auxiliary functions:
823 # ------------------------------
825 def GetEmptyCriterion(self):
827 Create an empty criterion
830 :class:`SMESH.Filter.Criterion`
833 Type = self.EnumToLong(FT_Undefined)
834 Compare = self.EnumToLong(FT_Undefined)
838 UnaryOp = self.EnumToLong(FT_Undefined)
839 BinaryOp = self.EnumToLong(FT_Undefined)
842 Precision = -1 ##@1e-07
843 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
844 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
846 def GetCriterion(self,elementType,
848 Compare = FT_EqualTo,
850 UnaryOp=FT_Undefined,
851 BinaryOp=FT_Undefined,
854 Create a criterion by the given parameters
855 Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
858 elementType: the :class:`type of elements <SMESH.ElementType>` (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
859 CritType: the type of criterion :class:`SMESH.FunctorType` (SMESH.FT_Taper, SMESH.FT_Area, etc.).
860 Note that the items starting from FT_LessThan are not suitable for *CritType*.
861 Compare: belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
862 Threshold: the threshold value (range of ids as string, shape, numeric)
863 UnaryOp: SMESH.FT_LogicalNOT or SMESH.FT_Undefined
864 BinaryOp: a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or
866 Tolerance: the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
867 SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
870 :class:`SMESH.Filter.Criterion`
872 Example: :ref:`combining_filters`
875 if not CritType in SMESH.FunctorType._items:
876 raise TypeError("CritType should be of SMESH.FunctorType")
877 aCriterion = self.GetEmptyCriterion()
878 aCriterion.TypeOfElement = elementType
879 aCriterion.Type = self.EnumToLong(CritType)
880 aCriterion.Tolerance = Tolerance
882 aThreshold = Threshold
884 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
885 aCriterion.Compare = self.EnumToLong(Compare)
886 elif Compare == "=" or Compare == "==":
887 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
889 aCriterion.Compare = self.EnumToLong(FT_LessThan)
891 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
892 elif Compare != FT_Undefined:
893 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
896 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
897 FT_BelongToCylinder, FT_LyingOnGeom]:
898 # Check that Threshold is GEOM object
899 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
900 aCriterion.ThresholdStr = GetName(aThreshold)
901 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
902 if not aCriterion.ThresholdID:
903 name = aCriterion.ThresholdStr
905 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
906 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
907 # or a name of GEOM object
908 elif isinstance( aThreshold, str ):
909 aCriterion.ThresholdStr = aThreshold
911 raise TypeError("The Threshold should be a shape.")
912 if isinstance(UnaryOp,float):
913 aCriterion.Tolerance = UnaryOp
914 UnaryOp = FT_Undefined
916 elif CritType == FT_BelongToMeshGroup:
917 # Check that Threshold is a group
918 if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
919 if aThreshold.GetType() != elementType:
920 raise ValueError("Group type mismatches Element type")
921 aCriterion.ThresholdStr = aThreshold.GetName()
922 aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
923 study = salome.myStudy
925 so = study.FindObjectIOR( aCriterion.ThresholdID )
929 aCriterion.ThresholdID = entry
931 raise TypeError("The Threshold should be a Mesh Group")
932 elif CritType == FT_RangeOfIds:
933 # Check that Threshold is string
934 if isinstance(aThreshold, str):
935 aCriterion.ThresholdStr = aThreshold
937 raise TypeError("The Threshold should be a string.")
938 elif CritType == FT_CoplanarFaces:
939 # Check the Threshold
940 if isinstance(aThreshold, int):
941 aCriterion.ThresholdID = str(aThreshold)
942 elif isinstance(aThreshold, str):
945 raise ValueError("Invalid ID of mesh face: '%s'"%aThreshold)
946 aCriterion.ThresholdID = aThreshold
948 raise TypeError("The Threshold should be an ID of mesh face and not '%s'"%aThreshold)
949 elif CritType == FT_ConnectedElements:
950 # Check the Threshold
951 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
952 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
953 if not aCriterion.ThresholdID:
954 name = aThreshold.GetName()
956 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
957 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
958 elif isinstance(aThreshold, int): # node id
959 aCriterion.Threshold = aThreshold
960 elif isinstance(aThreshold, list): # 3 point coordinates
961 if len( aThreshold ) < 3:
962 raise ValueError("too few point coordinates, must be 3")
963 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
964 elif isinstance(aThreshold, str):
965 if aThreshold.isdigit():
966 aCriterion.Threshold = aThreshold # node id
968 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
970 raise TypeError("The Threshold should either a VERTEX, or a node ID, "\
971 "or a list of point coordinates and not '%s'"%aThreshold)
972 elif CritType == FT_ElemGeomType:
973 # Check the Threshold
975 aCriterion.Threshold = self.EnumToLong(aThreshold)
976 assert( aThreshold in SMESH.GeometryType._items )
978 if isinstance(aThreshold, int):
979 aCriterion.Threshold = aThreshold
981 raise TypeError("The Threshold should be an integer or SMESH.GeometryType.")
984 elif CritType == FT_EntityType:
985 # Check the Threshold
987 aCriterion.Threshold = self.EnumToLong(aThreshold)
988 assert( aThreshold in SMESH.EntityType._items )
990 if isinstance(aThreshold, int):
991 aCriterion.Threshold = aThreshold
993 raise TypeError("The Threshold should be an integer or SMESH.EntityType.")
997 elif CritType == FT_GroupColor:
998 # Check the Threshold
1000 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
1002 raise TypeError("The threshold value should be of SALOMEDS.Color type")
1004 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
1005 FT_LinearOrQuadratic, FT_BadOrientedVolume,
1006 FT_BareBorderFace, FT_BareBorderVolume,
1007 FT_OverConstrainedFace, FT_OverConstrainedVolume,
1008 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
1009 # At this point the Threshold is unnecessary
1010 if aThreshold == FT_LogicalNOT:
1011 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
1012 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
1013 aCriterion.BinaryOp = aThreshold
1017 aThreshold = float(aThreshold)
1018 aCriterion.Threshold = aThreshold
1020 raise TypeError("The Threshold should be a number.")
1023 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
1024 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
1026 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
1027 aCriterion.BinaryOp = self.EnumToLong(Threshold)
1029 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
1030 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
1032 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
1033 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
1037 def GetFilter(self,elementType,
1038 CritType=FT_Undefined,
1041 UnaryOp=FT_Undefined,
1045 Create a filter with the given parameters
1048 elementType: the :class:`type of elements <SMESH.ElementType>` (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1049 CritType: the :class:`type of criterion <SMESH.FunctorType>` (SMESH.FT_Taper, SMESH.FT_Area, etc.).
1050 Note that the items starting from FT_LessThan are not suitable for CritType.
1051 Compare: belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
1052 Threshold: the threshold value (range of ids as string, shape, numeric)
1053 UnaryOp: SMESH.FT_LogicalNOT or SMESH.FT_Undefined
1054 Tolerance: the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
1055 SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
1056 mesh: the mesh to initialize the filter with
1059 :class:`SMESH.Filter`
1062 See :doc:`Filters usage examples <tui_filters>`
1065 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1066 aFilterMgr = self.CreateFilterManager()
1067 aFilter = aFilterMgr.CreateFilter()
1069 aCriteria.append(aCriterion)
1070 aFilter.SetCriteria(aCriteria)
1072 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
1073 else : aFilter.SetMesh( mesh )
1074 aFilterMgr.UnRegister()
1077 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
1079 Create a filter from criteria
1082 criteria: a list of :class:`SMESH.Filter.Criterion`
1083 binOp: binary operator used when binary operator of criteria is undefined
1086 :class:`SMESH.Filter`
1089 See :doc:`Filters usage examples <tui_filters>`
1092 for i in range( len( criteria ) - 1 ):
1093 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
1094 criteria[i].BinaryOp = self.EnumToLong( binOp )
1095 aFilterMgr = self.CreateFilterManager()
1096 aFilter = aFilterMgr.CreateFilter()
1097 aFilter.SetCriteria(criteria)
1098 aFilterMgr.UnRegister()
1101 def GetFunctor(self,theCriterion):
1103 Create a numerical functor by its type
1106 theCriterion (SMESH.FunctorType): functor type.
1107 Note that not all items correspond to numerical functors.
1110 :class:`SMESH.NumericalFunctor`
1113 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
1115 aFilterMgr = self.CreateFilterManager()
1117 if theCriterion == FT_AspectRatio:
1118 functor = aFilterMgr.CreateAspectRatio()
1119 elif theCriterion == FT_AspectRatio3D:
1120 functor = aFilterMgr.CreateAspectRatio3D()
1121 elif theCriterion == FT_Warping:
1122 functor = aFilterMgr.CreateWarping()
1123 elif theCriterion == FT_MinimumAngle:
1124 functor = aFilterMgr.CreateMinimumAngle()
1125 elif theCriterion == FT_Taper:
1126 functor = aFilterMgr.CreateTaper()
1127 elif theCriterion == FT_Skew:
1128 functor = aFilterMgr.CreateSkew()
1129 elif theCriterion == FT_Area:
1130 functor = aFilterMgr.CreateArea()
1131 elif theCriterion == FT_Volume3D:
1132 functor = aFilterMgr.CreateVolume3D()
1133 elif theCriterion == FT_MaxElementLength2D:
1134 functor = aFilterMgr.CreateMaxElementLength2D()
1135 elif theCriterion == FT_MaxElementLength3D:
1136 functor = aFilterMgr.CreateMaxElementLength3D()
1137 elif theCriterion == FT_MultiConnection:
1138 functor = aFilterMgr.CreateMultiConnection()
1139 elif theCriterion == FT_MultiConnection2D:
1140 functor = aFilterMgr.CreateMultiConnection2D()
1141 elif theCriterion == FT_Length:
1142 functor = aFilterMgr.CreateLength()
1143 elif theCriterion == FT_Length2D:
1144 functor = aFilterMgr.CreateLength2D()
1145 elif theCriterion == FT_Deflection2D:
1146 functor = aFilterMgr.CreateDeflection2D()
1147 elif theCriterion == FT_NodeConnectivityNumber:
1148 functor = aFilterMgr.CreateNodeConnectivityNumber()
1149 elif theCriterion == FT_BallDiameter:
1150 functor = aFilterMgr.CreateBallDiameter()
1152 print("Error: given parameter is not numerical functor type.")
1153 aFilterMgr.UnRegister()
1156 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
1161 theHType (string): mesh hypothesis type
1162 theLibName (string): mesh plug-in library name
1165 created hypothesis instance
1167 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
1169 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
1172 # wrap hypothesis methods
1173 for meth_name in dir( hyp.__class__ ):
1174 if not meth_name.startswith("Get") and \
1175 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
1176 method = getattr ( hyp.__class__, meth_name )
1177 if callable(method):
1178 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
1182 def GetMeshInfo(self, obj):
1184 Get the mesh statistic.
1185 Use :meth:`smeshBuilder.EnumToLong` to get an integer from
1186 an item of :class:`SMESH.EntityType`.
1189 dictionary { :class:`SMESH.EntityType` - "count of elements" }
1192 if isinstance( obj, Mesh ):
1195 if hasattr(obj, "GetMeshInfo"):
1196 values = obj.GetMeshInfo()
1197 for i in range(SMESH.Entity_Last._v):
1198 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1202 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1204 Get minimum distance between two objects
1206 * If *src2* is None, and *id2* = 0, distance from *src1* / *id1* to the origin is computed.
1207 * If *src2* is None, and *id2* != 0, it is assumed that both *id1* and *id2* belong to *src1*.
1210 src1 (SMESH.SMESH_IDSource): first source object
1211 src2 (SMESH.SMESH_IDSource): second source object
1212 id1 (int): node/element id from the first source
1213 id2 (int): node/element id from the second (or first) source
1214 isElem1 (boolean): *True* if *id1* is element id, *False* if it is node id
1215 isElem2 (boolean): *True* if *id2* is element id, *False* if it is node id
1218 minimum distance value
1221 :meth:`GetMinDistance`
1224 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1228 result = result.value
1231 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1233 Get :class:`SMESH.Measure` structure specifying minimum distance data between two objects
1235 * If *src2* is None, and *id2* = 0, distance from *src1* / *id1* to the origin is computed.
1236 * If *src2* is None, and *id2* != 0, it is assumed that both *id1* and *id2* belong to *src1*.
1239 src1 (SMESH.SMESH_IDSource): first source object
1240 src2 (SMESH.SMESH_IDSource): second source object
1241 id1 (int): node/element id from the first source
1242 id2 (int): node/element id from the second (or first) source
1243 isElem1 (boolean): *True* if **id1** is element id, *False* if it is node id
1244 isElem2 (boolean): *True* if **id2** is element id, *False* if it is node id
1247 :class:`SMESH.Measure` structure or None if input data is invalid
1252 if isinstance(src1, Mesh): src1 = src1.mesh
1253 if isinstance(src2, Mesh): src2 = src2.mesh
1254 if src2 is None and id2 != 0: src2 = src1
1255 if not hasattr(src1, "_narrow"): return None
1256 src1 = src1._narrow(SMESH.SMESH_IDSource)
1257 if not src1: return None
1258 unRegister = genObjUnRegister()
1261 e = m.GetMeshEditor()
1263 src1 = e.MakeIDSource([id1], SMESH.FACE)
1265 src1 = e.MakeIDSource([id1], SMESH.NODE)
1266 unRegister.set( src1 )
1268 if hasattr(src2, "_narrow"):
1269 src2 = src2._narrow(SMESH.SMESH_IDSource)
1270 if src2 and id2 != 0:
1272 e = m.GetMeshEditor()
1274 src2 = e.MakeIDSource([id2], SMESH.FACE)
1276 src2 = e.MakeIDSource([id2], SMESH.NODE)
1277 unRegister.set( src2 )
1280 aMeasurements = self.CreateMeasurements()
1281 unRegister.set( aMeasurements )
1282 result = aMeasurements.MinDistance(src1, src2)
1285 def BoundingBox(self, objects):
1287 Get bounding box of the specified object(s)
1290 objects (SMESH.SMESH_IDSource): single source object or list of source objects
1293 tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1296 :meth:`GetBoundingBox`
1299 result = self.GetBoundingBox(objects)
1303 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1306 def GetBoundingBox(self, objects):
1308 Get :class:`SMESH.Measure` structure specifying bounding box data of the specified object(s)
1311 objects (SMESH.SMESH_IDSource): single source object or list of source objects
1314 :class:`SMESH.Measure` structure
1320 if isinstance(objects, tuple):
1321 objects = list(objects)
1322 if not isinstance(objects, list):
1326 if isinstance(o, Mesh):
1327 srclist.append(o.mesh)
1328 elif hasattr(o, "_narrow"):
1329 src = o._narrow(SMESH.SMESH_IDSource)
1330 if src: srclist.append(src)
1333 aMeasurements = self.CreateMeasurements()
1334 result = aMeasurements.BoundingBox(srclist)
1335 aMeasurements.UnRegister()
1338 def GetLength(self, obj):
1340 Get sum of lengths of all 1D elements in the mesh object.
1343 obj: :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
1346 sum of lengths of all 1D elements
1349 if isinstance(obj, Mesh): obj = obj.mesh
1350 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1351 aMeasurements = self.CreateMeasurements()
1352 value = aMeasurements.Length(obj)
1353 aMeasurements.UnRegister()
1356 def GetArea(self, obj):
1358 Get sum of areas of all 2D elements in the mesh object.
1361 obj: :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
1364 sum of areas of all 2D elements
1367 if isinstance(obj, Mesh): obj = obj.mesh
1368 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1369 aMeasurements = self.CreateMeasurements()
1370 value = aMeasurements.Area(obj)
1371 aMeasurements.UnRegister()
1374 def GetVolume(self, obj):
1376 Get sum of volumes of all 3D elements in the mesh object.
1379 obj: :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
1382 sum of volumes of all 3D elements
1385 if isinstance(obj, Mesh): obj = obj.mesh
1386 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1387 aMeasurements = self.CreateMeasurements()
1388 value = aMeasurements.Volume(obj)
1389 aMeasurements.UnRegister()
1392 def GetGravityCenter(self, obj):
1394 Get gravity center of all nodes of the mesh object.
1397 obj: :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
1400 Three components of the gravity center (x,y,z)
1402 if isinstance(obj, Mesh): obj = obj.mesh
1403 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1404 aMeasurements = self.CreateMeasurements()
1405 pointStruct = aMeasurements.GravityCenter(obj)
1406 aMeasurements.UnRegister()
1407 return pointStruct.x, pointStruct.y, pointStruct.z
1409 pass # end of class smeshBuilder
1412 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1413 """Registering the new proxy for SMESH.SMESH_Gen"""
1416 def New( instance=None, instanceGeom=None):
1418 Create a new smeshBuilder instance. The smeshBuilder class provides the Python
1419 interface to create or load meshes.
1424 salome.salome_init()
1425 from salome.smesh import smeshBuilder
1426 smesh = smeshBuilder.New()
1429 instance: CORBA proxy of SMESH Engine. If None, the default Engine is used.
1430 instanceGeom: CORBA proxy of GEOM Engine. If None, the default Engine is used.
1432 :class:`smeshBuilder` instance
1437 if instance and isinstance( instance, SALOMEDS._objref_Study ):
1439 sys.stderr.write("Warning: 'study' argument is no more needed in smeshBuilder.New(). Consider updating your script!!!\n\n")
1444 smeshInst = smeshBuilder()
1445 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1446 smeshInst.init_smesh(instanceGeom)
1450 # Public class: Mesh
1451 # ==================
1454 class Mesh(metaclass = MeshMeta):
1456 This class allows defining and managing a mesh.
1457 It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1458 It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1459 new nodes and elements and by changing the existing entities), to get information
1460 about a mesh and to export a mesh in different formats.
1467 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1472 Create a mesh on the shape *obj* (or an empty mesh if *obj* is equal to 0) and
1473 sets the GUI name of this mesh to *name*.
1476 smeshpyD: an instance of smeshBuilder class
1477 geompyD: an instance of geomBuilder class
1478 obj: Shape to be meshed or :class:`SMESH.SMESH_Mesh` object
1479 name: Study name of the mesh
1482 self.smeshpyD = smeshpyD
1483 self.geompyD = geompyD
1488 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1491 # publish geom of mesh (issue 0021122)
1492 if not self.geom.GetStudyEntry():
1496 geo_name = name + " shape"
1498 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1499 geompyD.addToStudy( self.geom, geo_name )
1500 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1502 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1505 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1507 self.smeshpyD.SetName(self.mesh, name)
1509 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1512 self.geom = self.mesh.GetShapeToMesh()
1514 self.editor = self.mesh.GetMeshEditor()
1515 self.functors = [None] * SMESH.FT_Undefined._v
1517 # set self to algoCreator's
1518 for attrName in dir(self):
1519 attr = getattr( self, attrName )
1520 if isinstance( attr, algoCreator ):
1521 setattr( self, attrName, attr.copy( self ))
1528 Destructor. Clean-up resources
1531 #self.mesh.UnRegister()
1535 def SetMesh(self, theMesh):
1537 Initialize the Mesh object from an instance of :class:`SMESH.SMESH_Mesh` interface
1540 theMesh: a :class:`SMESH.SMESH_Mesh` object
1544 # do not call Register() as this prevents mesh servant deletion at closing study
1545 #if self.mesh: self.mesh.UnRegister()
1548 #self.mesh.Register()
1549 self.geom = self.mesh.GetShapeToMesh()
1554 Return the mesh, that is an encapsulated instance of :class:`SMESH.SMESH_Mesh` interface
1557 a :class:`SMESH.SMESH_Mesh` object
1564 Get the name of the mesh
1567 the name of the mesh as a string
1570 name = GetName(self.GetMesh())
1573 def SetName(self, name):
1575 Set a name to the mesh
1578 name: a new name of the mesh
1581 self.smeshpyD.SetName(self.GetMesh(), name)
1583 def GetSubMesh(self, geom, name):
1585 Get a sub-mesh object associated to a *geom* geometrical object.
1588 geom: a geometrical object (shape)
1589 name: a name for the sub-mesh in the Object Browser
1592 an object of type :class:`SMESH.SMESH_subMesh`, representing a part of mesh,
1593 which lies on the given shape
1596 A sub-mesh is implicitly created when a sub-shape is specified at
1597 creating an algorithm, for example::
1599 algo1D = mesh.Segment(geom=Edge_1)
1601 create a sub-mesh on *Edge_1* and assign Wire Discretization algorithm to it.
1602 The created sub-mesh can be retrieved from the algorithm::
1604 submesh = algo1D.GetSubMesh()
1607 AssureGeomPublished( self, geom, name )
1608 submesh = self.mesh.GetSubMesh( geom, name )
1613 Return the shape associated to the mesh
1621 def SetShape(self, geom):
1623 Associate the given shape to the mesh (entails the recreation of the mesh)
1626 geom: the shape to be meshed (GEOM_Object)
1629 self.mesh = self.smeshpyD.CreateMesh(geom)
1631 def HasShapeToMesh(self):
1633 Return ``True`` if this mesh is based on geometry
1635 return self.mesh.HasShapeToMesh()
1639 Load mesh from the study after opening the study
1643 def IsReadyToCompute(self, theSubObject):
1645 Return true if the hypotheses are defined well
1648 theSubObject: a sub-shape of a mesh shape
1654 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1656 def GetAlgoState(self, theSubObject):
1658 Return errors of hypotheses definition.
1659 The list of errors is empty if everything is OK.
1662 theSubObject: a sub-shape of a mesh shape
1668 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1670 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1672 Return a geometrical object on which the given element was built.
1673 The returned geometrical object, if not nil, is either found in the
1674 study or published by this method with the given name
1677 theElementID: the id of the mesh element
1678 theGeomName: the user-defined name of the geometrical object
1681 GEOM.GEOM_Object instance
1684 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1686 def MeshDimension(self):
1688 Return the mesh dimension depending on the dimension of the underlying shape
1689 or, if the mesh is not based on any shape, basing on deimension of elements
1692 mesh dimension as an integer value [0,3]
1695 if self.mesh.HasShapeToMesh():
1696 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1697 if len( shells ) > 0 :
1699 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1701 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1706 if self.NbVolumes() > 0: return 3
1707 if self.NbFaces() > 0: return 2
1708 if self.NbEdges() > 0: return 1
1711 def Evaluate(self, geom=0):
1713 Evaluate size of prospective mesh on a shape
1716 a list where i-th element is a number of elements of i-th :class:`SMESH.EntityType`.
1717 To know predicted number of e.g. edges, inquire it this way::
1719 Evaluate()[ smesh.EnumToLong( SMESH.Entity_Edge )]
1722 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1724 geom = self.mesh.GetShapeToMesh()
1727 return self.smeshpyD.Evaluate(self.mesh, geom)
1730 def Compute(self, geom=0, discardModifs=False, refresh=False):
1732 Compute the mesh and return the status of the computation
1735 geom: geomtrical shape on which mesh data should be computed
1736 discardModifs: if True and the mesh has been edited since
1737 a last total re-compute and that may prevent successful partial re-compute,
1738 then the mesh is cleaned before Compute()
1739 refresh: if *True*, Object Browser is automatically updated (when running in GUI)
1745 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1747 geom = self.mesh.GetShapeToMesh()
1752 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1754 ok = self.smeshpyD.Compute(self.mesh, geom)
1755 except SALOME.SALOME_Exception as ex:
1756 print("Mesh computation failed, exception caught:")
1757 print(" ", ex.details.text)
1760 print("Mesh computation failed, exception caught:")
1761 traceback.print_exc()
1765 # Treat compute errors
1766 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1768 for err in computeErrors:
1769 if self.mesh.HasShapeToMesh():
1770 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1772 stdErrors = ["OK", #COMPERR_OK
1773 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1774 "std::exception", #COMPERR_STD_EXCEPTION
1775 "OCC exception", #COMPERR_OCC_EXCEPTION
1776 "..", #COMPERR_SLM_EXCEPTION
1777 "Unknown exception", #COMPERR_EXCEPTION
1778 "Memory allocation problem", #COMPERR_MEMORY_PB
1779 "Algorithm failed", #COMPERR_ALGO_FAILED
1780 "Unexpected geometry", #COMPERR_BAD_SHAPE
1781 "Warning", #COMPERR_WARNING
1782 "Computation cancelled",#COMPERR_CANCELED
1783 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1785 if err.code < len(stdErrors): errText = stdErrors[err.code]
1787 errText = "code %s" % -err.code
1788 if errText: errText += ". "
1789 errText += err.comment
1790 if allReasons: allReasons += "\n"
1792 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1794 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1798 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1800 if err.isGlobalAlgo:
1808 reason = '%s %sD algorithm is missing' % (glob, dim)
1809 elif err.state == HYP_MISSING:
1810 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1811 % (glob, dim, name, dim))
1812 elif err.state == HYP_NOTCONFORM:
1813 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1814 elif err.state == HYP_BAD_PARAMETER:
1815 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1816 % ( glob, dim, name ))
1817 elif err.state == HYP_BAD_GEOMETRY:
1818 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1819 'geometry' % ( glob, dim, name ))
1820 elif err.state == HYP_HIDDEN_ALGO:
1821 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1822 'algorithm of upper dimension generating %sD mesh'
1823 % ( glob, dim, name, glob, dim ))
1825 reason = ("For unknown reason. "
1826 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1828 if allReasons: allReasons += "\n"
1829 allReasons += "- " + reason
1831 if not ok or allReasons != "":
1832 msg = '"' + GetName(self.mesh) + '"'
1833 if ok: msg += " has been computed with warnings"
1834 else: msg += " has not been computed"
1835 if allReasons != "": msg += ":"
1840 if salome.sg.hasDesktop():
1841 if not isinstance( refresh, list): # not a call from subMesh.Compute()
1842 if refresh: salome.sg.updateObjBrowser()
1846 def GetComputeErrors(self, shape=0 ):
1848 Return a list of error messages (:class:`SMESH.ComputeError`) of the last :meth:`Compute`
1852 shape = self.mesh.GetShapeToMesh()
1853 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1855 def GetSubShapeName(self, subShapeID ):
1857 Return a name of a sub-shape by its ID.
1858 Possible variants (for *subShapeID* == 3):
1860 - **"Face_12"** - published sub-shape
1861 - **FACE #3** - not published sub-shape
1862 - **sub-shape #3** - invalid sub-shape ID
1863 - **#3** - error in this function
1866 subShapeID: a unique ID of a sub-shape
1869 a string describing the sub-shape
1873 if not self.mesh.HasShapeToMesh():
1877 mainIOR = salome.orb.object_to_string( self.GetShape() )
1879 mainSO = s.FindObjectIOR(mainIOR)
1882 shapeText = '"%s"' % mainSO.GetName()
1883 subIt = s.NewChildIterator(mainSO)
1885 subSO = subIt.Value()
1887 obj = subSO.GetObject()
1888 if not obj: continue
1889 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1892 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1895 if ids == subShapeID:
1896 shapeText = '"%s"' % subSO.GetName()
1899 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1901 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1903 shapeText = 'sub-shape #%s' % (subShapeID)
1905 shapeText = "#%s" % (subShapeID)
1908 def GetFailedShapes(self, publish=False):
1910 Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1911 error of an algorithm
1914 publish: if *True*, the returned groups will be published in the study
1917 a list of GEOM groups each named after a failed algorithm
1922 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1923 for err in computeErrors:
1924 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1925 if not shape: continue
1926 if err.algoName in algo2shapes:
1927 algo2shapes[ err.algoName ].append( shape )
1929 algo2shapes[ err.algoName ] = [ shape ]
1933 for algoName, shapes in list(algo2shapes.items()):
1935 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1936 otherTypeShapes = []
1938 group = self.geompyD.CreateGroup( self.geom, groupType )
1939 for shape in shapes:
1940 if shape.GetShapeType() == shapes[0].GetShapeType():
1941 sameTypeShapes.append( shape )
1943 otherTypeShapes.append( shape )
1944 self.geompyD.UnionList( group, sameTypeShapes )
1946 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1948 group.SetName( algoName )
1949 groups.append( group )
1950 shapes = otherTypeShapes
1953 for group in groups:
1954 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1957 def GetMeshOrder(self):
1959 Return sub-mesh objects list in meshing order
1962 list of lists of :class:`sub-meshes <SMESH.SMESH_subMesh>`
1965 return self.mesh.GetMeshOrder()
1967 def SetMeshOrder(self, submeshes):
1969 Set order in which concurrent sub-meshes should be meshed
1972 submeshes: list of lists of :class:`sub-meshes <SMESH.SMESH_subMesh>`
1975 return self.mesh.SetMeshOrder(submeshes)
1977 def Clear(self, refresh=False):
1979 Remove all nodes and elements generated on geometry. Imported elements remain.
1982 refresh: if *True*, Object browser is automatically updated (when running in GUI)
1986 if ( salome.sg.hasDesktop() ):
1987 if refresh: salome.sg.updateObjBrowser()
1989 def ClearSubMesh(self, geomId, refresh=False):
1991 Remove all nodes and elements of indicated shape
1994 geomId: the ID of a sub-shape to remove elements on
1995 refresh: if *True*, Object browser is automatically updated (when running in GUI)
1998 self.mesh.ClearSubMesh(geomId)
1999 if salome.sg.hasDesktop():
2000 if refresh: salome.sg.updateObjBrowser()
2002 def AutomaticTetrahedralization(self, fineness=0):
2004 Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
2007 fineness: [0.0,1.0] defines mesh fineness
2013 dim = self.MeshDimension()
2015 self.RemoveGlobalHypotheses()
2016 self.Segment().AutomaticLength(fineness)
2018 self.Triangle().LengthFromEdges()
2023 return self.Compute()
2025 def AutomaticHexahedralization(self, fineness=0):
2027 Compute an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
2030 fineness: [0.0, 1.0] defines mesh fineness
2036 dim = self.MeshDimension()
2037 # assign the hypotheses
2038 self.RemoveGlobalHypotheses()
2039 self.Segment().AutomaticLength(fineness)
2046 return self.Compute()
2048 def AddHypothesis(self, hyp, geom=0):
2053 hyp: a hypothesis to assign
2054 geom: a subhape of mesh geometry
2057 :class:`SMESH.Hypothesis_Status`
2060 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
2061 hyp, geom = geom, hyp
2062 if isinstance( hyp, Mesh_Algorithm ):
2063 hyp = hyp.GetAlgorithm()
2068 geom = self.mesh.GetShapeToMesh()
2071 if self.mesh.HasShapeToMesh():
2072 hyp_type = hyp.GetName()
2073 lib_name = hyp.GetLibName()
2074 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
2075 # if checkAll and geom:
2076 # checkAll = geom.GetType() == 37
2078 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
2080 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
2081 status = self.mesh.AddHypothesis(geom, hyp)
2083 status = HYP_BAD_GEOMETRY, ""
2084 hyp_name = GetName( hyp )
2087 geom_name = geom.GetName()
2088 isAlgo = hyp._narrow( SMESH_Algo )
2089 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
2092 def IsUsedHypothesis(self, hyp, geom):
2094 Return True if an algorithm or hypothesis is assigned to a given shape
2097 hyp: an algorithm or hypothesis to check
2098 geom: a subhape of mesh geometry
2104 if not hyp: # or not geom
2106 if isinstance( hyp, Mesh_Algorithm ):
2107 hyp = hyp.GetAlgorithm()
2109 hyps = self.GetHypothesisList(geom)
2111 if h.GetId() == hyp.GetId():
2115 def RemoveHypothesis(self, hyp, geom=0):
2117 Unassign a hypothesis
2120 hyp (SMESH.SMESH_Hypothesis): a hypothesis to unassign
2121 geom (GEOM.GEOM_Object): a sub-shape of mesh geometry
2124 :class:`SMESH.Hypothesis_Status`
2129 if isinstance( hyp, Mesh_Algorithm ):
2130 hyp = hyp.GetAlgorithm()
2136 if self.IsUsedHypothesis( hyp, shape ):
2137 return self.mesh.RemoveHypothesis( shape, hyp )
2138 hypName = GetName( hyp )
2139 geoName = GetName( shape )
2140 print("WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName ))
2143 def GetHypothesisList(self, geom):
2145 Get the list of hypotheses added on a geometry
2148 geom (GEOM.GEOM_Object): a sub-shape of mesh geometry
2151 the sequence of :class:`SMESH.SMESH_Hypothesis`
2154 return self.mesh.GetHypothesisList( geom )
2156 def RemoveGlobalHypotheses(self):
2158 Remove all global hypotheses
2161 current_hyps = self.mesh.GetHypothesisList( self.geom )
2162 for hyp in current_hyps:
2163 self.mesh.RemoveHypothesis( self.geom, hyp )
2166 def ExportMED(self, *args, **kwargs):
2168 Export the mesh in a file in MED format
2169 allowing to overwrite the file if it exists or add the exported data to its contents
2172 fileName: is the file name
2173 auto_groups (boolean): parameter for creating/not creating
2174 the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
2175 the typical use is auto_groups=False.
2176 minor (int): define the minor version (y, where version is x.y.z) of MED file format.
2177 The minor must be between 0 and the current minor version of MED file library.
2178 If minor is equal to -1, the minor version is not changed (default).
2179 The major version (x, where version is x.y.z) cannot be changed.
2180 overwrite (boolean): parameter for overwriting/not overwriting the file
2181 meshPart: a part of mesh (:class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>`) to export instead of the mesh
2182 autoDimension: if *True* (default), a space dimension of a MED mesh can be either
2184 - 1D if all mesh nodes lie on OX coordinate axis, or
2185 - 2D if all mesh nodes lie on XOY coordinate plane, or
2186 - 3D in the rest cases.
2188 If *autoDimension* is *False*, the space dimension is always 3.
2189 fields: list of GEOM fields defined on the shape to mesh.
2190 geomAssocFields: each character of this string means a need to export a
2191 corresponding field; correspondence between fields and characters is following:
2193 - 'v' stands for "_vertices_" field;
2194 - 'e' stands for "_edges_" field;
2195 - 'f' stands for "_faces_" field;
2196 - 's' stands for "_solids_" field.
2198 # process positional arguments
2199 #args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
2201 auto_groups = args[1] if len(args) > 1 else False
2202 minor = args[2] if len(args) > 2 else -1
2203 overwrite = args[3] if len(args) > 3 else True
2204 meshPart = args[4] if len(args) > 4 else None
2205 autoDimension = args[5] if len(args) > 5 else True
2206 fields = args[6] if len(args) > 6 else []
2207 geomAssocFields = args[7] if len(args) > 7 else ''
2208 # process keywords arguments
2209 auto_groups = kwargs.get("auto_groups", auto_groups)
2210 minor = kwargs.get("minor", minor)
2211 overwrite = kwargs.get("overwrite", overwrite)
2212 meshPart = kwargs.get("meshPart", meshPart)
2213 autoDimension = kwargs.get("autoDimension", autoDimension)
2214 fields = kwargs.get("fields", fields)
2215 geomAssocFields = kwargs.get("geomAssocFields", geomAssocFields)
2216 # invoke engine's function
2217 if meshPart or fields or geomAssocFields:
2218 unRegister = genObjUnRegister()
2219 if isinstance( meshPart, list ):
2220 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2221 unRegister.set( meshPart )
2222 self.mesh.ExportPartToMED( meshPart, fileName, auto_groups, minor, overwrite, autoDimension,
2223 fields, geomAssocFields)
2225 self.mesh.ExportMED(fileName, auto_groups, minor, overwrite, autoDimension)
2227 def ExportSAUV(self, f, auto_groups=0):
2229 Export the mesh in a file in SAUV format
2234 auto_groups: boolean parameter for creating/not creating
2235 the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
2236 the typical use is auto_groups=False.
2239 self.mesh.ExportSAUV(f, auto_groups)
2241 def ExportDAT(self, f, meshPart=None):
2243 Export the mesh in a file in DAT format
2247 meshPart: a part of mesh (:class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>`) to export instead of the mesh
2251 unRegister = genObjUnRegister()
2252 if isinstance( meshPart, list ):
2253 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2254 unRegister.set( meshPart )
2255 self.mesh.ExportPartToDAT( meshPart, f )
2257 self.mesh.ExportDAT(f)
2259 def ExportUNV(self, f, meshPart=None):
2261 Export the mesh in a file in UNV format
2265 meshPart: a part of mesh (:class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>`) to export instead of the mesh
2269 unRegister = genObjUnRegister()
2270 if isinstance( meshPart, list ):
2271 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2272 unRegister.set( meshPart )
2273 self.mesh.ExportPartToUNV( meshPart, f )
2275 self.mesh.ExportUNV(f)
2277 def ExportSTL(self, f, ascii=1, meshPart=None):
2279 Export the mesh in a file in STL format
2283 ascii: defines the file encoding
2284 meshPart: a part of mesh (:class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>`) to export instead of the mesh
2288 unRegister = genObjUnRegister()
2289 if isinstance( meshPart, list ):
2290 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2291 unRegister.set( meshPart )
2292 self.mesh.ExportPartToSTL( meshPart, f, ascii )
2294 self.mesh.ExportSTL(f, ascii)
2296 def ExportCGNS(self, f, overwrite=1, meshPart=None, groupElemsByType=False):
2298 Export the mesh in a file in CGNS format
2302 overwrite: boolean parameter for overwriting/not overwriting the file
2303 meshPart: a part of mesh (:class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>`) to export instead of the mesh
2304 groupElemsByType: if True all elements of same entity type are exported at ones,
2305 else elements are exported in order of their IDs which can cause creation
2306 of multiple cgns sections
2309 unRegister = genObjUnRegister()
2310 if isinstance( meshPart, list ):
2311 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2312 unRegister.set( meshPart )
2313 if isinstance( meshPart, Mesh ):
2314 meshPart = meshPart.mesh
2316 meshPart = self.mesh
2317 self.mesh.ExportCGNS(meshPart, f, overwrite, groupElemsByType)
2319 def ExportGMF(self, f, meshPart=None):
2321 Export the mesh in a file in GMF format.
2322 GMF files must have .mesh extension for the ASCII format and .meshb for
2323 the bynary format. Other extensions are not allowed.
2327 meshPart: a part of mesh (:class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>`) to export instead of the mesh
2330 unRegister = genObjUnRegister()
2331 if isinstance( meshPart, list ):
2332 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2333 unRegister.set( meshPart )
2334 if isinstance( meshPart, Mesh ):
2335 meshPart = meshPart.mesh
2337 meshPart = self.mesh
2338 self.mesh.ExportGMF(meshPart, f, True)
2340 def ExportToMED(self, *args, **kwargs):
2342 Deprecated, used only for compatibility! Please, use :meth:`ExportMED` method instead.
2343 Export the mesh in a file in MED format
2344 allowing to overwrite the file if it exists or add the exported data to its contents
2347 fileName: the file name
2348 opt (boolean): parameter for creating/not creating
2349 the groups Group_On_All_Nodes, Group_On_All_Faces, ...
2350 overwrite: boolean parameter for overwriting/not overwriting the file
2351 autoDimension: if *True* (default), a space dimension of a MED mesh can be either
2353 - 1D if all mesh nodes lie on OX coordinate axis, or
2354 - 2D if all mesh nodes lie on XOY coordinate plane, or
2355 - 3D in the rest cases.
2357 If **autoDimension** is *False*, the space dimension is always 3.
2360 print("WARNING: ExportToMED() is deprecated, use ExportMED() instead")
2361 # process positional arguments
2362 #args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
2364 auto_groups = args[1] if len(args) > 1 else False
2365 overwrite = args[2] if len(args) > 2 else True
2366 autoDimension = args[3] if len(args) > 3 else True
2367 # process keywords arguments
2368 auto_groups = kwargs.get("opt", auto_groups) # old keyword name
2369 auto_groups = kwargs.get("auto_groups", auto_groups) # new keyword name
2370 overwrite = kwargs.get("overwrite", overwrite)
2371 autoDimension = kwargs.get("autoDimension", autoDimension)
2373 # invoke engine's function
2374 self.mesh.ExportMED(fileName, auto_groups, minor, overwrite, autoDimension)
2376 def ExportToMEDX(self, *args, **kwargs):
2378 Deprecated, used only for compatibility! Please, use ExportMED() method instead.
2379 Export the mesh in a file in MED format
2382 fileName: the file name
2383 opt (boolean): parameter for creating/not creating
2384 the groups Group_On_All_Nodes, Group_On_All_Faces, ...
2385 overwrite: boolean parameter for overwriting/not overwriting the file
2386 autoDimension: if *True* (default), a space dimension of a MED mesh can be either
2388 - 1D if all mesh nodes lie on OX coordinate axis, or
2389 - 2D if all mesh nodes lie on XOY coordinate plane, or
2390 - 3D in the rest cases.
2392 If **autoDimension** is *False*, the space dimension is always 3.
2395 print("WARNING: ExportToMEDX() is deprecated, use ExportMED() instead")
2396 # process positional arguments
2397 #args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
2399 auto_groups = args[1] if len(args) > 1 else False
2400 overwrite = args[2] if len(args) > 2 else True
2401 autoDimension = args[3] if len(args) > 3 else True
2402 # process keywords arguments
2403 auto_groups = kwargs.get("auto_groups", auto_groups)
2404 overwrite = kwargs.get("overwrite", overwrite)
2405 autoDimension = kwargs.get("autoDimension", autoDimension)
2407 # invoke engine's function
2408 self.mesh.ExportMED(fileName, auto_groups, minor, overwrite, autoDimension)
2410 # Operations with groups:
2411 # ----------------------
2412 def CreateEmptyGroup(self, elementType, name):
2414 Create an empty standalone mesh group
2417 elementType: the :class:`type <SMESH.ElementType>` of elements in the group;
2418 either of (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2419 name: the name of the mesh group
2422 :class:`SMESH.SMESH_Group`
2425 return self.mesh.CreateGroup(elementType, name)
2427 def Group(self, grp, name=""):
2429 Create a mesh group based on the geometric object *grp*
2430 and give it a *name*.
2431 If *name* is not defined the name of the geometric group is used
2434 Works like :meth:`GroupOnGeom`.
2437 grp: a geometric group, a vertex, an edge, a face or a solid
2438 name: the name of the mesh group
2441 :class:`SMESH.SMESH_GroupOnGeom`
2444 return self.GroupOnGeom(grp, name)
2446 def GroupOnGeom(self, grp, name="", typ=None):
2448 Create a mesh group based on the geometrical object *grp*
2449 and give it a *name*.
2450 if *name* is not defined the name of the geometric group is used
2453 grp: a geometrical group, a vertex, an edge, a face or a solid
2454 name: the name of the mesh group
2455 typ: the type of elements in the group; either of
2456 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
2457 automatically detected by the type of the geometry
2460 :class:`SMESH.SMESH_GroupOnGeom`
2463 AssureGeomPublished( self, grp, name )
2465 name = grp.GetName()
2467 typ = self._groupTypeFromShape( grp )
2468 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
2470 def _groupTypeFromShape( self, shape ):
2472 Pivate method to get a type of group on geometry
2474 tgeo = str(shape.GetShapeType())
2475 if tgeo == "VERTEX":
2477 elif tgeo == "EDGE":
2479 elif tgeo == "FACE" or tgeo == "SHELL":
2481 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
2483 elif tgeo == "COMPOUND":
2484 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
2486 raise ValueError("_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape))
2487 return self._groupTypeFromShape( sub[0] )
2489 raise ValueError("_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape))
2492 def GroupOnFilter(self, typ, name, filter):
2494 Create a mesh group with given *name* based on the *filter*.
2495 It is a special type of group dynamically updating it's contents during
2499 typ: the type of elements in the group; either of
2500 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2501 name: the name of the mesh group
2502 filter (SMESH.Filter): the filter defining group contents
2505 :class:`SMESH.SMESH_GroupOnFilter`
2508 return self.mesh.CreateGroupFromFilter(typ, name, filter)
2510 def MakeGroupByIds(self, groupName, elementType, elemIDs):
2512 Create a mesh group by the given ids of elements
2515 groupName: the name of the mesh group
2516 elementType: the type of elements in the group; either of
2517 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2518 elemIDs: either the list of ids, :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
2521 :class:`SMESH.SMESH_Group`
2524 group = self.mesh.CreateGroup(elementType, groupName)
2525 if isinstance( elemIDs, Mesh ):
2526 elemIDs = elemIDs.GetMesh()
2527 if hasattr( elemIDs, "GetIDs" ):
2528 if hasattr( elemIDs, "SetMesh" ):
2529 elemIDs.SetMesh( self.GetMesh() )
2530 group.AddFrom( elemIDs )
2538 CritType=FT_Undefined,
2541 UnaryOp=FT_Undefined,
2544 Create a mesh group by the given conditions
2547 groupName: the name of the mesh group
2548 elementType (SMESH.ElementType): the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2549 CritType (SMESH.FunctorType): the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.).
2550 Note that the items starting from FT_LessThan are not suitable for CritType.
2551 Compare (SMESH.FunctorType): belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
2552 Threshold: the threshold value (range of ids as string, shape, numeric, depending on *CritType*)
2553 UnaryOp (SMESH.FunctorType): SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2554 Tolerance (float): the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2555 SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2558 :class:`SMESH.SMESH_GroupOnFilter`
2561 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2562 group = self.MakeGroupByCriterion(groupName, aCriterion)
2565 def MakeGroupByCriterion(self, groupName, Criterion):
2567 Create a mesh group by the given criterion
2570 groupName: the name of the mesh group
2571 Criterion: the instance of :class:`SMESH.Filter.Criterion` class
2574 :class:`SMESH.SMESH_GroupOnFilter`
2577 :meth:`smeshBuilder.GetCriterion`
2580 return self.MakeGroupByCriteria( groupName, [Criterion] )
2582 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2584 Create a mesh group by the given criteria (list of :class:`SMESH.Filter.Criterion`)
2587 groupName: the name of the mesh group
2588 theCriteria: the list of :class:`SMESH.Filter.Criterion`
2589 binOp: binary operator (SMESH.FT_LogicalAND or SMESH.FT_LogicalOR ) used when binary operator of criteria is undefined
2592 :class:`SMESH.SMESH_GroupOnFilter`
2595 :meth:`smeshBuilder.GetCriterion`
2598 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2599 group = self.MakeGroupByFilter(groupName, aFilter)
2602 def MakeGroupByFilter(self, groupName, theFilter):
2604 Create a mesh group by the given filter
2607 groupName (string): the name of the mesh group
2608 theFilter (SMESH.Filter): the filter
2611 :class:`SMESH.SMESH_GroupOnFilter`
2614 :meth:`smeshBuilder.GetFilter`
2617 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2618 #theFilter.SetMesh( self.mesh )
2619 #group.AddFrom( theFilter )
2620 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2623 def RemoveGroup(self, group):
2628 group (SMESH.SMESH_GroupBase): group to remove
2631 self.mesh.RemoveGroup(group)
2633 def RemoveGroupWithContents(self, group):
2635 Remove a group with its contents
2638 group (SMESH.SMESH_GroupBase): group to remove
2641 self.mesh.RemoveGroupWithContents(group)
2643 def GetGroups(self, elemType = SMESH.ALL):
2645 Get the list of groups existing in the mesh in the order of creation
2646 (starting from the oldest one)
2649 elemType (SMESH.ElementType): type of elements the groups contain;
2650 by default groups of elements of all types are returned
2653 a list of :class:`SMESH.SMESH_GroupBase`
2656 groups = self.mesh.GetGroups()
2657 if elemType == SMESH.ALL:
2661 if g.GetType() == elemType:
2662 typedGroups.append( g )
2669 Get the number of groups existing in the mesh
2672 the quantity of groups as an integer value
2675 return self.mesh.NbGroups()
2677 def GetGroupNames(self):
2679 Get the list of names of groups existing in the mesh
2685 groups = self.GetGroups()
2687 for group in groups:
2688 names.append(group.GetName())
2691 def GetGroupByName(self, name, elemType = None):
2693 Find groups by name and type
2696 name (string): name of the group of interest
2697 elemType (SMESH.ElementType): type of elements the groups contain;
2698 by default one group of any type is returned;
2699 if elemType == SMESH.ALL then all groups of any type are returned
2702 a list of :class:`SMESH.SMESH_GroupBase`
2706 for group in self.GetGroups():
2707 if group.GetName() == name:
2708 if elemType is None:
2710 if ( elemType == SMESH.ALL or
2711 group.GetType() == elemType ):
2712 groups.append( group )
2715 def UnionGroups(self, group1, group2, name):
2717 Produce a union of two groups.
2718 A new group is created. All mesh elements that are
2719 present in the initial groups are added to the new one
2722 group1 (SMESH.SMESH_GroupBase): a group
2723 group2 (SMESH.SMESH_GroupBase): another group
2726 instance of :class:`SMESH.SMESH_Group`
2729 return self.mesh.UnionGroups(group1, group2, name)
2731 def UnionListOfGroups(self, groups, name):
2733 Produce a union list of groups.
2734 New group is created. All mesh elements that are present in
2735 initial groups are added to the new one
2738 groups: list of :class:`SMESH.SMESH_GroupBase`
2741 instance of :class:`SMESH.SMESH_Group`
2743 return self.mesh.UnionListOfGroups(groups, name)
2745 def IntersectGroups(self, group1, group2, name):
2747 Prodice an intersection of two groups.
2748 A new group is created. All mesh elements that are common
2749 for the two initial groups are added to the new one.
2752 group1 (SMESH.SMESH_GroupBase): a group
2753 group2 (SMESH.SMESH_GroupBase): another group
2756 instance of :class:`SMESH.SMESH_Group`
2759 return self.mesh.IntersectGroups(group1, group2, name)
2761 def IntersectListOfGroups(self, groups, name):
2763 Produce an intersection of groups.
2764 New group is created. All mesh elements that are present in all
2765 initial groups simultaneously are added to the new one
2768 groups: a list of :class:`SMESH.SMESH_GroupBase`
2771 instance of :class:`SMESH.SMESH_Group`
2773 return self.mesh.IntersectListOfGroups(groups, name)
2775 def CutGroups(self, main_group, tool_group, name):
2777 Produce a cut of two groups.
2778 A new group is created. All mesh elements that are present in
2779 the main group but are not present in the tool group are added to the new one
2782 main_group (SMESH.SMESH_GroupBase): a group to cut from
2783 tool_group (SMESH.SMESH_GroupBase): a group to cut by
2786 an instance of :class:`SMESH.SMESH_Group`
2789 return self.mesh.CutGroups(main_group, tool_group, name)
2791 def CutListOfGroups(self, main_groups, tool_groups, name):
2793 Produce a cut of groups.
2794 A new group is created. All mesh elements that are present in main groups
2795 but do not present in tool groups are added to the new one
2798 main_group: groups to cut from (list of :class:`SMESH.SMESH_GroupBase`)
2799 tool_group: groups to cut by (list of :class:`SMESH.SMESH_GroupBase`)
2802 an instance of :class:`SMESH.SMESH_Group`
2805 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2807 def CreateDimGroup(self, groups, elemType, name,
2808 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2810 Create a standalone group of entities basing on nodes of other groups.
2813 groups: list of reference :class:`sub-meshes, groups or filters <SMESH.SMESH_IDSource>`, of any type.
2814 elemType: a type of elements to include to the new group; either of
2815 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2816 name: a name of the new group.
2817 nbCommonNodes: a criterion of inclusion of an element to the new group
2818 basing on number of element nodes common with reference *groups*.
2819 Meaning of possible values are:
2821 - SMESH.ALL_NODES - include if all nodes are common,
2822 - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2823 - SMESH.AT_LEAST_ONE - include if one or more node is common,
2824 - SMEHS.MAJORITY - include if half of nodes or more are common.
2825 underlyingOnly: if *True* (default), an element is included to the
2826 new group provided that it is based on nodes of an element of *groups*;
2827 in this case the reference *groups* are supposed to be of higher dimension
2828 than *elemType*, which can be useful for example to get all faces lying on
2829 volumes of the reference *groups*.
2832 an instance of :class:`SMESH.SMESH_Group`
2835 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2837 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2840 def ConvertToStandalone(self, group):
2842 Convert group on geom into standalone group
2845 return self.mesh.ConvertToStandalone(group)
2847 # Get some info about mesh:
2848 # ------------------------
2850 def GetLog(self, clearAfterGet):
2852 Return the log of nodes and elements added or removed
2853 since the previous clear of the log.
2856 clearAfterGet: log is emptied after Get (safe if concurrents access)
2859 list of SMESH.log_block structures { commandType, number, coords, indexes }
2862 return self.mesh.GetLog(clearAfterGet)
2866 Clear the log of nodes and elements added or removed since the previous
2867 clear. Must be used immediately after :meth:`GetLog` if clearAfterGet is false.
2870 self.mesh.ClearLog()
2872 def SetAutoColor(self, theAutoColor):
2874 Toggle auto color mode on the object.
2875 If switched on, a default color of a new group in Create Group dialog is chosen randomly.
2878 theAutoColor (boolean): the flag which toggles auto color mode.
2881 self.mesh.SetAutoColor(theAutoColor)
2883 def GetAutoColor(self):
2885 Get flag of object auto color mode.
2891 return self.mesh.GetAutoColor()
2898 integer value, which is the internal Id of the mesh
2901 return self.mesh.GetId()
2903 def HasDuplicatedGroupNamesMED(self):
2905 Check the group names for duplications.
2906 Consider the maximum group name length stored in MED file.
2912 return self.mesh.HasDuplicatedGroupNamesMED()
2914 def GetMeshEditor(self):
2916 Obtain the mesh editor tool
2919 an instance of :class:`SMESH.SMESH_MeshEditor`
2924 def GetIDSource(self, ids, elemType = SMESH.ALL):
2926 Wrap a list of IDs of elements or nodes into :class:`SMESH.SMESH_IDSource` which
2927 can be passed as argument to a method accepting :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
2931 elemType: type of elements; this parameter is used to distinguish
2932 IDs of nodes from IDs of elements; by default ids are treated as
2933 IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2936 an instance of :class:`SMESH.SMESH_IDSource`
2939 call UnRegister() for the returned object as soon as it is no more useful::
2941 idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2942 mesh.DoSomething( idSrc )
2946 if isinstance( ids, int ):
2948 return self.editor.MakeIDSource(ids, elemType)
2951 # Get information about mesh contents:
2952 # ------------------------------------
2954 def GetMeshInfo(self, obj = None):
2956 Get the mesh statistic.
2957 Use :meth:`smeshBuilder.EnumToLong` to get an integer from
2958 an item of :class:`SMESH.EntityType`.
2961 dictionary { :class:`SMESH.EntityType` - "count of elements" }
2964 if not obj: obj = self.mesh
2965 return self.smeshpyD.GetMeshInfo(obj)
2969 Return the number of nodes in the mesh
2975 return self.mesh.NbNodes()
2977 def NbElements(self):
2979 Return the number of elements in the mesh
2985 return self.mesh.NbElements()
2987 def Nb0DElements(self):
2989 Return the number of 0d elements in the mesh
2995 return self.mesh.Nb0DElements()
2999 Return the number of ball discrete elements in the mesh
3005 return self.mesh.NbBalls()
3009 Return the number of edges in the mesh
3015 return self.mesh.NbEdges()
3017 def NbEdgesOfOrder(self, elementOrder):
3019 Return the number of edges with the given order in the mesh
3022 elementOrder: the order of elements
3023 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3029 return self.mesh.NbEdgesOfOrder(elementOrder)
3033 Return the number of faces in the mesh
3039 return self.mesh.NbFaces()
3041 def NbFacesOfOrder(self, elementOrder):
3043 Return the number of faces with the given order in the mesh
3046 elementOrder: the order of elements
3047 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3053 return self.mesh.NbFacesOfOrder(elementOrder)
3055 def NbTriangles(self):
3057 Return the number of triangles in the mesh
3063 return self.mesh.NbTriangles()
3065 def NbTrianglesOfOrder(self, elementOrder):
3067 Return the number of triangles with the given order in the mesh
3070 elementOrder: is the order of elements
3071 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3077 return self.mesh.NbTrianglesOfOrder(elementOrder)
3079 def NbBiQuadTriangles(self):
3081 Return the number of biquadratic triangles in the mesh
3087 return self.mesh.NbBiQuadTriangles()
3089 def NbQuadrangles(self):
3091 Return the number of quadrangles in the mesh
3097 return self.mesh.NbQuadrangles()
3099 def NbQuadranglesOfOrder(self, elementOrder):
3101 Return the number of quadrangles with the given order in the mesh
3104 elementOrder: the order of elements
3105 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3111 return self.mesh.NbQuadranglesOfOrder(elementOrder)
3113 def NbBiQuadQuadrangles(self):
3115 Return the number of biquadratic quadrangles in the mesh
3121 return self.mesh.NbBiQuadQuadrangles()
3123 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
3125 Return the number of polygons of given order in the mesh
3128 elementOrder: the order of elements
3129 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3135 return self.mesh.NbPolygonsOfOrder(elementOrder)
3137 def NbVolumes(self):
3139 Return the number of volumes in the mesh
3145 return self.mesh.NbVolumes()
3148 def NbVolumesOfOrder(self, elementOrder):
3150 Return the number of volumes with the given order in the mesh
3153 elementOrder: the order of elements
3154 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3160 return self.mesh.NbVolumesOfOrder(elementOrder)
3164 Return the number of tetrahedrons in the mesh
3170 return self.mesh.NbTetras()
3172 def NbTetrasOfOrder(self, elementOrder):
3174 Return the number of tetrahedrons with the given order in the mesh
3177 elementOrder: the order of elements
3178 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3184 return self.mesh.NbTetrasOfOrder(elementOrder)
3188 Return the number of hexahedrons in the mesh
3194 return self.mesh.NbHexas()
3196 def NbHexasOfOrder(self, elementOrder):
3198 Return the number of hexahedrons with the given order in the mesh
3201 elementOrder: the order of elements
3202 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3208 return self.mesh.NbHexasOfOrder(elementOrder)
3210 def NbTriQuadraticHexas(self):
3212 Return the number of triquadratic hexahedrons in the mesh
3218 return self.mesh.NbTriQuadraticHexas()
3220 def NbPyramids(self):
3222 Return the number of pyramids in the mesh
3228 return self.mesh.NbPyramids()
3230 def NbPyramidsOfOrder(self, elementOrder):
3232 Return the number of pyramids with the given order in the mesh
3235 elementOrder: the order of elements
3236 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3242 return self.mesh.NbPyramidsOfOrder(elementOrder)
3246 Return the number of prisms in the mesh
3252 return self.mesh.NbPrisms()
3254 def NbPrismsOfOrder(self, elementOrder):
3256 Return the number of prisms with the given order in the mesh
3259 elementOrder: the order of elements
3260 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3266 return self.mesh.NbPrismsOfOrder(elementOrder)
3268 def NbHexagonalPrisms(self):
3270 Return the number of hexagonal prisms in the mesh
3276 return self.mesh.NbHexagonalPrisms()
3278 def NbPolyhedrons(self):
3280 Return the number of polyhedrons in the mesh
3286 return self.mesh.NbPolyhedrons()
3288 def NbSubMesh(self):
3290 Return the number of submeshes in the mesh
3296 return self.mesh.NbSubMesh()
3298 def GetElementsId(self):
3300 Return the list of all mesh elements IDs
3303 the list of integer values
3306 :meth:`GetElementsByType`
3309 return self.mesh.GetElementsId()
3311 def GetElementsByType(self, elementType):
3313 Return the list of IDs of mesh elements with the given type
3316 elementType (SMESH.ElementType): the required type of elements
3319 list of integer values
3322 return self.mesh.GetElementsByType(elementType)
3324 def GetNodesId(self):
3326 Return the list of mesh nodes IDs
3329 the list of integer values
3332 return self.mesh.GetNodesId()
3334 # Get the information about mesh elements:
3335 # ------------------------------------
3337 def GetElementType(self, id, iselem=True):
3339 Return the type of mesh element or node
3342 the value from :class:`SMESH.ElementType` enumeration.
3343 Return SMESH.ALL if element or node with the given ID does not exist
3346 return self.mesh.GetElementType(id, iselem)
3348 def GetElementGeomType(self, id):
3350 Return the geometric type of mesh element
3353 the value from :class:`SMESH.EntityType` enumeration.
3356 return self.mesh.GetElementGeomType(id)
3358 def GetElementShape(self, id):
3360 Return the shape type of mesh element
3363 the value from :class:`SMESH.GeometryType` enumeration.
3366 return self.mesh.GetElementShape(id)
3368 def GetSubMeshElementsId(self, Shape):