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 mesh.smeshpyD.IsEnablePublish():
308 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
310 if not geom.GetStudyEntry():
312 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
313 # for all groups SubShapeName() return "Compound_-1"
314 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
316 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
318 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
321 def FirstVertexOnCurve(mesh, edge):
324 the first vertex of a geometrical edge by ignoring orientation
326 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
328 raise TypeError("Given object has no vertices")
329 if len( vv ) == 1: return vv[0]
330 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
331 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
332 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
333 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
336 dist1 += abs( xyz[i] - xyz1[i] )
337 dist2 += abs( xyz[i] - xyz2[i] )
346 smeshInst is a singleton
352 class smeshBuilder( SMESH._objref_SMESH_Gen, object ):
354 This class allows to create, load or manipulate meshes.
355 It has a set of methods to create, load or copy meshes, to combine several meshes, etc.
356 It also has methods to get infos and measure meshes.
359 # MirrorType enumeration
360 POINT = SMESH_MeshEditor.POINT
361 AXIS = SMESH_MeshEditor.AXIS
362 PLANE = SMESH_MeshEditor.PLANE
364 # Smooth_Method enumeration
365 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
366 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
368 PrecisionConfusion = smeshPrecisionConfusion
370 # TopAbs_State enumeration
371 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = list(range(4))
373 # Methods of splitting a hexahedron into tetrahedra
374 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
376 def __new__(cls, *args):
380 #print("==== __new__", engine, smeshInst, doLcc)
382 if smeshInst is None:
383 # smesh engine is either retrieved from engine, or created
385 # Following test avoids a recursive loop
387 if smeshInst is not None:
388 # smesh engine not created: existing engine found
392 # FindOrLoadComponent called:
393 # 1. CORBA resolution of server
394 # 2. the __new__ method is called again
395 #print("==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc)
396 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
398 # FindOrLoadComponent not called
399 if smeshInst is None:
400 # smeshBuilder instance is created from lcc.FindOrLoadComponent
401 #print("==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc)
402 smeshInst = super(smeshBuilder,cls).__new__(cls)
404 # smesh engine not created: existing engine found
405 #print("==== existing ", engine, smeshInst, doLcc)
407 #print("====1 ", smeshInst)
410 #print("====2 ", smeshInst)
413 def __init__(self, *args):
415 #print("--------------- smeshbuilder __init__ ---", created)
418 SMESH._objref_SMESH_Gen.__init__(self, *args)
421 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
423 Dump component to the Python script.
424 This method overrides IDL function to allow default values for the parameters.
427 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
429 def SetDumpPythonHistorical(self, isHistorical):
431 Set mode of DumpPython(), *historical* or *snapshot*.
432 In the *historical* mode, the Python Dump script includes all commands
433 performed by SMESH engine. In the *snapshot* mode, commands
434 relating to objects removed from the Study are excluded from the script
435 as well as commands not influencing the current state of meshes
438 if isHistorical: val = "true"
440 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
442 def init_smesh(self,geompyD = None):
444 Set Geometry component
447 self.UpdateStudy(geompyD)
448 notebook.myStudy = salome.myStudy
450 def Mesh(self, obj=0, name=0):
452 Create a mesh. This mesh can be either
454 * an empty mesh not bound to geometry, if *obj* == 0
455 * an empty mesh bound to geometry, if *obj* is GEOM.GEOM_Object
456 * a mesh wrapping a :class:`CORBA mesh <SMESH.SMESH_Mesh>` given as *obj* parameter.
461 1. a :class:`CORBA mesh <SMESH.SMESH_Mesh>` got by calling e.g.
464 salome.myStudy.FindObjectID("0:1:2:3").GetObject()
466 2. a geometrical object for meshing
468 name: the name for the new mesh.
471 an instance of class :class:`Mesh`.
474 if isinstance(obj,str):
476 return Mesh(self, self.geompyD, obj, name)
478 def EnumToLong(self,theItem):
480 Return a long value from enumeration
485 def ColorToString(self,c):
487 Convert SALOMEDS.Color to string.
488 To be used with filters.
491 c: color value (SALOMEDS.Color)
494 a string representation of the color.
498 if isinstance(c, SALOMEDS.Color):
499 val = "%s;%s;%s" % (c.R, c.G, c.B)
500 elif isinstance(c, str):
503 raise ValueError("Color value should be of string or SALOMEDS.Color type")
506 def GetPointStruct(self,theVertex):
508 Get :class:`SMESH.PointStruct` from vertex
511 theVertex (GEOM.GEOM_Object): vertex
514 :class:`SMESH.PointStruct`
517 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
518 return PointStruct(x,y,z)
520 def GetDirStruct(self,theVector):
522 Get :class:`SMESH.DirStruct` from vector
525 theVector (GEOM.GEOM_Object): vector
528 :class:`SMESH.DirStruct`
531 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
532 if(len(vertices) != 2):
533 print("Error: vector object is incorrect.")
535 p1 = self.geompyD.PointCoordinates(vertices[0])
536 p2 = self.geompyD.PointCoordinates(vertices[1])
537 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
538 dirst = DirStruct(pnt)
541 def MakeDirStruct(self,x,y,z):
543 Make :class:`SMESH.DirStruct` from a triplet of floats
546 x,y,z (float): vector components
549 :class:`SMESH.DirStruct`
552 pnt = PointStruct(x,y,z)
553 return DirStruct(pnt)
555 def GetAxisStruct(self,theObj):
557 Get :class:`SMESH.AxisStruct` from a geometrical object
560 theObj (GEOM.GEOM_Object): line or plane
563 :class:`SMESH.AxisStruct`
566 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
569 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
570 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
571 vertex1 = self.geompyD.PointCoordinates(vertex1)
572 vertex2 = self.geompyD.PointCoordinates(vertex2)
573 vertex3 = self.geompyD.PointCoordinates(vertex3)
574 vertex4 = self.geompyD.PointCoordinates(vertex4)
575 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
576 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
577 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] ]
578 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
579 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
580 elif len(edges) == 1:
581 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
582 p1 = self.geompyD.PointCoordinates( vertex1 )
583 p2 = self.geompyD.PointCoordinates( vertex2 )
584 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
585 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
586 elif theObj.GetShapeType() == GEOM.VERTEX:
587 x,y,z = self.geompyD.PointCoordinates( theObj )
588 axis = AxisStruct( x,y,z, 1,0,0,)
589 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
592 # From SMESH_Gen interface:
593 # ------------------------
595 def SetName(self, obj, name):
597 Set the given name to an object
600 obj: the object to rename
601 name: a new object name
604 if isinstance( obj, Mesh ):
606 elif isinstance( obj, Mesh_Algorithm ):
607 obj = obj.GetAlgorithm()
608 ior = salome.orb.object_to_string(obj)
609 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
611 def SetEmbeddedMode( self,theMode ):
616 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
618 def IsEmbeddedMode(self):
623 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
625 def UpdateStudy( self, geompyD = None ):
627 Update the current study. Calling UpdateStudy() allows to
628 update meshes at switching GEOM->SMESH
632 from salome.geom import geomBuilder
633 geompyD = geomBuilder.geom
635 geompyD = geomBuilder.New()
638 self.SetGeomEngine(geompyD)
639 SMESH._objref_SMESH_Gen.UpdateStudy(self)
640 sb = salome.myStudy.NewBuilder()
641 sc = salome.myStudy.FindComponent("SMESH")
643 sb.LoadWith(sc, self)
646 def SetEnablePublish( self, theIsEnablePublish ):
648 Set enable publishing in the study. Calling SetEnablePublish( False ) allows to
649 switch **off** publishing in the Study of mesh objects.
651 #self.SetEnablePublish(theIsEnablePublish)
652 SMESH._objref_SMESH_Gen.SetEnablePublish(self,theIsEnablePublish)
654 notebook = salome_notebook.NoteBook( theIsEnablePublish )
657 def CreateMeshesFromUNV( self,theFileName ):
659 Create a Mesh object importing data from the given UNV file
662 an instance of class :class:`Mesh`
665 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
666 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
669 def CreateMeshesFromMED( self,theFileName ):
671 Create a Mesh object(s) importing data from the given MED file
674 a tuple ( list of class :class:`Mesh` instances,
675 :class:`SMESH.DriverMED_ReadStatus` )
678 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
679 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
680 return aMeshes, aStatus
682 def CreateMeshesFromSAUV( self,theFileName ):
684 Create a Mesh object(s) importing data from the given SAUV file
687 a tuple ( list of class :class:`Mesh` instances, :class:`SMESH.DriverMED_ReadStatus` )
690 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
691 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
692 return aMeshes, aStatus
694 def CreateMeshesFromSTL( self, theFileName ):
696 Create a Mesh object importing data from the given STL file
699 an instance of class :class:`Mesh`
702 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
703 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
706 def CreateMeshesFromCGNS( self, theFileName ):
708 Create Mesh objects importing data from the given CGNS file
711 a tuple ( list of class :class:`Mesh` instances, :class:`SMESH.DriverMED_ReadStatus` )
714 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
715 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
716 return aMeshes, aStatus
718 def CreateMeshesFromGMF( self, theFileName ):
720 Create a Mesh object importing data from the given GMF file.
721 GMF files must have .mesh extension for the ASCII format and .meshb for
725 ( an instance of class :class:`Mesh`, :class:`SMESH.ComputeError` )
728 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
731 if error.comment: print("*** CreateMeshesFromGMF() errors:\n", error.comment)
732 return Mesh(self, self.geompyD, aSmeshMesh), error
734 def Concatenate( self, meshes, uniteIdenticalGroups,
735 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
738 Concatenate the given meshes into one mesh. All groups of input meshes will be
739 present in the new mesh.
742 meshes: :class:`meshes, sub-meshes, groups or filters <SMESH.SMESH_IDSource>` to combine into one mesh
743 uniteIdenticalGroups: if True, groups with same names are united, else they are renamed
744 mergeNodesAndElements: if True, equal nodes and elements are merged
745 mergeTolerance: tolerance for merging nodes
746 allGroups: forces creation of groups corresponding to every input mesh
747 name: name of a new mesh
750 an instance of class :class:`Mesh`
753 if not meshes: return None
754 for i,m in enumerate(meshes):
755 if isinstance(m, Mesh):
756 meshes[i] = m.GetMesh()
757 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
758 meshes[0].SetParameters(Parameters)
760 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
761 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
763 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
764 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
765 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
768 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
770 Create a mesh by copying a part of another mesh.
773 meshPart: a part of mesh to copy, either
774 :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`.
775 To copy nodes or elements not forming any mesh object,
776 pass result of :meth:`Mesh.GetIDSource` as *meshPart*
777 meshName: a name of the new mesh
778 toCopyGroups: to create in the new mesh groups the copied elements belongs to
779 toKeepIDs: to preserve order of the copied elements or not
782 an instance of class :class:`Mesh`
785 if isinstance( meshPart, Mesh ):
786 meshPart = meshPart.GetMesh()
787 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
788 return Mesh(self, self.geompyD, mesh)
790 def CopyMeshWithGeom( self, sourceMesh, newGeom, meshName="", toCopyGroups=True,
791 toReuseHypotheses=True, toCopyElements=True):
793 Create a mesh by copying a mesh definition (hypotheses and groups) to a new geometry.
794 It is supposed that the new geometry is a modified geometry of *sourceMesh*.
795 To facilitate and speed up the operation, consider using
796 "Set presentation parameters and sub-shapes from arguments" option in
797 a dialog of geometrical operation used to create the new geometry.
800 sourceMesh: the mesh to copy definition of.
801 newGeom: the new geomtry.
802 meshName: an optional name of the new mesh. If omitted, the mesh name is kept.
803 toCopyGroups: to create groups in the new mesh.
804 toReuseHypotheses: to reuse hypotheses of the *sourceMesh*.
805 toCopyElements: to copy mesh elements present on non-modified sub-shapes of
808 tuple ( ok, newMesh, newGroups, newSubMeshes, newHypotheses, invalidEntries )
809 *invalidEntries* are study entries of objects whose
810 counterparts are not found in the *newGeom*, followed by entries
811 of mesh sub-objects that are invalid because they depend on a not found
814 if isinstance( sourceMesh, Mesh ):
815 sourceMesh = sourceMesh.GetMesh()
817 ok, newMesh, newGroups, newSubMeshes, newHypotheses, invalidEntries = \
818 SMESH._objref_SMESH_Gen.CopyMeshWithGeom( self, sourceMesh, newGeom, meshName,
822 return ( ok, Mesh(self, self.geompyD, newMesh),
823 newGroups, newSubMeshes, newHypotheses, invalidEntries )
825 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
827 Return IDs of sub-shapes
830 theMainObject (GEOM.GEOM_Object): a shape
831 theListOfSubObjects: sub-shapes (list of GEOM.GEOM_Object)
833 the list of integer values
836 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
838 def GetPattern(self):
840 Create a pattern mapper.
843 an instance of :class:`SMESH.SMESH_Pattern`
845 :ref:`Example of Patterns usage <tui_pattern_mapping>`
848 return SMESH._objref_SMESH_Gen.GetPattern(self)
850 def SetBoundaryBoxSegmentation(self, nbSegments):
852 Set number of segments per diagonal of boundary box of geometry, by which
853 default segment length of appropriate 1D hypotheses is defined in GUI.
857 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
859 # Filtering. Auxiliary functions:
860 # ------------------------------
862 def GetEmptyCriterion(self):
864 Create an empty criterion
867 :class:`SMESH.Filter.Criterion`
870 Type = self.EnumToLong(FT_Undefined)
871 Compare = self.EnumToLong(FT_Undefined)
875 UnaryOp = self.EnumToLong(FT_Undefined)
876 BinaryOp = self.EnumToLong(FT_Undefined)
879 Precision = -1 ##@1e-07
880 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
881 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
883 def GetCriterion(self,elementType,
885 Compare = FT_EqualTo,
887 UnaryOp=FT_Undefined,
888 BinaryOp=FT_Undefined,
891 Create a criterion by the given parameters
892 Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
895 elementType: the :class:`type of elements <SMESH.ElementType>` (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
896 CritType: the type of criterion :class:`SMESH.FunctorType` (SMESH.FT_Taper, SMESH.FT_Area, etc.).
897 Note that the items starting from FT_LessThan are not suitable for *CritType*.
898 Compare: belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
899 Threshold: the threshold value (range of ids as string, shape, numeric)
900 UnaryOp: SMESH.FT_LogicalNOT or SMESH.FT_Undefined
901 BinaryOp: a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or
903 Tolerance: the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
904 SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
907 :class:`SMESH.Filter.Criterion`
909 Example: :ref:`combining_filters`
912 if not CritType in SMESH.FunctorType._items:
913 raise TypeError("CritType should be of SMESH.FunctorType")
914 aCriterion = self.GetEmptyCriterion()
915 aCriterion.TypeOfElement = elementType
916 aCriterion.Type = self.EnumToLong(CritType)
917 aCriterion.Tolerance = Tolerance
919 aThreshold = Threshold
921 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
922 aCriterion.Compare = self.EnumToLong(Compare)
923 elif Compare == "=" or Compare == "==":
924 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
926 aCriterion.Compare = self.EnumToLong(FT_LessThan)
928 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
929 elif Compare != FT_Undefined:
930 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
933 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
934 FT_BelongToCylinder, FT_LyingOnGeom]:
935 # Check that Threshold is GEOM object
936 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
937 aCriterion.ThresholdStr = GetName(aThreshold)
938 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
939 if not aCriterion.ThresholdID:
940 name = aCriterion.ThresholdStr
942 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
943 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
944 # or a name of GEOM object
945 elif isinstance( aThreshold, str ):
946 aCriterion.ThresholdStr = aThreshold
948 raise TypeError("The Threshold should be a shape.")
949 if isinstance(UnaryOp,float):
950 aCriterion.Tolerance = UnaryOp
951 UnaryOp = FT_Undefined
953 elif CritType == FT_BelongToMeshGroup:
954 # Check that Threshold is a group
955 if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
956 if aThreshold.GetType() != elementType:
957 raise ValueError("Group type mismatches Element type")
958 aCriterion.ThresholdStr = aThreshold.GetName()
959 aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
960 study = salome.myStudy
962 so = study.FindObjectIOR( aCriterion.ThresholdID )
966 aCriterion.ThresholdID = entry
968 raise TypeError("The Threshold should be a Mesh Group")
969 elif CritType == FT_RangeOfIds:
970 # Check that Threshold is string
971 if isinstance(aThreshold, str):
972 aCriterion.ThresholdStr = aThreshold
974 raise TypeError("The Threshold should be a string.")
975 elif CritType == FT_CoplanarFaces:
976 # Check the Threshold
977 if isinstance(aThreshold, int):
978 aCriterion.ThresholdID = str(aThreshold)
979 elif isinstance(aThreshold, str):
982 raise ValueError("Invalid ID of mesh face: '%s'"%aThreshold)
983 aCriterion.ThresholdID = aThreshold
985 raise TypeError("The Threshold should be an ID of mesh face and not '%s'"%aThreshold)
986 elif CritType == FT_ConnectedElements:
987 # Check the Threshold
988 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
989 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
990 if not aCriterion.ThresholdID:
991 name = aThreshold.GetName()
993 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
994 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
995 elif isinstance(aThreshold, int): # node id
996 aCriterion.Threshold = aThreshold
997 elif isinstance(aThreshold, list): # 3 point coordinates
998 if len( aThreshold ) < 3:
999 raise ValueError("too few point coordinates, must be 3")
1000 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
1001 elif isinstance(aThreshold, str):
1002 if aThreshold.isdigit():
1003 aCriterion.Threshold = aThreshold # node id
1005 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
1007 raise TypeError("The Threshold should either a VERTEX, or a node ID, "\
1008 "or a list of point coordinates and not '%s'"%aThreshold)
1009 elif CritType == FT_ElemGeomType:
1010 # Check the Threshold
1012 aCriterion.Threshold = self.EnumToLong(aThreshold)
1013 assert( aThreshold in SMESH.GeometryType._items )
1015 if isinstance(aThreshold, int):
1016 aCriterion.Threshold = aThreshold
1018 raise TypeError("The Threshold should be an integer or SMESH.GeometryType.")
1021 elif CritType == FT_EntityType:
1022 # Check the Threshold
1024 aCriterion.Threshold = self.EnumToLong(aThreshold)
1025 assert( aThreshold in SMESH.EntityType._items )
1027 if isinstance(aThreshold, int):
1028 aCriterion.Threshold = aThreshold
1030 raise TypeError("The Threshold should be an integer or SMESH.EntityType.")
1034 elif CritType == FT_GroupColor:
1035 # Check the Threshold
1037 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
1039 raise TypeError("The threshold value should be of SALOMEDS.Color type")
1041 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
1042 FT_LinearOrQuadratic, FT_BadOrientedVolume,
1043 FT_BareBorderFace, FT_BareBorderVolume,
1044 FT_OverConstrainedFace, FT_OverConstrainedVolume,
1045 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
1046 # At this point the Threshold is unnecessary
1047 if aThreshold == FT_LogicalNOT:
1048 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
1049 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
1050 aCriterion.BinaryOp = aThreshold
1054 aThreshold = float(aThreshold)
1055 aCriterion.Threshold = aThreshold
1057 raise TypeError("The Threshold should be a number.")
1060 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
1061 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
1063 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
1064 aCriterion.BinaryOp = self.EnumToLong(Threshold)
1066 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
1067 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
1069 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
1070 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
1074 def GetFilter(self,elementType,
1075 CritType=FT_Undefined,
1078 UnaryOp=FT_Undefined,
1082 Create a filter with the given parameters
1085 elementType: the :class:`type of elements <SMESH.ElementType>` (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1086 CritType: the :class:`type of criterion <SMESH.FunctorType>` (SMESH.FT_Taper, SMESH.FT_Area, etc.).
1087 Note that the items starting from FT_LessThan are not suitable for CritType.
1088 Compare: belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
1089 Threshold: the threshold value (range of ids as string, shape, numeric)
1090 UnaryOp: SMESH.FT_LogicalNOT or SMESH.FT_Undefined
1091 Tolerance: the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
1092 SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
1093 mesh: the mesh to initialize the filter with
1096 :class:`SMESH.Filter`
1099 See :doc:`Filters usage examples <tui_filters>`
1102 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1103 aFilterMgr = self.CreateFilterManager()
1104 aFilter = aFilterMgr.CreateFilter()
1106 aCriteria.append(aCriterion)
1107 aFilter.SetCriteria(aCriteria)
1109 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
1110 else : aFilter.SetMesh( mesh )
1111 aFilterMgr.UnRegister()
1114 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
1116 Create a filter from criteria
1119 criteria: a list of :class:`SMESH.Filter.Criterion`
1120 binOp: binary operator used when binary operator of criteria is undefined
1123 :class:`SMESH.Filter`
1126 See :doc:`Filters usage examples <tui_filters>`
1129 for i in range( len( criteria ) - 1 ):
1130 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
1131 criteria[i].BinaryOp = self.EnumToLong( binOp )
1132 aFilterMgr = self.CreateFilterManager()
1133 aFilter = aFilterMgr.CreateFilter()
1134 aFilter.SetCriteria(criteria)
1135 aFilterMgr.UnRegister()
1138 def GetFunctor(self,theCriterion):
1140 Create a numerical functor by its type
1143 theCriterion (SMESH.FunctorType): functor type.
1144 Note that not all items correspond to numerical functors.
1147 :class:`SMESH.NumericalFunctor`
1150 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
1152 aFilterMgr = self.CreateFilterManager()
1154 if theCriterion == FT_AspectRatio:
1155 functor = aFilterMgr.CreateAspectRatio()
1156 elif theCriterion == FT_AspectRatio3D:
1157 functor = aFilterMgr.CreateAspectRatio3D()
1158 elif theCriterion == FT_Warping:
1159 functor = aFilterMgr.CreateWarping()
1160 elif theCriterion == FT_MinimumAngle:
1161 functor = aFilterMgr.CreateMinimumAngle()
1162 elif theCriterion == FT_Taper:
1163 functor = aFilterMgr.CreateTaper()
1164 elif theCriterion == FT_Skew:
1165 functor = aFilterMgr.CreateSkew()
1166 elif theCriterion == FT_Area:
1167 functor = aFilterMgr.CreateArea()
1168 elif theCriterion == FT_Volume3D:
1169 functor = aFilterMgr.CreateVolume3D()
1170 elif theCriterion == FT_MaxElementLength2D:
1171 functor = aFilterMgr.CreateMaxElementLength2D()
1172 elif theCriterion == FT_MaxElementLength3D:
1173 functor = aFilterMgr.CreateMaxElementLength3D()
1174 elif theCriterion == FT_MultiConnection:
1175 functor = aFilterMgr.CreateMultiConnection()
1176 elif theCriterion == FT_MultiConnection2D:
1177 functor = aFilterMgr.CreateMultiConnection2D()
1178 elif theCriterion == FT_Length:
1179 functor = aFilterMgr.CreateLength()
1180 elif theCriterion == FT_Length2D:
1181 functor = aFilterMgr.CreateLength2D()
1182 elif theCriterion == FT_Deflection2D:
1183 functor = aFilterMgr.CreateDeflection2D()
1184 elif theCriterion == FT_NodeConnectivityNumber:
1185 functor = aFilterMgr.CreateNodeConnectivityNumber()
1186 elif theCriterion == FT_BallDiameter:
1187 functor = aFilterMgr.CreateBallDiameter()
1189 print("Error: given parameter is not numerical functor type.")
1190 aFilterMgr.UnRegister()
1193 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
1198 theHType (string): mesh hypothesis type
1199 theLibName (string): mesh plug-in library name
1202 created hypothesis instance
1204 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
1206 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
1209 # wrap hypothesis methods
1210 for meth_name in dir( hyp.__class__ ):
1211 if not meth_name.startswith("Get") and \
1212 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
1213 method = getattr ( hyp.__class__, meth_name )
1214 if callable(method):
1215 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
1219 def GetMeshInfo(self, obj):
1221 Get the mesh statistic.
1222 Use :meth:`smeshBuilder.EnumToLong` to get an integer from
1223 an item of :class:`SMESH.EntityType`.
1226 dictionary { :class:`SMESH.EntityType` - "count of elements" }
1229 if isinstance( obj, Mesh ):
1232 if hasattr(obj, "GetMeshInfo"):
1233 values = obj.GetMeshInfo()
1234 for i in range(SMESH.Entity_Last._v):
1235 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1239 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1241 Get minimum distance between two objects
1243 * If *src2* is None, and *id2* = 0, distance from *src1* / *id1* to the origin is computed.
1244 * If *src2* is None, and *id2* != 0, it is assumed that both *id1* and *id2* belong to *src1*.
1247 src1 (SMESH.SMESH_IDSource): first source object
1248 src2 (SMESH.SMESH_IDSource): second source object
1249 id1 (int): node/element id from the first source
1250 id2 (int): node/element id from the second (or first) source
1251 isElem1 (boolean): *True* if *id1* is element id, *False* if it is node id
1252 isElem2 (boolean): *True* if *id2* is element id, *False* if it is node id
1255 minimum distance value
1258 :meth:`GetMinDistance`
1261 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1265 result = result.value
1268 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1270 Get :class:`SMESH.Measure` structure specifying minimum distance data between two objects
1272 * If *src2* is None, and *id2* = 0, distance from *src1* / *id1* to the origin is computed.
1273 * If *src2* is None, and *id2* != 0, it is assumed that both *id1* and *id2* belong to *src1*.
1276 src1 (SMESH.SMESH_IDSource): first source object
1277 src2 (SMESH.SMESH_IDSource): second source object
1278 id1 (int): node/element id from the first source
1279 id2 (int): node/element id from the second (or first) source
1280 isElem1 (boolean): *True* if **id1** is element id, *False* if it is node id
1281 isElem2 (boolean): *True* if **id2** is element id, *False* if it is node id
1284 :class:`SMESH.Measure` structure or None if input data is invalid
1289 if isinstance(src1, Mesh): src1 = src1.mesh
1290 if isinstance(src2, Mesh): src2 = src2.mesh
1291 if src2 is None and id2 != 0: src2 = src1
1292 if not hasattr(src1, "_narrow"): return None
1293 src1 = src1._narrow(SMESH.SMESH_IDSource)
1294 if not src1: return None
1295 unRegister = genObjUnRegister()
1298 e = m.GetMeshEditor()
1300 src1 = e.MakeIDSource([id1], SMESH.FACE)
1302 src1 = e.MakeIDSource([id1], SMESH.NODE)
1303 unRegister.set( src1 )
1305 if hasattr(src2, "_narrow"):
1306 src2 = src2._narrow(SMESH.SMESH_IDSource)
1307 if src2 and id2 != 0:
1309 e = m.GetMeshEditor()
1311 src2 = e.MakeIDSource([id2], SMESH.FACE)
1313 src2 = e.MakeIDSource([id2], SMESH.NODE)
1314 unRegister.set( src2 )
1317 aMeasurements = self.CreateMeasurements()
1318 unRegister.set( aMeasurements )
1319 result = aMeasurements.MinDistance(src1, src2)
1322 def BoundingBox(self, objects):
1324 Get bounding box of the specified object(s)
1327 objects (SMESH.SMESH_IDSource): single source object or list of source objects
1330 tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1333 :meth:`GetBoundingBox`
1336 result = self.GetBoundingBox(objects)
1340 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1343 def GetBoundingBox(self, objects):
1345 Get :class:`SMESH.Measure` structure specifying bounding box data of the specified object(s)
1348 objects (SMESH.SMESH_IDSource): single source object or list of source objects
1351 :class:`SMESH.Measure` structure
1357 if isinstance(objects, tuple):
1358 objects = list(objects)
1359 if not isinstance(objects, list):
1363 if isinstance(o, Mesh):
1364 srclist.append(o.mesh)
1365 elif hasattr(o, "_narrow"):
1366 src = o._narrow(SMESH.SMESH_IDSource)
1367 if src: srclist.append(src)
1370 aMeasurements = self.CreateMeasurements()
1371 result = aMeasurements.BoundingBox(srclist)
1372 aMeasurements.UnRegister()
1375 def GetLength(self, obj):
1377 Get sum of lengths of all 1D elements in the mesh object.
1380 obj: :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
1383 sum of lengths of all 1D elements
1386 if isinstance(obj, Mesh): obj = obj.mesh
1387 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1388 aMeasurements = self.CreateMeasurements()
1389 value = aMeasurements.Length(obj)
1390 aMeasurements.UnRegister()
1393 def GetArea(self, obj):
1395 Get sum of areas of all 2D elements in the mesh object.
1398 obj: :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
1401 sum of areas of all 2D elements
1404 if isinstance(obj, Mesh): obj = obj.mesh
1405 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1406 aMeasurements = self.CreateMeasurements()
1407 value = aMeasurements.Area(obj)
1408 aMeasurements.UnRegister()
1411 def GetVolume(self, obj):
1413 Get sum of volumes of all 3D elements in the mesh object.
1416 obj: :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
1419 sum of volumes of all 3D elements
1422 if isinstance(obj, Mesh): obj = obj.mesh
1423 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1424 aMeasurements = self.CreateMeasurements()
1425 value = aMeasurements.Volume(obj)
1426 aMeasurements.UnRegister()
1429 def GetGravityCenter(self, obj):
1431 Get gravity center of all nodes of the mesh object.
1434 obj: :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
1437 Three components of the gravity center (x,y,z)
1439 if isinstance(obj, Mesh): obj = obj.mesh
1440 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1441 aMeasurements = self.CreateMeasurements()
1442 pointStruct = aMeasurements.GravityCenter(obj)
1443 aMeasurements.UnRegister()
1444 return pointStruct.x, pointStruct.y, pointStruct.z
1446 pass # end of class smeshBuilder
1449 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1450 """Registering the new proxy for SMESH.SMESH_Gen"""
1453 def New( instance=None, instanceGeom=None):
1455 Create a new smeshBuilder instance. The smeshBuilder class provides the Python
1456 interface to create or load meshes.
1461 salome.salome_init()
1462 from salome.smesh import smeshBuilder
1463 smesh = smeshBuilder.New()
1466 instance: CORBA proxy of SMESH Engine. If None, the default Engine is used.
1467 instanceGeom: CORBA proxy of GEOM Engine. If None, the default Engine is used.
1469 :class:`smeshBuilder` instance
1474 if instance and isinstance( instance, SALOMEDS._objref_Study ):
1476 sys.stderr.write("Warning: 'study' argument is no more needed in smeshBuilder.New(). Consider updating your script!!!\n\n")
1481 smeshInst = smeshBuilder()
1482 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1483 smeshInst.init_smesh(instanceGeom)
1487 # Public class: Mesh
1488 # ==================
1491 class Mesh(metaclass = MeshMeta):
1493 This class allows defining and managing a mesh.
1494 It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1495 It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1496 new nodes and elements and by changing the existing entities), to get information
1497 about a mesh and to export a mesh in different formats.
1504 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1509 Create a mesh on the shape *obj* (or an empty mesh if *obj* is equal to 0) and
1510 sets the GUI name of this mesh to *name*.
1513 smeshpyD: an instance of smeshBuilder class
1514 geompyD: an instance of geomBuilder class
1515 obj: Shape to be meshed or :class:`SMESH.SMESH_Mesh` object
1516 name: Study name of the mesh
1519 self.smeshpyD = smeshpyD
1520 self.geompyD = geompyD
1525 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1528 # publish geom of mesh (issue 0021122)
1529 if not self.geom.GetStudyEntry():
1533 geo_name = name + " shape"
1535 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1536 geompyD.addToStudy( self.geom, geo_name )
1537 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1539 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1542 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1544 self.smeshpyD.SetName(self.mesh, name)
1546 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1549 self.geom = self.mesh.GetShapeToMesh()
1551 self.editor = self.mesh.GetMeshEditor()
1552 self.functors = [None] * SMESH.FT_Undefined._v
1554 # set self to algoCreator's
1555 for attrName in dir(self):
1556 attr = getattr( self, attrName )
1557 if isinstance( attr, algoCreator ):
1558 setattr( self, attrName, attr.copy( self ))
1565 Destructor. Clean-up resources
1568 #self.mesh.UnRegister()
1572 def SetMesh(self, theMesh):
1574 Initialize the Mesh object from an instance of :class:`SMESH.SMESH_Mesh` interface
1577 theMesh: a :class:`SMESH.SMESH_Mesh` object
1581 # do not call Register() as this prevents mesh servant deletion at closing study
1582 #if self.mesh: self.mesh.UnRegister()
1585 #self.mesh.Register()
1586 self.geom = self.mesh.GetShapeToMesh()
1591 Return the mesh, that is an encapsulated instance of :class:`SMESH.SMESH_Mesh` interface
1594 a :class:`SMESH.SMESH_Mesh` object
1601 Get the name of the mesh
1604 the name of the mesh as a string
1607 name = GetName(self.GetMesh())
1610 def SetName(self, name):
1612 Set a name to the mesh
1615 name: a new name of the mesh
1618 self.smeshpyD.SetName(self.GetMesh(), name)
1620 def GetSubMesh(self, geom, name):
1622 Get a sub-mesh object associated to a *geom* geometrical object.
1625 geom: a geometrical object (shape)
1626 name: a name for the sub-mesh in the Object Browser
1629 an object of type :class:`SMESH.SMESH_subMesh`, representing a part of mesh,
1630 which lies on the given shape
1633 A sub-mesh is implicitly created when a sub-shape is specified at
1634 creating an algorithm, for example::
1636 algo1D = mesh.Segment(geom=Edge_1)
1638 create a sub-mesh on *Edge_1* and assign Wire Discretization algorithm to it.
1639 The created sub-mesh can be retrieved from the algorithm::
1641 submesh = algo1D.GetSubMesh()
1644 AssureGeomPublished( self, geom, name )
1645 submesh = self.mesh.GetSubMesh( geom, name )
1650 Return the shape associated to the mesh
1658 def SetShape(self, geom):
1660 Associate the given shape to the mesh (entails the recreation of the mesh)
1663 geom: the shape to be meshed (GEOM_Object)
1666 self.mesh = self.smeshpyD.CreateMesh(geom)
1668 def HasShapeToMesh(self):
1670 Return ``True`` if this mesh is based on geometry
1672 return self.mesh.HasShapeToMesh()
1676 Load mesh from the study after opening the study
1680 def IsReadyToCompute(self, theSubObject):
1682 Return true if the hypotheses are defined well
1685 theSubObject: a sub-shape of a mesh shape
1691 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1693 def GetAlgoState(self, theSubObject):
1695 Return errors of hypotheses definition.
1696 The list of errors is empty if everything is OK.
1699 theSubObject: a sub-shape of a mesh shape
1705 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1707 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1709 Return a geometrical object on which the given element was built.
1710 The returned geometrical object, if not nil, is either found in the
1711 study or published by this method with the given name
1714 theElementID: the id of the mesh element
1715 theGeomName: the user-defined name of the geometrical object
1718 GEOM.GEOM_Object instance
1721 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1723 def MeshDimension(self):
1725 Return the mesh dimension depending on the dimension of the underlying shape
1726 or, if the mesh is not based on any shape, basing on deimension of elements
1729 mesh dimension as an integer value [0,3]
1732 if self.mesh.HasShapeToMesh():
1733 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1734 if len( shells ) > 0 :
1736 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1738 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1743 if self.NbVolumes() > 0: return 3
1744 if self.NbFaces() > 0: return 2
1745 if self.NbEdges() > 0: return 1
1748 def Evaluate(self, geom=0):
1750 Evaluate size of prospective mesh on a shape
1753 a list where i-th element is a number of elements of i-th :class:`SMESH.EntityType`.
1754 To know predicted number of e.g. edges, inquire it this way::
1756 Evaluate()[ smesh.EnumToLong( SMESH.Entity_Edge )]
1759 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1761 geom = self.mesh.GetShapeToMesh()
1764 return self.smeshpyD.Evaluate(self.mesh, geom)
1767 def Compute(self, geom=0, discardModifs=False, refresh=False):
1769 Compute the mesh and return the status of the computation
1772 geom: geomtrical shape on which mesh data should be computed
1773 discardModifs: if True and the mesh has been edited since
1774 a last total re-compute and that may prevent successful partial re-compute,
1775 then the mesh is cleaned before Compute()
1776 refresh: if *True*, Object Browser is automatically updated (when running in GUI)
1782 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1784 geom = self.mesh.GetShapeToMesh()
1789 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1791 ok = self.smeshpyD.Compute(self.mesh, geom)
1792 except SALOME.SALOME_Exception as ex:
1793 print("Mesh computation failed, exception caught:")
1794 print(" ", ex.details.text)
1797 print("Mesh computation failed, exception caught:")
1798 traceback.print_exc()
1802 # Treat compute errors
1803 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1805 for err in computeErrors:
1806 if self.mesh.HasShapeToMesh():
1807 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1809 stdErrors = ["OK", #COMPERR_OK
1810 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1811 "std::exception", #COMPERR_STD_EXCEPTION
1812 "OCC exception", #COMPERR_OCC_EXCEPTION
1813 "..", #COMPERR_SLM_EXCEPTION
1814 "Unknown exception", #COMPERR_EXCEPTION
1815 "Memory allocation problem", #COMPERR_MEMORY_PB
1816 "Algorithm failed", #COMPERR_ALGO_FAILED
1817 "Unexpected geometry", #COMPERR_BAD_SHAPE
1818 "Warning", #COMPERR_WARNING
1819 "Computation cancelled",#COMPERR_CANCELED
1820 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1822 if err.code < len(stdErrors): errText = stdErrors[err.code]
1824 errText = "code %s" % -err.code
1825 if errText: errText += ". "
1826 errText += err.comment
1827 if allReasons: allReasons += "\n"
1829 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1831 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1835 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1837 if err.isGlobalAlgo:
1845 reason = '%s %sD algorithm is missing' % (glob, dim)
1846 elif err.state == HYP_MISSING:
1847 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1848 % (glob, dim, name, dim))
1849 elif err.state == HYP_NOTCONFORM:
1850 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1851 elif err.state == HYP_BAD_PARAMETER:
1852 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1853 % ( glob, dim, name ))
1854 elif err.state == HYP_BAD_GEOMETRY:
1855 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1856 'geometry' % ( glob, dim, name ))
1857 elif err.state == HYP_HIDDEN_ALGO:
1858 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1859 'algorithm of upper dimension generating %sD mesh'
1860 % ( glob, dim, name, glob, dim ))
1862 reason = ("For unknown reason. "
1863 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1865 if allReasons: allReasons += "\n"
1866 allReasons += "- " + reason
1868 if not ok or allReasons != "":
1869 msg = '"' + GetName(self.mesh) + '"'
1870 if ok: msg += " has been computed with warnings"
1871 else: msg += " has not been computed"
1872 if allReasons != "": msg += ":"
1877 if salome.sg.hasDesktop():
1878 if not isinstance( refresh, list): # not a call from subMesh.Compute()
1879 if refresh: salome.sg.updateObjBrowser()
1883 def GetComputeErrors(self, shape=0 ):
1885 Return a list of error messages (:class:`SMESH.ComputeError`) of the last :meth:`Compute`
1889 shape = self.mesh.GetShapeToMesh()
1890 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1892 def GetSubShapeName(self, subShapeID ):
1894 Return a name of a sub-shape by its ID.
1895 Possible variants (for *subShapeID* == 3):
1897 - **"Face_12"** - published sub-shape
1898 - **FACE #3** - not published sub-shape
1899 - **sub-shape #3** - invalid sub-shape ID
1900 - **#3** - error in this function
1903 subShapeID: a unique ID of a sub-shape
1906 a string describing the sub-shape
1910 if not self.mesh.HasShapeToMesh():
1914 mainIOR = salome.orb.object_to_string( self.GetShape() )
1916 mainSO = s.FindObjectIOR(mainIOR)
1919 shapeText = '"%s"' % mainSO.GetName()
1920 subIt = s.NewChildIterator(mainSO)
1922 subSO = subIt.Value()
1924 obj = subSO.GetObject()
1925 if not obj: continue
1926 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1929 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1932 if ids == subShapeID:
1933 shapeText = '"%s"' % subSO.GetName()
1936 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1938 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1940 shapeText = 'sub-shape #%s' % (subShapeID)
1942 shapeText = "#%s" % (subShapeID)
1945 def GetFailedShapes(self, publish=False):
1947 Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1948 error of an algorithm
1951 publish: if *True*, the returned groups will be published in the study
1954 a list of GEOM groups each named after a failed algorithm
1959 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1960 for err in computeErrors:
1961 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1962 if not shape: continue
1963 if err.algoName in algo2shapes:
1964 algo2shapes[ err.algoName ].append( shape )
1966 algo2shapes[ err.algoName ] = [ shape ]
1970 for algoName, shapes in list(algo2shapes.items()):
1972 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1973 otherTypeShapes = []
1975 group = self.geompyD.CreateGroup( self.geom, groupType )
1976 for shape in shapes:
1977 if shape.GetShapeType() == shapes[0].GetShapeType():
1978 sameTypeShapes.append( shape )
1980 otherTypeShapes.append( shape )
1981 self.geompyD.UnionList( group, sameTypeShapes )
1983 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1985 group.SetName( algoName )
1986 groups.append( group )
1987 shapes = otherTypeShapes
1990 for group in groups:
1991 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1994 def GetMeshOrder(self):
1996 Return sub-mesh objects list in meshing order
1999 list of lists of :class:`sub-meshes <SMESH.SMESH_subMesh>`
2002 return self.mesh.GetMeshOrder()
2004 def SetMeshOrder(self, submeshes):
2006 Set order in which concurrent sub-meshes should be meshed
2009 submeshes: list of lists of :class:`sub-meshes <SMESH.SMESH_subMesh>`
2012 return self.mesh.SetMeshOrder(submeshes)
2014 def Clear(self, refresh=False):
2016 Remove all nodes and elements generated on geometry. Imported elements remain.
2019 refresh: if *True*, Object browser is automatically updated (when running in GUI)
2023 if ( salome.sg.hasDesktop() ):
2024 if refresh: salome.sg.updateObjBrowser()
2026 def ClearSubMesh(self, geomId, refresh=False):
2028 Remove all nodes and elements of indicated shape
2031 geomId: the ID of a sub-shape to remove elements on
2032 refresh: if *True*, Object browser is automatically updated (when running in GUI)
2035 self.mesh.ClearSubMesh(geomId)
2036 if salome.sg.hasDesktop():
2037 if refresh: salome.sg.updateObjBrowser()
2039 def AutomaticTetrahedralization(self, fineness=0):
2041 Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
2044 fineness: [0.0,1.0] defines mesh fineness
2050 dim = self.MeshDimension()
2052 self.RemoveGlobalHypotheses()
2053 self.Segment().AutomaticLength(fineness)
2055 self.Triangle().LengthFromEdges()
2060 return self.Compute()
2062 def AutomaticHexahedralization(self, fineness=0):
2064 Compute an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
2067 fineness: [0.0, 1.0] defines mesh fineness
2073 dim = self.MeshDimension()
2074 # assign the hypotheses
2075 self.RemoveGlobalHypotheses()
2076 self.Segment().AutomaticLength(fineness)
2083 return self.Compute()
2085 def AddHypothesis(self, hyp, geom=0):
2090 hyp: a hypothesis to assign
2091 geom: a subhape of mesh geometry
2094 :class:`SMESH.Hypothesis_Status`
2097 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
2098 hyp, geom = geom, hyp
2099 if isinstance( hyp, Mesh_Algorithm ):
2100 hyp = hyp.GetAlgorithm()
2105 geom = self.mesh.GetShapeToMesh()
2108 if self.mesh.HasShapeToMesh():
2109 hyp_type = hyp.GetName()
2110 lib_name = hyp.GetLibName()
2111 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
2112 # if checkAll and geom:
2113 # checkAll = geom.GetType() == 37
2115 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
2117 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
2118 status = self.mesh.AddHypothesis(geom, hyp)
2120 status = HYP_BAD_GEOMETRY, ""
2121 hyp_name = GetName( hyp )
2124 geom_name = geom.GetName()
2125 isAlgo = hyp._narrow( SMESH_Algo )
2126 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
2129 def IsUsedHypothesis(self, hyp, geom):
2131 Return True if an algorithm or hypothesis is assigned to a given shape
2134 hyp: an algorithm or hypothesis to check
2135 geom: a subhape of mesh geometry
2141 if not hyp: # or not geom
2143 if isinstance( hyp, Mesh_Algorithm ):
2144 hyp = hyp.GetAlgorithm()
2146 hyps = self.GetHypothesisList(geom)
2148 if h.GetId() == hyp.GetId():
2152 def RemoveHypothesis(self, hyp, geom=0):
2154 Unassign a hypothesis
2157 hyp (SMESH.SMESH_Hypothesis): a hypothesis to unassign
2158 geom (GEOM.GEOM_Object): a sub-shape of mesh geometry
2161 :class:`SMESH.Hypothesis_Status`
2166 if isinstance( hyp, Mesh_Algorithm ):
2167 hyp = hyp.GetAlgorithm()
2173 if self.IsUsedHypothesis( hyp, shape ):
2174 return self.mesh.RemoveHypothesis( shape, hyp )
2175 hypName = GetName( hyp )
2176 geoName = GetName( shape )
2177 print("WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName ))
2180 def GetHypothesisList(self, geom):
2182 Get the list of hypotheses added on a geometry
2185 geom (GEOM.GEOM_Object): a sub-shape of mesh geometry
2188 the sequence of :class:`SMESH.SMESH_Hypothesis`
2191 return self.mesh.GetHypothesisList( geom )
2193 def RemoveGlobalHypotheses(self):
2195 Remove all global hypotheses
2198 current_hyps = self.mesh.GetHypothesisList( self.geom )
2199 for hyp in current_hyps:
2200 self.mesh.RemoveHypothesis( self.geom, hyp )
2203 def ExportMED(self, *args, **kwargs):
2205 Export the mesh in a file in MED format
2206 allowing to overwrite the file if it exists or add the exported data to its contents
2209 fileName: is the file name
2210 auto_groups (boolean): parameter for creating/not creating
2211 the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
2212 the typical use is auto_groups=False.
2213 minor (int): define the minor version (y, where version is x.y.z) of MED file format.
2214 The minor must be between 0 and the current minor version of MED file library.
2215 If minor is equal to -1, the minor version is not changed (default).
2216 The major version (x, where version is x.y.z) cannot be changed.
2217 overwrite (boolean): parameter for overwriting/not overwriting the file
2218 meshPart: a part of mesh (:class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>`) to export instead of the mesh
2219 autoDimension: if *True* (default), a space dimension of a MED mesh can be either
2221 - 1D if all mesh nodes lie on OX coordinate axis, or
2222 - 2D if all mesh nodes lie on XOY coordinate plane, or
2223 - 3D in the rest cases.
2225 If *autoDimension* is *False*, the space dimension is always 3.
2226 fields: list of GEOM fields defined on the shape to mesh.
2227 geomAssocFields: each character of this string means a need to export a
2228 corresponding field; correspondence between fields and characters
2231 - 'v' stands for "_vertices_" field;
2232 - 'e' stands for "_edges_" field;
2233 - 'f' stands for "_faces_" field;
2234 - 's' stands for "_solids_" field.
2236 zTolerance (float): tolerance in Z direction. If Z coordinate of a node is
2237 close to zero within a given tolerance, the coordinate is set to zero.
2238 If *ZTolerance* is negative (default), the node coordinates are kept as is.
2240 # process positional arguments
2241 #args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
2243 auto_groups = args[1] if len(args) > 1 else False
2244 minor = args[2] if len(args) > 2 else -1
2245 overwrite = args[3] if len(args) > 3 else True
2246 meshPart = args[4] if len(args) > 4 else None
2247 autoDimension = args[5] if len(args) > 5 else True
2248 fields = args[6] if len(args) > 6 else []
2249 geomAssocFields = args[7] if len(args) > 7 else ''
2250 z_tolerance = args[8] if len(args) > 8 else -1.
2251 # process keywords arguments
2252 auto_groups = kwargs.get("auto_groups", auto_groups)
2253 minor = kwargs.get("minor", minor)
2254 overwrite = kwargs.get("overwrite", overwrite)
2255 meshPart = kwargs.get("meshPart", meshPart)
2256 autoDimension = kwargs.get("autoDimension", autoDimension)
2257 fields = kwargs.get("fields", fields)
2258 geomAssocFields = kwargs.get("geomAssocFields", geomAssocFields)
2259 z_tolerance = kwargs.get("zTolerance", z_tolerance)
2260 # invoke engine's function
2261 if meshPart or fields or geomAssocFields or z_tolerance > 0:
2262 unRegister = genObjUnRegister()
2263 if isinstance( meshPart, list ):
2264 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2265 unRegister.set( meshPart )
2266 self.mesh.ExportPartToMED( meshPart, fileName, auto_groups, minor, overwrite, autoDimension,
2267 fields, geomAssocFields, z_tolerance)
2269 self.mesh.ExportMED(fileName, auto_groups, minor, overwrite, autoDimension)
2271 def ExportSAUV(self, f, auto_groups=0):
2273 Export the mesh in a file in SAUV format
2278 auto_groups: boolean parameter for creating/not creating
2279 the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
2280 the typical use is auto_groups=False.
2283 self.mesh.ExportSAUV(f, auto_groups)
2285 def ExportDAT(self, f, meshPart=None):
2287 Export the mesh in a file in DAT format
2291 meshPart: a part of mesh (:class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>`) to export instead of the mesh
2295 unRegister = genObjUnRegister()
2296 if isinstance( meshPart, list ):
2297 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2298 unRegister.set( meshPart )
2299 self.mesh.ExportPartToDAT( meshPart, f )
2301 self.mesh.ExportDAT(f)
2303 def ExportUNV(self, f, meshPart=None):
2305 Export the mesh in a file in UNV format
2309 meshPart: a part of mesh (:class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>`) to export instead of the mesh
2313 unRegister = genObjUnRegister()
2314 if isinstance( meshPart, list ):
2315 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2316 unRegister.set( meshPart )
2317 self.mesh.ExportPartToUNV( meshPart, f )
2319 self.mesh.ExportUNV(f)
2321 def ExportSTL(self, f, ascii=1, meshPart=None):
2323 Export the mesh in a file in STL format
2327 ascii: defines the file encoding
2328 meshPart: a part of mesh (:class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>`) to export instead of the mesh
2332 unRegister = genObjUnRegister()
2333 if isinstance( meshPart, list ):
2334 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2335 unRegister.set( meshPart )
2336 self.mesh.ExportPartToSTL( meshPart, f, ascii )
2338 self.mesh.ExportSTL(f, ascii)
2340 def ExportCGNS(self, f, overwrite=1, meshPart=None, groupElemsByType=False):
2342 Export the mesh in a file in CGNS format
2346 overwrite: boolean parameter for overwriting/not overwriting the file
2347 meshPart: a part of mesh (:class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>`) to export instead of the mesh
2348 groupElemsByType: if True all elements of same entity type are exported at ones,
2349 else elements are exported in order of their IDs which can cause creation
2350 of multiple cgns sections
2353 unRegister = genObjUnRegister()
2354 if isinstance( meshPart, list ):
2355 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2356 unRegister.set( meshPart )
2357 if isinstance( meshPart, Mesh ):
2358 meshPart = meshPart.mesh
2360 meshPart = self.mesh
2361 self.mesh.ExportCGNS(meshPart, f, overwrite, groupElemsByType)
2363 def ExportGMF(self, f, meshPart=None):
2365 Export the mesh in a file in GMF format.
2366 GMF files must have .mesh extension for the ASCII format and .meshb for
2367 the bynary format. Other extensions are not allowed.
2371 meshPart: a part of mesh (:class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>`) to export instead of the mesh
2374 unRegister = genObjUnRegister()
2375 if isinstance( meshPart, list ):
2376 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2377 unRegister.set( meshPart )
2378 if isinstance( meshPart, Mesh ):
2379 meshPart = meshPart.mesh
2381 meshPart = self.mesh
2382 self.mesh.ExportGMF(meshPart, f, True)
2384 def ExportToMED(self, *args, **kwargs):
2386 Deprecated, used only for compatibility! Please, use :meth:`ExportMED` method instead.
2387 Export the mesh in a file in MED format
2388 allowing to overwrite the file if it exists or add the exported data to its contents
2391 fileName: the file name
2392 opt (boolean): parameter for creating/not creating
2393 the groups Group_On_All_Nodes, Group_On_All_Faces, ...
2394 overwrite: boolean parameter for overwriting/not overwriting the file
2395 autoDimension: if *True* (default), a space dimension of a MED mesh can be either
2397 - 1D if all mesh nodes lie on OX coordinate axis, or
2398 - 2D if all mesh nodes lie on XOY coordinate plane, or
2399 - 3D in the rest cases.
2401 If **autoDimension** is *False*, the space dimension is always 3.
2404 print("WARNING: ExportToMED() is deprecated, use ExportMED() instead")
2405 # process positional arguments
2406 #args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
2408 auto_groups = args[1] if len(args) > 1 else False
2409 overwrite = args[2] if len(args) > 2 else True
2410 autoDimension = args[3] if len(args) > 3 else True
2411 # process keywords arguments
2412 auto_groups = kwargs.get("opt", auto_groups) # old keyword name
2413 auto_groups = kwargs.get("auto_groups", auto_groups) # new keyword name
2414 overwrite = kwargs.get("overwrite", overwrite)
2415 autoDimension = kwargs.get("autoDimension", autoDimension)
2417 # invoke engine's function
2418 self.mesh.ExportMED(fileName, auto_groups, minor, overwrite, autoDimension)
2420 def ExportToMEDX(self, *args, **kwargs):
2422 Deprecated, used only for compatibility! Please, use ExportMED() method instead.
2423 Export the mesh in a file in MED format
2426 fileName: the file name
2427 opt (boolean): parameter for creating/not creating
2428 the groups Group_On_All_Nodes, Group_On_All_Faces, ...
2429 overwrite: boolean parameter for overwriting/not overwriting the file
2430 autoDimension: if *True* (default), a space dimension of a MED mesh can be either
2432 - 1D if all mesh nodes lie on OX coordinate axis, or
2433 - 2D if all mesh nodes lie on XOY coordinate plane, or
2434 - 3D in the rest cases.
2436 If **autoDimension** is *False*, the space dimension is always 3.
2439 print("WARNING: ExportToMEDX() is deprecated, use ExportMED() instead")
2440 # process positional arguments
2441 #args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
2443 auto_groups = args[1] if len(args) > 1 else False
2444 overwrite = args[2] if len(args) > 2 else True
2445 autoDimension = args[3] if len(args) > 3 else True
2446 # process keywords arguments
2447 auto_groups = kwargs.get("auto_groups", auto_groups)
2448 overwrite = kwargs.get("overwrite", overwrite)
2449 autoDimension = kwargs.get("autoDimension", autoDimension)
2451 # invoke engine's function
2452 self.mesh.ExportMED(fileName, auto_groups, minor, overwrite, autoDimension)
2454 # Operations with groups:
2455 # ----------------------
2456 def CreateEmptyGroup(self, elementType, name):
2458 Create an empty standalone mesh group
2461 elementType: the :class:`type <SMESH.ElementType>` of elements in the group;
2462 either of (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2463 name: the name of the mesh group
2466 :class:`SMESH.SMESH_Group`
2469 return self.mesh.CreateGroup(elementType, name)
2471 def Group(self, grp, name=""):
2473 Create a mesh group based on the geometric object *grp*
2474 and give it a *name*.
2475 If *name* is not defined the name of the geometric group is used
2478 Works like :meth:`GroupOnGeom`.
2481 grp: a geometric group, a vertex, an edge, a face or a solid
2482 name: the name of the mesh group
2485 :class:`SMESH.SMESH_GroupOnGeom`
2488 return self.GroupOnGeom(grp, name)
2490 def GroupOnGeom(self, grp, name="", typ=None):
2492 Create a mesh group based on the geometrical object *grp*
2493 and give it a *name*.
2494 if *name* is not defined the name of the geometric group is used
2497 grp: a geometrical group, a vertex, an edge, a face or a solid
2498 name: the name of the mesh group
2499 typ: the type of elements in the group; either of
2500 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
2501 automatically detected by the type of the geometry
2504 :class:`SMESH.SMESH_GroupOnGeom`
2507 AssureGeomPublished( self, grp, name )
2509 name = grp.GetName()
2511 typ = self._groupTypeFromShape( grp )
2512 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
2514 def _groupTypeFromShape( self, shape ):
2516 Pivate method to get a type of group on geometry
2518 tgeo = str(shape.GetShapeType())
2519 if tgeo == "VERTEX":
2521 elif tgeo == "EDGE":
2523 elif tgeo == "FACE" or tgeo == "SHELL":
2525 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
2527 elif tgeo == "COMPOUND":
2528 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
2530 raise ValueError("_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape))
2531 return self._groupTypeFromShape( sub[0] )
2533 raise ValueError("_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape))
2536 def GroupOnFilter(self, typ, name, filter):
2538 Create a mesh group with given *name* based on the *filter*.
2539 It is a special type of group dynamically updating it's contents during
2543 typ: the type of elements in the group; either of
2544 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2545 name: the name of the mesh group
2546 filter (SMESH.Filter): the filter defining group contents
2549 :class:`SMESH.SMESH_GroupOnFilter`
2552 return self.mesh.CreateGroupFromFilter(typ, name, filter)
2554 def MakeGroupByIds(self, groupName, elementType, elemIDs):
2556 Create a mesh group by the given ids of elements
2559 groupName: the name of the mesh group
2560 elementType: the type of elements in the group; either of
2561 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2562 elemIDs: either the list of ids, :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
2565 :class:`SMESH.SMESH_Group`
2568 group = self.mesh.CreateGroup(elementType, groupName)
2569 if isinstance( elemIDs, Mesh ):
2570 elemIDs = elemIDs.GetMesh()
2571 if hasattr( elemIDs, "GetIDs" ):
2572 if hasattr( elemIDs, "SetMesh" ):
2573 elemIDs.SetMesh( self.GetMesh() )
2574 group.AddFrom( elemIDs )
2582 CritType=FT_Undefined,
2585 UnaryOp=FT_Undefined,
2588 Create a mesh group by the given conditions
2591 groupName: the name of the mesh group
2592 elementType (SMESH.ElementType): the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2593 CritType (SMESH.FunctorType): the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.).
2594 Note that the items starting from FT_LessThan are not suitable for CritType.
2595 Compare (SMESH.FunctorType): belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
2596 Threshold: the threshold value (range of ids as string, shape, numeric, depending on *CritType*)
2597 UnaryOp (SMESH.FunctorType): SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2598 Tolerance (float): the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2599 SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2602 :class:`SMESH.SMESH_GroupOnFilter`
2605 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2606 group = self.MakeGroupByCriterion(groupName, aCriterion)
2609 def MakeGroupByCriterion(self, groupName, Criterion):
2611 Create a mesh group by the given criterion
2614 groupName: the name of the mesh group
2615 Criterion: the instance of :class:`SMESH.Filter.Criterion` class
2618 :class:`SMESH.SMESH_GroupOnFilter`
2621 :meth:`smeshBuilder.GetCriterion`
2624 return self.MakeGroupByCriteria( groupName, [Criterion] )
2626 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2628 Create a mesh group by the given criteria (list of :class:`SMESH.Filter.Criterion`)
2631 groupName: the name of the mesh group
2632 theCriteria: the list of :class:`SMESH.Filter.Criterion`
2633 binOp: binary operator (SMESH.FT_LogicalAND or SMESH.FT_LogicalOR ) used when binary operator of criteria is undefined
2636 :class:`SMESH.SMESH_GroupOnFilter`
2639 :meth:`smeshBuilder.GetCriterion`
2642 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2643 group = self.MakeGroupByFilter(groupName, aFilter)
2646 def MakeGroupByFilter(self, groupName, theFilter):
2648 Create a mesh group by the given filter
2651 groupName (string): the name of the mesh group
2652 theFilter (SMESH.Filter): the filter
2655 :class:`SMESH.SMESH_GroupOnFilter`
2658 :meth:`smeshBuilder.GetFilter`
2661 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2662 #theFilter.SetMesh( self.mesh )
2663 #group.AddFrom( theFilter )
2664 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2667 def RemoveGroup(self, group):
2672 group (SMESH.SMESH_GroupBase): group to remove
2675 self.mesh.RemoveGroup(group)
2677 def RemoveGroupWithContents(self, group):
2679 Remove a group with its contents
2682 group (SMESH.SMESH_GroupBase): group to remove
2685 self.mesh.RemoveGroupWithContents(group)
2687 def GetGroups(self, elemType = SMESH.ALL):
2689 Get the list of groups existing in the mesh in the order of creation
2690 (starting from the oldest one)
2693 elemType (SMESH.ElementType): type of elements the groups contain;
2694 by default groups of elements of all types are returned
2697 a list of :class:`SMESH.SMESH_GroupBase`
2700 groups = self.mesh.GetGroups()
2701 if elemType == SMESH.ALL:
2705 if g.GetType() == elemType:
2706 typedGroups.append( g )
2713 Get the number of groups existing in the mesh
2716 the quantity of groups as an integer value
2719 return self.mesh.NbGroups()
2721 def GetGroupNames(self):
2723 Get the list of names of groups existing in the mesh
2729 groups = self.GetGroups()
2731 for group in groups:
2732 names.append(group.GetName())
2735 def GetGroupByName(self, name, elemType = None):
2737 Find groups by name and type
2740 name (string): name of the group of interest
2741 elemType (SMESH.ElementType): type of elements the groups contain;
2742 by default one group of any type is returned;
2743 if elemType == SMESH.ALL then all groups of any type are returned
2746 a list of :class:`SMESH.SMESH_GroupBase`
2750 for group in self.GetGroups():
2751 if group.GetName() == name:
2752 if elemType is None:
2754 if ( elemType == SMESH.ALL or
2755 group.GetType() == elemType ):
2756 groups.append( group )
2759 def UnionGroups(self, group1, group2, name):
2761 Produce a union of two groups.
2762 A new group is created. All mesh elements that are
2763 present in the initial groups are added to the new one
2766 group1 (SMESH.SMESH_GroupBase): a group
2767 group2 (SMESH.SMESH_GroupBase): another group
2770 instance of :class:`SMESH.SMESH_Group`
2773 return self.mesh.UnionGroups(group1, group2, name)
2775 def UnionListOfGroups(self, groups, name):
2777 Produce a union list of groups.
2778 New group is created. All mesh elements that are present in
2779 initial groups are added to the new one
2782 groups: list of :class:`SMESH.SMESH_GroupBase`
2785 instance of :class:`SMESH.SMESH_Group`
2787 return self.mesh.UnionListOfGroups(groups, name)
2789 def IntersectGroups(self, group1, group2, name):
2791 Prodice an intersection of two groups.
2792 A new group is created. All mesh elements that are common
2793 for the two initial groups are added to the new one.
2796 group1 (SMESH.SMESH_GroupBase): a group
2797 group2 (SMESH.SMESH_GroupBase): another group
2800 instance of :class:`SMESH.SMESH_Group`
2803 return self.mesh.IntersectGroups(group1, group2, name)
2805 def IntersectListOfGroups(self, groups, name):
2807 Produce an intersection of groups.
2808 New group is created. All mesh elements that are present in all
2809 initial groups simultaneously are added to the new one
2812 groups: a list of :class:`SMESH.SMESH_GroupBase`
2815 instance of :class:`SMESH.SMESH_Group`
2817 return self.mesh.IntersectListOfGroups(groups, name)
2819 def CutGroups(self, main_group, tool_group, name):
2821 Produce a cut of two groups.
2822 A new group is created. All mesh elements that are present in
2823 the main group but are not present in the tool group are added to the new one
2826 main_group (SMESH.SMESH_GroupBase): a group to cut from
2827 tool_group (SMESH.SMESH_GroupBase): a group to cut by
2830 an instance of :class:`SMESH.SMESH_Group`
2833 return self.mesh.CutGroups(main_group, tool_group, name)
2835 def CutListOfGroups(self, main_groups, tool_groups, name):
2837 Produce a cut of groups.
2838 A new group is created. All mesh elements that are present in main groups
2839 but do not present in tool groups are added to the new one
2842 main_group: groups to cut from (list of :class:`SMESH.SMESH_GroupBase`)
2843 tool_group: groups to cut by (list of :class:`SMESH.SMESH_GroupBase`)
2846 an instance of :class:`SMESH.SMESH_Group`
2849 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2851 def CreateDimGroup(self, groups, elemType, name,
2852 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2854 Create a standalone group of entities basing on nodes of other groups.
2857 groups: list of reference :class:`sub-meshes, groups or filters <SMESH.SMESH_IDSource>`, of any type.
2858 elemType: a type of elements to include to the new group; either of
2859 (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2860 name: a name of the new group.
2861 nbCommonNodes: a criterion of inclusion of an element to the new group
2862 basing on number of element nodes common with reference *groups*.
2863 Meaning of possible values are:
2865 - SMESH.ALL_NODES - include if all nodes are common,
2866 - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2867 - SMESH.AT_LEAST_ONE - include if one or more node is common,
2868 - SMEHS.MAJORITY - include if half of nodes or more are common.
2869 underlyingOnly: if *True* (default), an element is included to the
2870 new group provided that it is based on nodes of an element of *groups*;
2871 in this case the reference *groups* are supposed to be of higher dimension
2872 than *elemType*, which can be useful for example to get all faces lying on
2873 volumes of the reference *groups*.
2876 an instance of :class:`SMESH.SMESH_Group`
2879 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2881 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2884 def ConvertToStandalone(self, group):
2886 Convert group on geom into standalone group
2889 return self.mesh.ConvertToStandalone(group)
2891 # Get some info about mesh:
2892 # ------------------------
2894 def GetLog(self, clearAfterGet):
2896 Return the log of nodes and elements added or removed
2897 since the previous clear of the log.
2900 clearAfterGet: log is emptied after Get (safe if concurrents access)
2903 list of SMESH.log_block structures { commandType, number, coords, indexes }
2906 return self.mesh.GetLog(clearAfterGet)
2910 Clear the log of nodes and elements added or removed since the previous
2911 clear. Must be used immediately after :meth:`GetLog` if clearAfterGet is false.
2914 self.mesh.ClearLog()
2916 def SetAutoColor(self, theAutoColor):
2918 Toggle auto color mode on the object.
2919 If switched on, a default color of a new group in Create Group dialog is chosen randomly.
2922 theAutoColor (boolean): the flag which toggles auto color mode.
2925 self.mesh.SetAutoColor(theAutoColor)
2927 def GetAutoColor(self):
2929 Get flag of object auto color mode.
2935 return self.mesh.GetAutoColor()
2942 integer value, which is the internal Id of the mesh
2945 return self.mesh.GetId()
2947 def HasDuplicatedGroupNamesMED(self):
2949 Check the group names for duplications.
2950 Consider the maximum group name length stored in MED file.
2956 return self.mesh.HasDuplicatedGroupNamesMED()
2958 def GetMeshEditor(self):
2960 Obtain the mesh editor tool
2963 an instance of :class:`SMESH.SMESH_MeshEditor`
2968 def GetIDSource(self, ids, elemType = SMESH.ALL):
2970 Wrap a list of IDs of elements or nodes into :class:`SMESH.SMESH_IDSource` which
2971 can be passed as argument to a method accepting :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
2975 elemType: type of elements; this parameter is used to distinguish
2976 IDs of nodes from IDs of elements; by default ids are treated as
2977 IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2980 an instance of :class:`SMESH.SMESH_IDSource`
2983 call UnRegister() for the returned object as soon as it is no more useful::
2985 idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2986 mesh.DoSomething( idSrc )
2990 if isinstance( ids, int ):
2992 return self.editor.MakeIDSource(ids, elemType)
2995 # Get information about mesh contents:
2996 # ------------------------------------
2998 def GetMeshInfo(self, obj = None):
3000 Get the mesh statistic.
3001 Use :meth:`smeshBuilder.EnumToLong` to get an integer from
3002 an item of :class:`SMESH.EntityType`.
3005 dictionary { :class:`SMESH.EntityType` - "count of elements" }
3008 if not obj: obj = self.mesh
3009 return self.smeshpyD.GetMeshInfo(obj)
3013 Return the number of nodes in the mesh
3019 return self.mesh.NbNodes()
3021 def NbElements(self):
3023 Return the number of elements in the mesh
3029 return self.mesh.NbElements()
3031 def Nb0DElements(self):
3033 Return the number of 0d elements in the mesh
3039 return self.mesh.Nb0DElements()
3043 Return the number of ball discrete elements in the mesh
3049 return self.mesh.NbBalls()
3053 Return the number of edges in the mesh
3059 return self.mesh.NbEdges()
3061 def NbEdgesOfOrder(self, elementOrder):
3063 Return the number of edges with the given order in the mesh
3066 elementOrder: the order of elements
3067 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3073 return self.mesh.NbEdgesOfOrder(elementOrder)
3077 Return the number of faces in the mesh
3083 return self.mesh.NbFaces()
3085 def NbFacesOfOrder(self, elementOrder):
3087 Return the number of faces with the given order in the mesh
3090 elementOrder: the order of elements
3091 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3097 return self.mesh.NbFacesOfOrder(elementOrder)
3099 def NbTriangles(self):
3101 Return the number of triangles in the mesh
3107 return self.mesh.NbTriangles()
3109 def NbTrianglesOfOrder(self, elementOrder):
3111 Return the number of triangles with the given order in the mesh
3114 elementOrder: is the order of elements
3115 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3121 return self.mesh.NbTrianglesOfOrder(elementOrder)
3123 def NbBiQuadTriangles(self):
3125 Return the number of biquadratic triangles in the mesh
3131 return self.mesh.NbBiQuadTriangles()
3133 def NbQuadrangles(self):
3135 Return the number of quadrangles in the mesh
3141 return self.mesh.NbQuadrangles()
3143 def NbQuadranglesOfOrder(self, elementOrder):
3145 Return the number of quadrangles with the given order in the mesh
3148 elementOrder: the order of elements
3149 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3155 return self.mesh.NbQuadranglesOfOrder(elementOrder)
3157 def NbBiQuadQuadrangles(self):
3159 Return the number of biquadratic quadrangles in the mesh
3165 return self.mesh.NbBiQuadQuadrangles()
3167 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
3169 Return the number of polygons of given order in the mesh
3172 elementOrder: the order of elements
3173 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3179 return self.mesh.NbPolygonsOfOrder(elementOrder)
3181 def NbVolumes(self):
3183 Return the number of volumes in the mesh
3189 return self.mesh.NbVolumes()
3192 def NbVolumesOfOrder(self, elementOrder):
3194 Return the number of volumes with the given order in the mesh
3197 elementOrder: the order of elements
3198 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3204 return self.mesh.NbVolumesOfOrder(elementOrder)
3208 Return the number of tetrahedrons in the mesh
3214 return self.mesh.NbTetras()
3216 def NbTetrasOfOrder(self, elementOrder):
3218 Return the number of tetrahedrons with the given order in the mesh
3221 elementOrder: the order of elements
3222 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3228 return self.mesh.NbTetrasOfOrder(elementOrder)
3232 Return the number of hexahedrons in the mesh
3238 return self.mesh.NbHexas()
3240 def NbHexasOfOrder(self, elementOrder):
3242 Return the number of hexahedrons with the given order in the mesh
3245 elementOrder: the order of elements
3246 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3252 return self.mesh.NbHexasOfOrder(elementOrder)
3254 def NbTriQuadraticHexas(self):
3256 Return the number of triquadratic hexahedrons in the mesh
3262 return self.mesh.NbTriQuadraticHexas()
3264 def NbPyramids(self):
3266 Return the number of pyramids in the mesh
3272 return self.mesh.NbPyramids()
3274 def NbPyramidsOfOrder(self, elementOrder):
3276 Return the number of pyramids with the given order in the mesh
3279 elementOrder: the order of elements
3280 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3286 return self.mesh.NbPyramidsOfOrder(elementOrder)
3290 Return the number of prisms in the mesh
3296 return self.mesh.NbPrisms()
3298 def NbPrismsOfOrder(self, elementOrder):
3300 Return the number of prisms with the given order in the mesh
3303 elementOrder: the order of elements
3304 (SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC)
3310 return self.mesh.NbPrismsOfOrder(elementOrder)
3312 def NbHexagonalPrisms(self):
3314 Return the number of hexagonal prisms in the mesh
3320 return self.mesh.NbHexagonalPrisms()
3322 def NbPolyhedrons(self):
3324 Return the number of polyhedrons in the mesh
3330 return self.mesh.NbPolyhedrons()
3332 def NbSubMesh(self):
3334 Return the number of submeshes in the mesh
3340 return self.mesh.NbSubMesh()
3342 def GetElementsId(self):
3344 Return the list of all mesh elements IDs
3347 the list of integer values
3350 :meth:`GetElementsByType`
3353 return self.mesh.GetElementsId()
3355 def GetElementsByType(self, elementType):
3357 Return the list of IDs of mesh elements with the given type
3360 elementType (SMESH.ElementType): the required type of elements
3363 list of integer values
3366 return self.mesh.GetElementsByType(elementType)
3368 def GetNodesId(self):
3370 Return the list of mesh nodes IDs
3373 the list of integer values
3376 return self.mesh.GetNodesId()
3378 # Get the information about mesh elements:
3379 # ------------------------------------
3381 def GetElementType(self, id, iselem=True):
3383 Return the type of mesh element or node
3386 the value from :class:`SMESH.ElementType` enumeration.
3387 Return SMESH.ALL if element or node with the given ID does not exist
3390 return self.mesh.GetElementType(id, iselem)
3392 def GetElementGeomType(self, id):
3394 Return the geometric type of mesh element
3397 the value from :class:`SMESH.EntityType` enumeration.
3400 return self.mesh.GetElementGeomType(id)
3402 def GetElementShape(self, id):
3404 Return the shape type of mesh element
3407 the value from :class:`SMESH.GeometryType` enumeration.
3410 return self.mesh.GetElementShape(id)
3412 def GetSubMeshElementsId(self, Shape):
3414 Return the list of sub-mesh elements IDs
3417 Shape (GEOM.GEOM_Object): a geom object (sub-shape).
3418 *Shape* must be the sub-shape of the :meth:`main shape <GetShape>`
3421 list of integer values
3424 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
3425 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3428 return self.mesh.GetSubMeshElementsId(ShapeID)
3430 def GetSubMeshNodesId(self, Shape, all):
3432 Return the list of sub-mesh nodes IDs
3435 Shape: a geom object (sub-shape).
3436 *Shape* must be the sub-shape of a :meth:`GetShape`
3437 all: If True, gives all nodes of sub-mesh elements, otherwise gives only sub-mesh nodes
3440 list of integer values
3443 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
3444 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3447 return self.mesh.GetSubMeshNodesId(ShapeID, all)
3449 def GetSubMeshElementType(self, Shape):
3451 Return type of elements on given shape
3454 Shape: a geom object (sub-shape).
3455 *Shape* must be a sub-shape of a ShapeToMesh()
3458 :class:`SMESH.ElementType`
3461 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
3462 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3465 return self.mesh.GetSubMeshElementType(ShapeID)
3469 Get the mesh description
3475 return self.mesh.Dump()
3478 # Get the information about nodes and elements of a mesh by its IDs:
3479 # -----------------------------------------------------------
3481 def GetNodeXYZ(self, id):
3483 Get XYZ coordinates of a node.
3484 If there is no node for the given ID - return an empty list
3487 list of float values
3490 return self.mesh.GetNodeXYZ(id)
3492 def GetNodeInverseElements(self, id):
3494 Return list of IDs of inverse elements for the given node.
3495 If there is no node for the given ID - return an empty list
3498 list of integer values
3501 return self.mesh.GetNodeInverseElements(id)
3503 def GetNodePosition(self,NodeID):
3505 Return the position of a node on the shape
3508 :class:`SMESH.NodePosition`
3511 return self.mesh.GetNodePosition(NodeID)
3513 def GetElementPosition(self,ElemID):
3515 Return the position of an element on the shape
3518 :class:`SMESH.ElementPosition`
3521 return self.mesh.GetElementPosition(ElemID)
3523 def GetShapeID(self, id):
3525 Return the ID of the shape, on which the given node was generated.
3528 an integer value > 0 or -1 if there is no node for the given
3529 ID or the node is not assigned to any geometry
3532 return self.mesh.GetShapeID(id)
3534 def GetShapeIDForElem(self,id):
3536 Return the ID of the shape, on which the given element was generated.
3539 an integer value > 0 or -1 if there is no element for the given
3540 ID or the element is not assigned to any geometry
3543 return self.mesh.GetShapeIDForElem(id)
3545 def GetElemNbNodes(self, id):
3547 Return the number of nodes of the given element
3550 an integer value > 0 or -1 if there is no element for the given ID
3553 return self.mesh.GetElemNbNodes(id)
3555 def GetElemNode(self, id, index):
3557 Return the node ID the given (zero based) index for the given element.
3559 * If there is no element for the given ID - return -1.
3560 * If there is no node for the given index - return -2.
3563 id (int): element ID
3564 index (int): node index within the element
3567 an integer value (ID)
3570 :meth:`GetElemNodes`
3573 return self.mesh.GetElemNode(id, index)
3575 def GetElemNodes(self, id):
3577 Return the IDs of nodes of the given element
3580 a list of integer values
3583 return self.mesh.GetElemNodes(id)
3585 def IsMediumNode(self, elementID, nodeID):
3587 Return true if the given node is the medium node in the given quadratic element
3590 return self.mesh.IsMediumNode(elementID, nodeID)
3592 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
3594 Return true if the given node is the medium node in one of quadratic elements
3597 nodeID: ID of the node
3598 elementType: the type of elements to check a state of the node, either of
3599 (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
3602 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
3604 def ElemNbEdges(self, id):
3606 Return the number of edges for the given element
3609 return self.mesh.ElemNbEdges(id)
3611 def ElemNbFaces(self, id):
3613 Return the number of faces for the given element
3616 return self.mesh.ElemNbFaces(id)
3618 def GetElemFaceNodes(self,elemId, faceIndex):
3620 Return nodes of given face (counted from zero) for given volumic element.
3623 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
3625 def GetFaceNormal(self, faceId, normalized=False):
3627 Return three components of normal of given mesh face
3628 (or an empty array in KO case)
3631 return self.mesh.GetFaceNormal(faceId,normalized)
3633 def FindElementByNodes(self, nodes):
3635 Return an element based on all given nodes.
3638 return self.mesh.FindElementByNodes(nodes)
3640 def GetElementsByNodes(self, nodes, elemType=SMESH.ALL):
3642 Return elements including all given nodes.
3645 return self.mesh.GetElementsByNodes( nodes, elemType )
3647 def IsPoly(self, id):
3649 Return true if the given element is a polygon
3652 return self.mesh.IsPoly(id)
3654 def IsQuadratic(self, id):
3656 Return true if the given element is quadratic
3659 return self.mesh.IsQuadratic(id)
3661 def GetBallDiameter(self, id):
3663 Return diameter of a ball discrete element or zero in case of an invalid *id*
3666 return self.mesh.GetBallDiameter(id)
3668 def BaryCenter(self, id):
3670 Return XYZ coordinates of the barycenter of the given element.
3671 If there is no element for the given ID - return an empty list
3674 a list of three double values
3677 return self.mesh.BaryCenter(id)
3679 def GetIdsFromFilter(self, theFilter):
3681 Pass mesh elements through the given filter and return IDs of fitting elements
3684 theFilter: :class:`SMESH.Filter`
3690 :meth:`SMESH.Filter.GetIDs`
3693 theFilter.SetMesh( self.mesh )
3694 return theFilter.GetIDs()
3696 # Get mesh measurements information:
3697 # ------------------------------------
3699 def GetFreeBorders(self):
3701 Verify whether a 2D mesh element has free edges (edges connected to one face only).
3702 Return a list of special structures (borders).
3705 a list of :class:`SMESH.FreeEdges.Border`
3708 aFilterMgr = self.smeshpyD.CreateFilterManager()
3709 aPredicate = aFilterMgr.CreateFreeEdges()
3710 aPredicate.SetMesh(self.mesh)
3711 aBorders = aPredicate.GetBorders()
3712 aFilterMgr.UnRegister()
3715 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
3717 Get minimum distance between two nodes, elements or distance to the origin
3720 id1: first node/element id
3721 id2: second node/element id (if 0, distance from *id1* to the origin is computed)
3722 isElem1: *True* if *id1* is element id, *False* if it is node id
3723 isElem2: *True* if *id2* is element id, *False* if it is node id
3726 minimum distance value
3728 :meth:`GetMinDistance`
3731 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
3732 return aMeasure.value
3734 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
3736 Get :class:`SMESH.Measure` structure specifying minimum distance data between two objects
3739 id1: first node/element id
3740 id2: second node/element id (if 0, distance from *id1* to the origin is computed)
3741 isElem1: *True* if *id1* is element id, *False* if it is node id
3742 isElem2: *True* if *id2* is element id, *False* if it is node id
3745 :class:`SMESH.Measure` structure
3751 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
3753 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
3756 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
3758 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
3763 aMeasurements = self.smeshpyD.CreateMeasurements()
3764 aMeasure = aMeasurements.MinDistance(id1, id2)
3765 genObjUnRegister([aMeasurements,id1, id2])
3768 def BoundingBox(self, objects=None, isElem=False):
3770 Get bounding box of the specified object(s)
3773 objects: single :class:`source object <SMESH.SMESH_IDSource>` or list of source objects or list of nodes/elements IDs
3774 isElem: if *objects* is a list of IDs, *True* value in this parameters specifies that *objects* are elements,
3775 *False* specifies that *objects* are nodes
3778 tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
3781 :meth:`GetBoundingBox()`
3784 result = self.GetBoundingBox(objects, isElem)
3788 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
3791 def GetBoundingBox(self, objects=None, isElem=False):
3793 Get :class:`SMESH.Measure` structure specifying bounding box data of the specified object(s)
3796 objects: single :class:`source object <SMESH.SMESH_IDSource>` or list of source objects or list of nodes/elements IDs
3797 isElem: if *objects* is a list of IDs, True means that *objects* are elements,
3798 False means that *objects* are nodes
3801 :class:`SMESH.Measure` structure
3804 :meth:`BoundingBox()`
3808 objects = [self.mesh]
3809 elif isinstance(objects, tuple):
3810 objects = list(objects)
3811 if not isinstance(objects, list):
3813 if len(objects) > 0 and isinstance(objects[0], int):
3816 unRegister = genObjUnRegister()
3818 if isinstance(o, Mesh):
3819 srclist.append(o.mesh)
3820 elif hasattr(o, "_narrow"):
3821 src = o._narrow(SMESH.SMESH_IDSource)
3822 if src: srclist.append(src)
3824 elif isinstance(o, list):
3826 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
3828 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
3829 unRegister.set( srclist[-1] )
3832 aMeasurements = self.smeshpyD.CreateMeasurements()
3833 unRegister.set( aMeasurements )
3834 aMeasure = aMeasurements.BoundingBox(srclist)
3837 # Mesh edition (SMESH_MeshEditor functionality):
3838 # ---------------------------------------------
3840 def RemoveElements(self, IDsOfElements):
3842 Remove the elements from the mesh by ids
3845 IDsOfElements: is a list of ids of elements to remove
3851 return self.editor.RemoveElements(IDsOfElements)
3853 def RemoveNodes(self, IDsOfNodes):
3855 Remove nodes from mesh by ids
3858 IDsOfNodes: is a list of ids of nodes to remove
3864 return self.editor.RemoveNodes(IDsOfNodes)
3866 def RemoveOrphanNodes(self):
3868 Remove all orphan (free) nodes from mesh
3871 number of the removed nodes
3874 return self.editor.RemoveOrphanNodes()
3876 def AddNode(self, x, y, z):
3878 Add a node to the mesh by coordinates
3884 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3885 if hasVars: self.mesh.SetParameters(Parameters)
3886 return self.editor.AddNode( x, y, z)
3888 def Add0DElement( self, IDOfNode, DuplicateElements=True ):
3890 Create a 0D element on a node with given number.
3893 IDOfNode: the ID of node for creation of the element.
3894 DuplicateElements: to add one more 0D element to a node or not
3897 ID of the new 0D element
3900 return self.editor.Add0DElement( IDOfNode, DuplicateElements )
3902 def Add0DElementsToAllNodes(self, theObject, theGroupName="", DuplicateElements=False):
3904 Create 0D elements on all nodes of the given elements except those
3905 nodes on which a 0D element already exists.
3908 theObject: an object on whose nodes 0D elements will be created.
3909 It can be list of element IDs, :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
3910 theGroupName: optional name of a group to add 0D elements created
3911 and/or found on nodes of *theObject*.
3912 DuplicateElements: to add one more 0D element to a node or not
3915 an object (a new group or a temporary :class:`SMESH.SMESH_IDSource`) holding
3916 IDs of new and/or found 0D elements. IDs of 0D elements
3917 can be retrieved from the returned object by
3918 calling :meth:`GetIDs() <SMESH.SMESH_IDSource.GetIDs>`
3921 unRegister = genObjUnRegister()
3922 if isinstance( theObject, Mesh ):
3923 theObject = theObject.GetMesh()
3924 elif isinstance( theObject, list ):
3925 theObject = self.GetIDSource( theObject, SMESH.ALL )
3926 unRegister.set( theObject )
3927 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName, DuplicateElements )
3929 def AddBall(self, IDOfNode, diameter):
3931 Create a ball element on a node with given ID.
3934 IDOfNode: the ID of node for creation of the element.
3935 diameter: the bal diameter.
3938 ID of the new ball element
3941 return self.editor.AddBall( IDOfNode, diameter )
3943 def AddEdge(self, IDsOfNodes):
3945 Create a linear or quadratic edge (this is determined
3946 by the number of given nodes).
3949 IDsOfNodes: list of node IDs for creation of the element.
3950 The order of nodes in this list should correspond to
3951 the :ref:`connectivity convention <connectivity_page>`.
3957 return self.editor.AddEdge(IDsOfNodes)
3959 def AddFace(self, IDsOfNodes):
3961 Create a linear or quadratic face (this is determined
3962 by the number of given nodes).
3965 IDsOfNodes: list of node IDs for creation of the element.
3966 The order of nodes in this list should correspond to
3967 the :ref:`connectivity convention <connectivity_page>`.
3973 return self.editor.AddFace(IDsOfNodes)
3975 def AddPolygonalFace(self, IdsOfNodes):
3977 Add a polygonal face defined by a list of node IDs
3980 IdsOfNodes: the list of node IDs for creation of the element.
3986 return self.editor.AddPolygonalFace(IdsOfNodes)
3988 def AddQuadPolygonalFace(self, IdsOfNodes):
3990 Add a quadratic polygonal face defined by a list of node IDs
3993 IdsOfNodes: the list of node IDs for creation of the element;
3994 corner nodes follow first.
4000 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
4002 def AddVolume(self, IDsOfNodes):
4004 Create both simple and quadratic volume (this is determined
4005 by the number of given nodes).
4008 IDsOfNodes: list of node IDs for creation of the element.
4009 The order of nodes in this list should correspond to
4010 the :ref:`connectivity convention <connectivity_page>`.
4013 ID of the new volumic element
4016 return self.editor.AddVolume(IDsOfNodes)
4018 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
4020 Create a volume of many faces, giving nodes for each face.
4023 IdsOfNodes: list of node IDs for volume creation, face by face.
4024 Quantities: list of integer values, Quantities[i]
4025 gives the quantity of nodes in face number i.
4028 ID of the new volumic element
4031 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
4033 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
4035 Create a volume of many faces, giving the IDs of the existing faces.
4038 The created volume will refer only to the nodes
4039 of the given faces, not to the faces themselves.
4042 IdsOfFaces: the list of face IDs for volume creation.
4045 ID of the new volumic element
4048 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
4051 def SetNodeOnVertex(self, NodeID, Vertex):
4053 Bind a node to a vertex
4057 Vertex: a vertex (GEOM.GEOM_Object) or vertex ID
4060 True if succeed else raises an exception
4063 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
4064 VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
4068 self.editor.SetNodeOnVertex(NodeID, VertexID)
4069 except SALOME.SALOME_Exception as inst:
4070 raise ValueError(inst.details.text)
4074 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
4076 Store the node position on an edge
4080 Edge: an edge (GEOM.GEOM_Object) or edge ID
4081 paramOnEdge: a parameter on the edge where the node is located
4084 True if succeed else raises an exception
4087 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
4088 EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
4092 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
4093 except SALOME.SALOME_Exception as inst:
4094 raise ValueError(inst.details.text)
4097 def SetNodeOnFace(self, NodeID, Face, u, v):
4099 Store node position on a face
4103 Face: a face (GEOM.GEOM_Object) or face ID
4104 u: U parameter on the face where the node is located
4105 v: V parameter on the face where the node is located
4108 True if succeed else raises an exception
4111 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
4112 FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
4116 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
4117 except SALOME.SALOME_Exception as inst:
4118 raise ValueError(inst.details.text)
4121 def SetNodeInVolume(self, NodeID, Solid):
4123 Bind a node to a solid
4127 Solid: a solid (GEOM.GEOM_Object) or solid ID
4130 True if succeed else raises an exception
4133 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
4134 SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
4138 self.editor.SetNodeInVolume(NodeID, SolidID)
4139 except SALOME.SALOME_Exception as inst:
4140 raise ValueError(inst.details.text)
4143 def SetMeshElementOnShape(self, ElementID, Shape):
4145 Bind an element to a shape
4148 ElementID: an element ID
4149 Shape: a shape (GEOM.GEOM_Object) or shape ID
4152 True if succeed else raises an exception
4155 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
4156 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
4160 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
4161 except SALOME.SALOME_Exception as inst:
4162 raise ValueError(inst.details.text)
4166 def MoveNode(self, NodeID, x, y, z):
4168 Move the node with the given id
4171 NodeID: the id of the node
4172 x: a new X coordinate
4173 y: a new Y coordinate
4174 z: a new Z coordinate
4177 True if succeed else False
4180 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
4181 if hasVars: self.mesh.SetParameters(Parameters)
4182 return self.editor.MoveNode(NodeID, x, y, z)
4184 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
4186 Find the node closest to a point and moves it to a point location
4189 x: the X coordinate of a point
4190 y: the Y coordinate of a point
4191 z: the Z coordinate of a point
4192 NodeID: if specified (>0), the node with this ID is moved,
4193 otherwise, the node closest to point (*x*, *y*, *z*) is moved
4196 the ID of a moved node
4199 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
4200 if hasVars: self.mesh.SetParameters(Parameters)
4201 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
4203 def FindNodeClosestTo(self, x, y, z):
4205 Find the node closest to a point
4208 x: the X coordinate of a point
4209 y: the Y coordinate of a point
4210 z: the Z coordinate of a point
4216 #preview = self.mesh.GetMeshEditPreviewer()
4217 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
4218 return self.editor.FindNodeClosestTo(x, y, z)
4220 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
4222 Find the elements where a point lays IN or ON
4225 x,y,z (float): coordinates of the point
4226 elementType (SMESH.ElementType): type of elements to find; SMESH.ALL type
4227 means elements of any type excluding nodes, discrete and 0D elements.
4228 meshPart: a part of mesh (:class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>`) to search within
4231 list of IDs of found elements
4234 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
4236 return self.editor.FindElementsByPoint(x, y, z, elementType)
4238 def ProjectPoint(self, x,y,z, meshObject, elementType):
4240 Project a point to a mesh object.
4241 Return ID of an element of given type where the given point is projected
4242 and coordinates of the projection point.
4243 In the case if nothing found, return -1 and []
4245 if ( isinstance( meshObject, Mesh )):
4246 meshObject = meshObject.GetMesh()
4247 return self.editor.ProjectPoint( x,y,z, meshObject, elementType )
4249 def GetPointState(self, x, y, z):
4251 Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
4252 smesh.TopAbs_IN, smesh.TopAbs_OUT, smesh.TopAbs_ON and smesh.TopAbs_UNKNOWN.
4253 UNKNOWN state means that either mesh is wrong or the analysis fails.
4256 return self.editor.GetPointState(x, y, z)
4258 def IsManifold(self):
4260 Check if a 2D mesh is manifold
4263 return self.editor.IsManifold()
4265 def IsCoherentOrientation2D(self):
4267 Check if orientation of 2D elements is coherent
4270 return self.editor.IsCoherentOrientation2D()
4272 def MeshToPassThroughAPoint(self, x, y, z):
4274 Find the node closest to a point and moves it to a point location
4277 x: the X coordinate of a point
4278 y: the Y coordinate of a point
4279 z: the Z coordinate of a point
4282 the ID of a moved node
4285 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
4287 def InverseDiag(self, NodeID1, NodeID2):
4289 Replace two neighbour triangles sharing Node1-Node2 link
4290 with the triangles built on the same 4 nodes but having other common link.
4293 NodeID1: the ID of the first node
4294 NodeID2: the ID of the second node
4297 False if proper faces were not found
4299 return self.editor.InverseDiag(NodeID1, NodeID2)
4301 def DeleteDiag(self, NodeID1, NodeID2):
4303 Replace two neighbour triangles sharing *Node1-Node2* link
4304 with a quadrangle built on the same 4 nodes.
4307 NodeID1: ID of the first node
4308 NodeID2: ID of the second node
4311 False if proper faces were not found
4314 return self.editor.DeleteDiag(NodeID1, NodeID2)
4316 def Reorient(self, IDsOfElements=None):
4318 Reorient elements by ids
4321 IDsOfElements: if undefined reorients all mesh elements
4324 True if succeed else False
4327 if IDsOfElements == None:
4328 IDsOfElements = self.GetElementsId()
4329 return self.editor.Reorient(IDsOfElements)
4331 def ReorientObject(self, theObject):
4333 Reorient all elements of the object
4336 theObject: :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
4339 True if succeed else False
4342 if ( isinstance( theObject, Mesh )):
4343 theObject = theObject.GetMesh()
4344 return self.editor.ReorientObject(theObject)
4346 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
4348 Reorient faces contained in *the2DObject*.
4351 the2DObject: is a :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>` or list of IDs of 2D elements
4352 theDirection: is a desired direction of normal of *theFace*.
4353 It can be either a GEOM vector or a list of coordinates [x,y,z].
4354 theFaceOrPoint: defines a face of *the2DObject* whose normal will be
4355 compared with theDirection. It can be either ID of face or a point
4356 by which the face will be found. The point can be given as either
4357 a GEOM vertex or a list of point coordinates.
4360 number of reoriented faces
4363 unRegister = genObjUnRegister()
4365 if isinstance( the2DObject, Mesh ):
4366 the2DObject = the2DObject.GetMesh()
4367 if isinstance( the2DObject, list ):
4368 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
4369 unRegister.set( the2DObject )
4370 # check theDirection
4371 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
4372 theDirection = self.smeshpyD.GetDirStruct( theDirection )
4373 if isinstance( theDirection, list ):
4374 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
4375 # prepare theFace and thePoint
4376 theFace = theFaceOrPoint
4377 thePoint = PointStruct(0,0,0)
4378 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
4379 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
4381 if isinstance( theFaceOrPoint, list ):
4382 thePoint = PointStruct( *theFaceOrPoint )
4384 if isinstance( theFaceOrPoint, PointStruct ):
4385 thePoint = theFaceOrPoint
4387 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
4389 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
4391 Reorient faces according to adjacent volumes.
4394 the2DObject: is a :class:`mesh, sub-mesh, group, filter <SMESH.SMESH_IDSource>` or list of
4395 either IDs of faces or face groups.
4396 the3DObject: is a :class:`mesh, sub-mesh, group, filter <SMESH.SMESH_IDSource>` or list of IDs of volumes.
4397 theOutsideNormal: to orient faces to have their normals
4398 pointing either *outside* or *inside* the adjacent volumes.
4401 number of reoriented faces.
4404 unRegister = genObjUnRegister()
4406 if not isinstance( the2DObject, list ):
4407 the2DObject = [ the2DObject ]
4408 elif the2DObject and isinstance( the2DObject[0], int ):
4409 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
4410 unRegister.set( the2DObject )
4411 the2DObject = [ the2DObject ]
4412 for i,obj2D in enumerate( the2DObject ):
4413 if isinstance( obj2D, Mesh ):
4414 the2DObject[i] = obj2D.GetMesh()
4415 if isinstance( obj2D, list ):
4416 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
4417 unRegister.set( the2DObject[i] )
4419 if isinstance( the3DObject, Mesh ):
4420 the3DObject = the3DObject.GetMesh()
4421 if isinstance( the3DObject, list ):
4422 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
4423 unRegister.set( the3DObject )
4424 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
4426 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
4428 Fuse the neighbouring triangles into quadrangles.
4431 IDsOfElements: The triangles to be fused.
4432 theCriterion: a numerical functor, in terms of enum :class:`SMESH.FunctorType`, used to
4433 applied to possible quadrangles to choose a neighbour to fuse with.
4434 Note that not all items of :class:`SMESH.FunctorType` corresponds
4435 to numerical functors.
4436 MaxAngle: is the maximum angle between element normals at which the fusion
4437 is still performed; theMaxAngle is measured in radians.
4438 Also it could be a name of variable which defines angle in degrees.
4441 True in case of success, False otherwise.
4444 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
4445 self.mesh.SetParameters(Parameters)
4446 if not IDsOfElements:
4447 IDsOfElements = self.GetElementsId()
4448 Functor = self.smeshpyD.GetFunctor(theCriterion)
4449 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
4451 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
4453 Fuse the neighbouring triangles of the object into quadrangles
4456 theObject: is :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
4457 theCriterion: is a numerical functor, in terms of enum :class:`SMESH.FunctorType`,
4458 applied to possible quadrangles to choose a neighbour to fuse with.
4459 Note that not all items of :class:`SMESH.FunctorType` corresponds
4460 to numerical functors.
4461 MaxAngle: a max angle between element normals at which the fusion
4462 is still performed; theMaxAngle is measured in radians.
4465 True in case of success, False otherwise.
4468 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
4469 self.mesh.SetParameters(Parameters)
4470 if isinstance( theObject, Mesh ):
4471 theObject = theObject.GetMesh()
4472 Functor = self.smeshpyD.GetFunctor(theCriterion)
4473 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
4475 def QuadToTri (self, IDsOfElements, theCriterion = None):
4477 Split quadrangles into triangles.
4480 IDsOfElements: the faces to be splitted.
4481 theCriterion: is a numerical functor, in terms of enum :class:`SMESH.FunctorType`, used to
4482 choose a diagonal for splitting. If *theCriterion* is None, which is a default
4483 value, then quadrangles will be split by the smallest diagonal.
4484 Note that not all items of :class:`SMESH.FunctorType` corresponds
4485 to numerical functors.
4488 True in case of success, False otherwise.
4490 if IDsOfElements == []:
4491 IDsOfElements = self.GetElementsId()
4492 if theCriterion is None:
4493 theCriterion = FT_MaxElementLength2D
4494 Functor = self.smeshpyD.GetFunctor(theCriterion)
4495 return self.editor.QuadToTri(IDsOfElements, Functor)
4497 def QuadToTriObject (self, theObject, theCriterion = None):
4499 Split quadrangles into triangles.
4502 theObject: the object from which the list of elements is taken,
4503 this is :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
4504 theCriterion: is a numerical functor, in terms of enum :class:`SMESH.FunctorType`, used to
4505 choose a diagonal for splitting. If *theCriterion* is None, which is a default
4506 value, then quadrangles will be split by the smallest diagonal.
4507 Note that not all items of :class:`SMESH.FunctorType` corresponds
4508 to numerical functors.
4511 True in case of success, False otherwise.
4513 if ( isinstance( theObject, Mesh )):
4514 theObject = theObject.GetMesh()
4515 if theCriterion is None:
4516 theCriterion = FT_MaxElementLength2D
4517 Functor = self.smeshpyD.GetFunctor(theCriterion)
4518 return self.editor.QuadToTriObject(theObject, Functor)
4520 def QuadTo4Tri (self, theElements=[]):
4522 Split each of given quadrangles into 4 triangles. A node is added at the center of
4526 theElements: the faces to be splitted. This can be either
4527 :class:`mesh, sub-mesh, group, filter <SMESH.SMESH_IDSource>`
4528 or a list of face IDs. By default all quadrangles are split
4530 unRegister = genObjUnRegister()
4531 if isinstance( theElements, Mesh ):
4532 theElements = theElements.mesh
4533 elif not theElements:
4534 theElements = self.mesh
4535 elif isinstance( theElements, list ):
4536 theElements = self.GetIDSource( theElements, SMESH.FACE )
4537 unRegister.set( theElements )
4538 return self.editor.QuadTo4Tri( theElements )
4540 def SplitQuad (self, IDsOfElements, Diag13):
4542 Split quadrangles into triangles.
4545 IDsOfElements: the faces to be splitted
4546 Diag13 (boolean): is used to choose a diagonal for splitting.
4549 True in case of success, False otherwise.
4551 if IDsOfElements == []:
4552 IDsOfElements = self.GetElementsId()
4553 return self.editor.SplitQuad(IDsOfElements, Diag13)
4555 def SplitQuadObject (self, theObject, Diag13):
4557 Split quadrangles into triangles.
4560 theObject: the object from which the list of elements is taken,
4561 this is :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
4562 Diag13 (boolean): is used to choose a diagonal for splitting.
4565 True in case of success, False otherwise.
4567 if ( isinstance( theObject, Mesh )):
4568 theObject = theObject.GetMesh()
4569 return self.editor.SplitQuadObject(theObject, Diag13)
4571 def BestSplit (self, IDOfQuad, theCriterion):
4573 Find a better splitting of the given quadrangle.
4576 IDOfQuad: the ID of the quadrangle to be splitted.
4577 theCriterion: is a numerical functor, in terms of enum :class:`SMESH.FunctorType`, used to
4578 choose a diagonal for splitting.
4579 Note that not all items of :class:`SMESH.FunctorType` corresponds
4580 to numerical functors.
4583 * 1 if 1-3 diagonal is better,
4584 * 2 if 2-4 diagonal is better,
4585 * 0 if error occurs.
4587 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
4589 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
4591 Split volumic elements into tetrahedrons
4594 elems: either a list of elements or a :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
4595 method: flags passing splitting method:
4596 smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
4597 smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
4599 unRegister = genObjUnRegister()
4600 if isinstance( elems, Mesh ):
4601 elems = elems.GetMesh()
4602 if ( isinstance( elems, list )):
4603 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
4604 unRegister.set( elems )
4605 self.editor.SplitVolumesIntoTetra(elems, method)
4608 def SplitBiQuadraticIntoLinear(self, elems=None):
4610 Split bi-quadratic elements into linear ones without creation of additional nodes:
4612 - bi-quadratic triangle will be split into 3 linear quadrangles;
4613 - bi-quadratic quadrangle will be split into 4 linear quadrangles;
4614 - tri-quadratic hexahedron will be split into 8 linear hexahedra.
4616 Quadratic elements of lower dimension adjacent to the split bi-quadratic element
4617 will be split in order to keep the mesh conformal.
4620 elems: elements to split\: :class:`mesh, sub-mesh, group, filter <SMESH.SMESH_IDSource>` or element IDs;
4621 if None (default), all bi-quadratic elements will be split
4623 unRegister = genObjUnRegister()
4624 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
4625 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
4626 unRegister.set( elems )
4628 elems = [ self.GetMesh() ]
4629 if isinstance( elems, Mesh ):
4630 elems = [ elems.GetMesh() ]
4631 if not isinstance( elems, list ):
4633 self.editor.SplitBiQuadraticIntoLinear( elems )
4635 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
4636 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
4638 Split hexahedra into prisms
4641 elems: either a list of elements or a :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
4642 startHexPoint: a point used to find a hexahedron for which *facetNormal*
4643 gives a normal vector defining facets to split into triangles.
4644 *startHexPoint* can be either a triple of coordinates or a vertex.
4645 facetNormal: a normal to a facet to split into triangles of a
4646 hexahedron found by *startHexPoint*.
4647 *facetNormal* can be either a triple of coordinates or an edge.
4648 method: flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
4649 smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
4650 allDomains: if :code:`False`, only hexahedra adjacent to one closest
4651 to *startHexPoint* are split, else *startHexPoint*
4652 is used to find the facet to split in all domains present in *elems*.
4655 unRegister = genObjUnRegister()
4656 if isinstance( elems, Mesh ):
4657 elems = elems.GetMesh()
4658 if ( isinstance( elems, list )):
4659 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
4660 unRegister.set( elems )
4663 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
4664 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
4665 elif isinstance( startHexPoint, list ):
4666 startHexPoint = SMESH.PointStruct( startHexPoint[0],
4669 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
4670 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
4671 elif isinstance( facetNormal, list ):
4672 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
4675 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
4677 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
4679 def SplitQuadsNearTriangularFacets(self):
4681 Split quadrangle faces near triangular facets of volumes
4683 faces_array = self.GetElementsByType(SMESH.FACE)
4684 for face_id in faces_array:
4685 if self.GetElemNbNodes(face_id) == 4: # quadrangle
4686 quad_nodes = self.mesh.GetElemNodes(face_id)
4687 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
4688 isVolumeFound = False
4689 for node1_elem in node1_elems:
4690 if not isVolumeFound:
4691 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
4692 nb_nodes = self.GetElemNbNodes(node1_elem)
4693 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
4694 volume_elem = node1_elem
4695 volume_nodes = self.mesh.GetElemNodes(volume_elem)
4696 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
4697 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
4698 isVolumeFound = True
4699 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
4700 self.SplitQuad([face_id], False) # diagonal 2-4
4701 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
4702 isVolumeFound = True
4703 self.SplitQuad([face_id], True) # diagonal 1-3
4704 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
4705 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
4706 isVolumeFound = True
4707 self.SplitQuad([face_id], True) # diagonal 1-3
4709 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
4711 Split hexahedrons into tetrahedrons.
4713 This operation uses :doc:`pattern_mapping` functionality for splitting.
4716 theObject: the object from which the list of hexahedrons is taken;
4717 this is :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
4718 theNode000,theNode001: within the range [0,7]; gives the orientation of the
4719 pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
4720 will be mapped into *theNode000*-th node of each volume, the (0,0,1)
4721 key-point will be mapped into *theNode001*-th node of each volume.
4722 The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
4725 True in case of success, False otherwise.
4733 # (0,0,1) 4.---------.7 * |
4740 # (0,0,0) 0.---------.3
4741 pattern_tetra = "!!! Nb of points: \n 8 \n\
4751 !!! Indices of points of 6 tetras: \n\
4759 pattern = self.smeshpyD.GetPattern()
4760 isDone = pattern.LoadFromFile(pattern_tetra)
4762 print('Pattern.LoadFromFile :', pattern.GetErrorCode())
4765 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
4766 isDone = pattern.MakeMesh(self.mesh, False, False)
4767 if not isDone: print('Pattern.MakeMesh :', pattern.GetErrorCode())
4769 # split quafrangle faces near triangular facets of volumes
4770 self.SplitQuadsNearTriangularFacets()
4774 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
4776 Split hexahedrons into prisms.
4778 Uses the :doc:`pattern_mapping` functionality for splitting.
4781 theObject: the object (:class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`) from where the list of hexahedrons is taken;
4782 theNode000,theNode001: (within the range [0,7]) gives the orientation of the
4783 pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
4784 will be mapped into the *theNode000* -th node of each volume, keypoint (0,0,1)
4785 will be mapped into the *theNode001* -th node of each volume.
4786 Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
4789 True in case of success, False otherwise.
4791 # Pattern: 5.---------.6
4796 # (0,0,1) 4.---------.7 |
4803 # (0,0,0) 0.---------.3
4804 pattern_prism = "!!! Nb of points: \n 8 \n\
4814 !!! Indices of points of 2 prisms: \n\
4818 pattern = self.smeshpyD.GetPattern()
4819 isDone = pattern.LoadFromFile(pattern_prism)
4821 print('Pattern.LoadFromFile :', pattern.GetErrorCode())
4824 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
4825 isDone = pattern.MakeMesh(self.mesh, False, False)
4826 if not isDone: print('Pattern.MakeMesh :', pattern.GetErrorCode())
4828 # Split quafrangle faces near triangular facets of volumes
4829 self.SplitQuadsNearTriangularFacets()
4833 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
4834 MaxNbOfIterations, MaxAspectRatio, Method):
4839 IDsOfElements: the list if ids of elements to smooth
4840 IDsOfFixedNodes: the list of ids of fixed nodes.
4841 Note that nodes built on edges and boundary nodes are always fixed.
4842 MaxNbOfIterations: the maximum number of iterations
4843 MaxAspectRatio: varies in range [1.0, inf]
4844 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4845 or Centroidal (smesh.CENTROIDAL_SMOOTH)
4848 True in case of success, False otherwise.
4851 if IDsOfElements == []:
4852 IDsOfElements = self.GetElementsId()
4853 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
4854 self.mesh.SetParameters(Parameters)
4855 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
4856 MaxNbOfIterations, MaxAspectRatio, Method)
4858 def SmoothObject(self, theObject, IDsOfFixedNodes,
4859 MaxNbOfIterations, MaxAspectRatio, Method):
4861 Smooth elements which belong to the given object
4864 theObject: the object to smooth
4865 IDsOfFixedNodes: the list of ids of fixed nodes.
4866 Note that nodes built on edges and boundary nodes are always fixed.
4867 MaxNbOfIterations: the maximum number of iterations
4868 MaxAspectRatio: varies in range [1.0, inf]
4869 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4870 or Centroidal (smesh.CENTROIDAL_SMOOTH)
4873 True in case of success, False otherwise.
4876 if ( isinstance( theObject, Mesh )):
4877 theObject = theObject.GetMesh()
4878 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
4879 MaxNbOfIterations, MaxAspectRatio, Method)
4881 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
4882 MaxNbOfIterations, MaxAspectRatio, Method):
4884 Parametrically smooth the given elements
4887 IDsOfElements: the list if ids of elements to smooth
4888 IDsOfFixedNodes: the list of ids of fixed nodes.
4889 Note that nodes built on edges and boundary nodes are always fixed.
4890 MaxNbOfIterations: the maximum number of iterations
4891 MaxAspectRatio: varies in range [1.0, inf]
4892 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4893 or Centroidal (smesh.CENTROIDAL_SMOOTH)
4896 True in case of success, False otherwise.
4899 if IDsOfElements == []:
4900 IDsOfElements = self.GetElementsId()
4901 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
4902 self.mesh.SetParameters(Parameters)
4903 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
4904 MaxNbOfIterations, MaxAspectRatio, Method)
4906 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
4907 MaxNbOfIterations, MaxAspectRatio, Method):
4909 Parametrically smooth the elements which belong to the given object
4912 theObject: the object to smooth
4913 IDsOfFixedNodes: the list of ids of fixed nodes.
4914 Note that nodes built on edges and boundary nodes are always fixed.
4915 MaxNbOfIterations: the maximum number of iterations
4916 MaxAspectRatio: varies in range [1.0, inf]
4917 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4918 or Centroidal (smesh.CENTROIDAL_SMOOTH)
4921 True in case of success, False otherwise.
4924 if ( isinstance( theObject, Mesh )):
4925 theObject = theObject.GetMesh()
4926 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
4927 MaxNbOfIterations, MaxAspectRatio, Method)
4929 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
4931 Convert the mesh to quadratic or bi-quadratic, deletes old elements, replacing
4932 them with quadratic with the same id.
4935 theForce3d: method of new node creation:
4937 * False - the medium node lies at the geometrical entity from which the mesh element is built
4938 * True - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
4939 theSubMesh: a :class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>` to convert
4940 theToBiQuad: If True, converts the mesh to bi-quadratic
4943 :class:`SMESH.ComputeError` which can hold a warning
4946 If *theSubMesh* is provided, the mesh can become non-conformal
4949 if isinstance( theSubMesh, Mesh ):
4950 theSubMesh = theSubMesh.mesh
4952 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
4955 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
4957 self.editor.ConvertToQuadratic(theForce3d)
4958 error = self.editor.GetLastError()
4959 if error and error.comment:
4960 print(error.comment)
4963 def ConvertFromQuadratic(self, theSubMesh=None):
4965 Convert the mesh from quadratic to ordinary,
4966 deletes old quadratic elements,
4967 replacing them with ordinary mesh elements with the same id.
4970 theSubMesh: a :class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>` to convert
4973 If *theSubMesh* is provided, the mesh can become non-conformal
4977 self.editor.ConvertFromQuadraticObject(theSubMesh)
4979 return self.editor.ConvertFromQuadratic()
4981 def Make2DMeshFrom3D(self):
4983 Create 2D mesh as skin on boundary faces of a 3D mesh
4986 True if operation has been completed successfully, False otherwise
4989 return self.editor.Make2DMeshFrom3D()
4991 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
4992 toCopyElements=False, toCopyExistingBondary=False):
4994 Create missing boundary elements
4997 elements: elements whose boundary is to be checked:
4998 :class:`mesh, sub-mesh, group, filter <SMESH.SMESH_IDSource>` or list of elements.
4999 If *elements* is mesh, it must be the mesh whose MakeBoundaryMesh() is called
5000 dimension: defines type of boundary elements to create, either of
5001 { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }.
5002 SMESH.BND_1DFROM3D create mesh edges on all borders of free facets of 3D cells
5003 groupName: a name of group to store created boundary elements in,
5004 "" means not to create the group
5005 meshName: a name of new mesh to store created boundary elements in,
5006 "" means not to create the new mesh
5007 toCopyElements: if True, the checked elements will be copied into
5008 the new mesh else only boundary elements will be copied into the new mesh
5009 toCopyExistingBondary: if True, not only new but also pre-existing
5010 boundary elements will be copied into the new mesh
5013 tuple (:class:`Mesh`, :class:`group <SMESH.SMESH_Group>`) where boundary elements were added to
5016 unRegister = genObjUnRegister()
5017 if isinstance( elements, Mesh ):
5018 elements = elements.GetMesh()
5019 if ( isinstance( elements, list )):
5020 elemType = SMESH.ALL
5021 if elements: elemType = self.GetElementType( elements[0], iselem=True)
5022 elements = self.editor.MakeIDSource(elements, elemType)
5023 unRegister.set( elements )
5024 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
5025 toCopyElements,toCopyExistingBondary)
5026 if mesh: mesh = self.smeshpyD.Mesh(mesh)
5029 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
5030 toCopyAll=False, groups=[]):
5032 Create missing boundary elements around either the whole mesh or
5036 dimension: defines type of boundary elements to create, either of
5037 { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
5038 groupName: a name of group to store all boundary elements in,
5039 "" means not to create the group
5040 meshName: a name of a new mesh, which is a copy of the initial
5041 mesh + created boundary elements; "" means not to create the new mesh
5042 toCopyAll: if True, the whole initial mesh will be copied into
5043 the new mesh else only boundary elements will be copied into the new mesh
5044 groups: list of :class:`sub-meshes, groups or filters <SMESH.SMESH_IDSource>` of elements to make boundary around
5047 tuple( long, mesh, groups )
5048 - long - number of added boundary elements
5049 - mesh - the :class:`Mesh` where elements were added to
5050 - group - the :class:`group <SMESH.SMESH_Group>` of boundary elements or None
5053 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
5055 if mesh: mesh = self.smeshpyD.Mesh(mesh)
5056 return nb, mesh, group
5058 def RenumberNodes(self):
5060 Renumber mesh nodes to remove unused node IDs
5062 self.editor.RenumberNodes()
5064 def RenumberElements(self):
5066 Renumber mesh elements to remove unused element IDs
5068 self.editor.RenumberElements()
5070 def _getIdSourceList(self, arg, idType, unRegister):
5072 Private method converting *arg* into a list of :class:`SMESH.SMESH_IDSource`
5074 if arg and isinstance( arg, list ):
5075 if isinstance( arg[0], int ):
5076 arg = self.GetIDSource( arg, idType )
5077 unRegister.set( arg )
5078 elif isinstance( arg[0], Mesh ):
5079 arg[0] = arg[0].GetMesh()
5080 elif isinstance( arg, Mesh ):
5082 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
5086 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
5087 MakeGroups=False, TotalAngle=False):
5089 Generate new elements by rotation of the given elements and nodes around the axis
5092 nodes: nodes to revolve: a list including ids, :class:`a mesh, sub-meshes, groups or filters <SMESH.SMESH_IDSource>`
5093 edges: edges to revolve: a list including ids, :class:`a mesh, sub-meshes, groups or filters <SMESH.SMESH_IDSource>`
5094 faces: faces to revolve: a list including ids, :class:`a mesh, sub-meshes, groups or filters <SMESH.SMESH_IDSource>`
5095 Axis: the axis of rotation: :class:`SMESH.AxisStruct`, line (geom object) or [x,y,z,dx,dy,dz]
5096 AngleInRadians: the angle of Rotation (in radians) or a name of variable
5097 which defines angle in degrees
5098 NbOfSteps: the number of steps
5099 Tolerance: tolerance
5100 MakeGroups: forces the generation of new groups from existing ones
5101 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
5102 of all steps, else - size of each step
5105 the list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True, empty list otherwise
5108 unRegister = genObjUnRegister()
5109 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
5110 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
5111 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
5113 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
5114 Axis = self.smeshpyD.GetAxisStruct( Axis )
5115 if isinstance( Axis, list ):
5116 Axis = SMESH.AxisStruct( *Axis )
5118 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
5119 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
5120 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
5121 self.mesh.SetParameters(Parameters)
5122 if TotalAngle and NbOfSteps:
5123 AngleInRadians /= NbOfSteps
5124 return self.editor.RotationSweepObjects( nodes, edges, faces,
5125 Axis, AngleInRadians,
5126 NbOfSteps, Tolerance, MakeGroups)
5128 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
5129 MakeGroups=False, TotalAngle=False):
5131 Generate new elements by rotation of the elements around the axis
5134 IDsOfElements: the list of ids of elements to sweep
5135 Axis: the axis of rotation, :class:`SMESH.AxisStruct` or line(geom object)
5136 AngleInRadians: the angle of Rotation (in radians) or a name of variable which defines angle in degrees
5137 NbOfSteps: the number of steps
5138 Tolerance: tolerance
5139 MakeGroups: forces the generation of new groups from existing ones
5140 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
5141 of all steps, else - size of each step
5144 the list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True, empty list otherwise
5147 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
5148 AngleInRadians, NbOfSteps, Tolerance,
5149 MakeGroups, TotalAngle)
5151 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
5152 MakeGroups=False, TotalAngle=False):
5154 Generate new elements by rotation of the elements of object around the axis
5155 theObject object which elements should be sweeped.
5156 It can be a mesh, a sub mesh or a group.
5159 Axis: the axis of rotation, :class:`SMESH.AxisStruct` or line(geom object)
5160 AngleInRadians: the angle of Rotation
5161 NbOfSteps: number of steps
5162 Tolerance: tolerance
5163 MakeGroups: forces the generation of new groups from existing ones
5164 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
5165 of all steps, else - size of each step
5168 the list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True, empty list otherwise
5171 return self.RotationSweepObjects( [], theObject, theObject, Axis,
5172 AngleInRadians, NbOfSteps, Tolerance,
5173 MakeGroups, TotalAngle )
5175 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
5176 MakeGroups=False, TotalAngle=False):
5178 Generate new elements by rotation of the elements of object around the axis
5179 theObject object which elements should be sweeped.
5180 It can be a mesh, a sub mesh or a group.
5183 Axis: the axis of rotation, :class:`SMESH.AxisStruct` or line(geom object)
5184 AngleInRadians: the angle of Rotation
5185 NbOfSteps: number of steps
5186 Tolerance: tolerance
5187 MakeGroups: forces the generation of new groups from existing ones
5188 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
5189 of all steps, else - size of each step
5192 the list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True,
5193 empty list otherwise
5196 return self.RotationSweepObjects([],theObject,[], Axis,
5197 AngleInRadians, NbOfSteps, Tolerance,
5198 MakeGroups, TotalAngle)
5200 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
5201 MakeGroups=False, TotalAngle=False):
5203 Generate new elements by rotation of the elements of object around the axis
5204 theObject object which elements should be sweeped.
5205 It can be a mesh, a sub mesh or a group.
5208 Axis: the axis of rotation, :class:`SMESH.AxisStruct` or line(geom object)
5209 AngleInRadians: the angle of Rotation
5210 NbOfSteps: number of steps
5211 Tolerance: tolerance
5212 MakeGroups: forces the generation of new groups from existing ones
5213 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
5214 of all steps, else - size of each step
5217 the list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True, empty list otherwise
5220 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
5221 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
5223 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False,
5224 scaleFactors=[], linearVariation=False, basePoint=[] ):
5226 Generate new elements by extrusion of the given elements and nodes
5229 nodes: nodes to extrude: a list including ids, :class:`a mesh, sub-meshes, groups or filters <SMESH.SMESH_IDSource>`
5230 edges: edges to extrude: a list including ids, :class:`a mesh, sub-meshes, groups or filters <SMESH.SMESH_IDSource>`
5231 faces: faces to extrude: a list including ids, :class:`a mesh, sub-meshes, groups or filters <SMESH.SMESH_IDSource>`
5232 StepVector: vector or :class:`SMESH.DirStruct` or 3 vector components, defining
5233 the direction and value of extrusion for one step (the total extrusion
5234 length will be NbOfSteps * ||StepVector||)
5235 NbOfSteps: the number of steps
5236 MakeGroups: forces the generation of new groups from existing ones
5237 scaleFactors: optional scale factors to apply during extrusion
5238 linearVariation: if *True*, scaleFactors are spread over all *scaleFactors*,
5239 else scaleFactors[i] is applied to nodes at the i-th extrusion step
5240 basePoint: optional scaling center; if not provided, a gravity center of
5241 nodes and elements being extruded is used as the scaling center.
5244 - a list of tree components of the point or
5248 the list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True, empty list otherwise
5250 Example: :ref:`tui_extrusion`
5252 unRegister = genObjUnRegister()
5253 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
5254 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
5255 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
5257 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
5258 StepVector = self.smeshpyD.GetDirStruct(StepVector)
5259 if isinstance( StepVector, list ):
5260 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
5262 if isinstance( basePoint, int):
5263 xyz = self.GetNodeXYZ( basePoint )
5265 raise RuntimeError("Invalid node ID: %s" % basePoint)
5267 if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
5268 basePoint = self.geompyD.PointCoordinates( basePoint )
5270 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
5271 Parameters = StepVector.PS.parameters + var_separator + Parameters
5272 self.mesh.SetParameters(Parameters)
5274 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
5275 StepVector, NbOfSteps,
5276 scaleFactors, linearVariation, basePoint,
5280 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
5282 Generate new elements by extrusion of the elements with given ids
5285 IDsOfElements: the list of ids of elements or nodes for extrusion
5286 StepVector: vector or :class:`SMESH.DirStruct` or 3 vector components, defining
5287 the direction and value of extrusion for one step (the total extrusion
5288 length will be NbOfSteps * ||StepVector||)
5289 NbOfSteps: the number of steps
5290 MakeGroups: forces the generation of new groups from existing ones
5291 IsNodes: is True if elements with given ids are nodes
5294 the list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True, empty list otherwise
5296 Example: :ref:`tui_extrusion`
5299 if IsNodes: n = IDsOfElements
5300 else : e,f, = IDsOfElements,IDsOfElements
5301 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
5303 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
5304 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
5306 Generate new elements by extrusion along the normal to a discretized surface or wire
5309 Elements: elements to extrude - a list including ids, :class:`a mesh, sub-meshes, groups or filters <SMESH.SMESH_IDSource>`.
5310 Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
5311 StepSize: length of one extrusion step (the total extrusion
5312 length will be *NbOfSteps* *StepSize*).
5313 NbOfSteps: number of extrusion steps.
5314 ByAverageNormal: if True each node is translated by *StepSize*
5315 along the average of the normal vectors to the faces sharing the node;
5316 else each node is translated along the same average normal till
5317 intersection with the plane got by translation of the face sharing
5318 the node along its own normal by *StepSize*.
5319 UseInputElemsOnly: to use only *Elements* when computing extrusion direction
5320 for every node of *Elements*.
5321 MakeGroups: forces generation of new groups from existing ones.
5322 Dim: dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
5323 is not yet implemented. This parameter is used if *Elements* contains
5324 both faces and edges, i.e. *Elements* is a Mesh.
5327 the list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True,
5328 empty list otherwise.
5329 Example: :ref:`tui_extrusion`
5332 unRegister = genObjUnRegister()
5333 if isinstance( Elements, Mesh ):
5334 Elements = [ Elements.GetMesh() ]
5335 if isinstance( Elements, list ):
5337 raise RuntimeError("Elements empty!")
5338 if isinstance( Elements[0], int ):
5339 Elements = self.GetIDSource( Elements, SMESH.ALL )
5340 unRegister.set( Elements )
5341 if not isinstance( Elements, list ):
5342 Elements = [ Elements ]
5343 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
5344 self.mesh.SetParameters(Parameters)
5345 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
5346 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
5348 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
5350 Generate new elements by extrusion of the elements or nodes which belong to the object
5353 theObject: the object whose elements or nodes should be processed.
5354 It can be a :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`.
5355 StepVector: vector or :class:`SMESH.DirStruct` or 3 vector components, defining
5356 the direction and value of extrusion for one step (the total extrusion
5357 length will be NbOfSteps * ||StepVector||)
5358 NbOfSteps: the number of steps
5359 MakeGroups: forces the generation of new groups from existing ones
5360 IsNodes: is True if elements to extrude are nodes
5363 list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True, empty list otherwise
5364 Example: :ref:`tui_extrusion`
5368 if IsNodes: n = theObject
5369 else : e,f, = theObject,theObject
5370 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
5372 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
5374 Generate new elements by extrusion of edges which belong to the object
5377 theObject: object whose 1D elements should be processed.
5378 It can be a :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`.
5379 StepVector: vector or :class:`SMESH.DirStruct` or 3 vector components, defining
5380 the direction and value of extrusion for one step (the total extrusion
5381 length will be NbOfSteps * ||StepVector||)
5382 NbOfSteps: the number of steps
5383 MakeGroups: to generate new groups from existing ones
5386 list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True, empty list otherwise
5387 Example: :ref:`tui_extrusion`
5390 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
5392 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
5394 Generate new elements by extrusion of faces which belong to the object
5397 theObject: object whose 2D elements should be processed.
5398 It can be a :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`.
5399 StepVector: vector or :class:`SMESH.DirStruct` or 3 vector components, defining
5400 the direction and value of extrusion for one step (the total extrusion
5401 length will be NbOfSteps * ||StepVector||)
5402 NbOfSteps: the number of steps
5403 MakeGroups: forces the generation of new groups from existing ones
5406 list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True, empty list otherwise
5407 Example: :ref:`tui_extrusion`
5410 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
5412 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
5413 ExtrFlags, SewTolerance, MakeGroups=False):
5415 Generate new elements by extrusion of the elements with given ids
5418 IDsOfElements: is ids of elements
5419 StepVector: vector or :class:`SMESH.DirStruct` or 3 vector components, defining
5420 the direction and value of extrusion for one step (the total extrusion
5421 length will be NbOfSteps * ||StepVector||)
5422 NbOfSteps: the number of steps
5423 ExtrFlags: sets flags for extrusion
5424 SewTolerance: uses for comparing locations of nodes if flag
5425 EXTRUSION_FLAG_SEW is set
5426 MakeGroups: forces the generation of new groups from existing ones
5429 list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True, empty list otherwise
5432 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
5433 StepVector = self.smeshpyD.GetDirStruct(StepVector)
5434 if isinstance( StepVector, list ):
5435 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
5436 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
5437 ExtrFlags, SewTolerance, MakeGroups)
5439 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
5440 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
5441 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
5443 Generate new elements by extrusion of the given elements and nodes along the path.
5444 The path of extrusion must be a meshed edge.
5447 Nodes: nodes to extrude: a list including ids, :class:`a mesh, sub-meshes, groups or filters <SMESH.SMESH_IDSource>`
5448 Edges: edges to extrude: a list including ids, :class:`a mesh, sub-meshes, groups or filters <SMESH.SMESH_IDSource>`
5449 Faces: faces to extrude: a list including ids, :class:`a mesh, sub-meshes, groups or filters <SMESH.SMESH_IDSource>`
5450 PathMesh: 1D mesh or 1D sub-mesh, along which proceeds the extrusion
5451 PathShape: shape (edge) defines the sub-mesh of PathMesh if PathMesh
5452 contains not only path segments, else it can be None
5453 NodeStart: the first or the last node on the path. Defines the direction of extrusion
5454 HasAngles: allows the shape to be rotated around the path
5455 to get the resulting mesh in a helical fashion
5456 Angles: list of angles
5457 LinearVariation: forces the computation of rotation angles as linear
5458 variation of the given Angles along path steps
5459 HasRefPoint: allows using the reference point
5460 RefPoint: the reference point around which the shape is rotated (the mass center of the
5461 shape by default). The User can specify any point as the Reference Point.
5462 *RefPoint* can be either GEOM Vertex, [x,y,z] or :class:`SMESH.PointStruct`
5463 MakeGroups: forces the generation of new groups from existing ones
5466 list of created :class:`groups <SMESH.SMESH_GroupBase>` and
5467 :class:`error code <SMESH.SMESH_MeshEditor.Extrusion_Error>`
5468 Example: :ref:`tui_extrusion_along_path`
5471 unRegister = genObjUnRegister()
5472 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
5473 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
5474 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
5476 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
5477 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
5478 if isinstance( RefPoint, list ):
5479 if not RefPoint: RefPoint = [0,0,0]
5480 RefPoint = SMESH.PointStruct( *RefPoint )
5481 if isinstance( PathMesh, Mesh ):
5482 PathMesh = PathMesh.GetMesh()
5483 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
5484 Parameters = AnglesParameters + var_separator + RefPoint.parameters
5485 self.mesh.SetParameters(Parameters)
5486 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
5487 PathMesh, PathShape, NodeStart,
5488 HasAngles, Angles, LinearVariation,
5489 HasRefPoint, RefPoint, MakeGroups)
5491 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
5492 HasAngles=False, Angles=[], LinearVariation=False,
5493 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
5494 ElemType=SMESH.FACE):
5496 Generate new elements by extrusion of the given elements.
5497 The path of extrusion must be a meshed edge.
5500 Base: :class:`mesh, sub-mesh, group, filter <SMESH.SMESH_IDSource>`, or list of ids of elements for extrusion
5501 Path: 1D mesh or 1D sub-mesh, along which proceeds the extrusion
5502 NodeStart: the start node from Path. Defines the direction of extrusion
5503 HasAngles: allows the shape to be rotated around the path
5504 to get the resulting mesh in a helical fashion
5505 Angles: list of angles in radians
5506 LinearVariation: forces the computation of rotation angles as linear
5507 variation of the given Angles along path steps
5508 HasRefPoint: allows using the reference point
5509 RefPoint: the reference point around which the elements are rotated (the mass
5510 center of the elements by default).
5511 The User can specify any point as the Reference Point.
5512 *RefPoint* can be either GEOM Vertex, [x,y,z] or :class:`SMESH.PointStruct`
5513 MakeGroups: forces the generation of new groups from existing ones
5514 ElemType: type of elements for extrusion (if param Base is a mesh)
5517 list of created :class:`groups <SMESH.SMESH_GroupBase>` and
5518 :class:`error code <SMESH.SMESH_MeshEditor.Extrusion_Error>`
5519 if *MakeGroups* == True, only :class:`error code <SMESH.SMESH_MeshEditor.Extrusion_Error>`
5521 Example: :ref:`tui_extrusion_along_path`
5525 if ElemType == SMESH.NODE: n = Base
5526 if ElemType == SMESH.EDGE: e = Base
5527 if ElemType == SMESH.FACE: f = Base
5528 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
5529 HasAngles, Angles, LinearVariation,
5530 HasRefPoint, RefPoint, MakeGroups)
5531 if MakeGroups: return gr,er
5534 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
5535 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5536 MakeGroups=False, LinearVariation=False):
5538 Generate new elements by extrusion of the given elements.
5539 The path of extrusion must be a meshed edge.
5542 IDsOfElements: ids of elements
5543 PathMesh: mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
5544 PathShape: shape (edge) defines the sub-mesh for the path
5545 NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5546 HasAngles: allows the shape to be rotated around the path
5547 to get the resulting mesh in a helical fashion
5548 Angles: list of angles in radians
5549 HasRefPoint: allows using the reference point
5550 RefPoint: the reference point around which the shape is rotated (the mass center of the shape by default).
5551 The User can specify any point as the Reference Point.
5552 *RefPoint* can be either GEOM Vertex, [x,y,z] or :class:`SMESH.PointStruct`
5553 MakeGroups: forces the generation of new groups from existing ones
5554 LinearVariation: forces the computation of rotation angles as linear
5555 variation of the given Angles along path steps
5558 list of created :class:`groups <SMESH.SMESH_GroupBase>` and
5559 :class:`error code <SMESH.SMESH_MeshEditor.Extrusion_Error>`
5560 if *MakeGroups* == True, only :class:`error code <SMESH.SMESH_MeshEditor.Extrusion_Error>` otherwise
5561 Example: :ref:`tui_extrusion_along_path`
5564 n,e,f = [],IDsOfElements,IDsOfElements
5565 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
5566 NodeStart, HasAngles, Angles,
5568 HasRefPoint, RefPoint, MakeGroups)
5569 if MakeGroups: return gr,er
5572 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
5573 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5574 MakeGroups=False, LinearVariation=False):
5576 Generate new elements by extrusion of the elements which belong to the object.
5577 The path of extrusion must be a meshed edge.
5580 theObject: the object whose elements should be processed.
5581 It can be a :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`.
5582 PathMesh: mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
5583 PathShape: shape (edge) defines the sub-mesh for the path
5584 NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5585 HasAngles: allows the shape to be rotated around the path
5586 to get the resulting mesh in a helical fashion
5587 Angles: list of angles
5588 HasRefPoint: allows using the reference point
5589 RefPoint: the reference point around which the shape is rotated (the mass center of the shape by default).
5590 The User can specify any point as the Reference Point.
5591 *RefPoint* can be either GEOM Vertex, [x,y,z] or :class:`SMESH.PointStruct`
5592 MakeGroups: forces the generation of new groups from existing ones
5593 LinearVariation: forces the computation of rotation angles as linear
5594 variation of the given Angles along path steps
5597 list of created :class:`groups <SMESH.SMESH_GroupBase>` and
5598 :class:`error code <SMESH.SMESH_MeshEditor.Extrusion_Error>` if *MakeGroups* == True,
5599 only :class:`error code <SMESH.SMESH_MeshEditor.Extrusion_Error>` otherwise
5600 Example: :ref:`tui_extrusion_along_path`
5603 n,e,f = [],theObject,theObject
5604 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
5605 HasAngles, Angles, LinearVariation,
5606 HasRefPoint, RefPoint, MakeGroups)
5607 if MakeGroups: return gr,er
5610 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
5611 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5612 MakeGroups=False, LinearVariation=False):
5614 Generate new elements by extrusion of mesh segments which belong to the object.
5615 The path of extrusion must be a meshed edge.
5618 theObject: the object whose 1D elements should be processed.
5619 It can be a :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`.
5620 PathMesh: mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
5621 PathShape: shape (edge) defines the sub-mesh for the path
5622 NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5623 HasAngles: allows the shape to be rotated around the path
5624 to get the resulting mesh in a helical fashion
5625 Angles: list of angles
5626 HasRefPoint: allows using the reference point
5627 RefPoint: the reference point around which the shape is rotated (the mass center of the shape by default).
5628 The User can specify any point as the Reference Point.
5629 *RefPoint* can be either GEOM Vertex, [x,y,z] or :class:`SMESH.PointStruct`
5630 MakeGroups: forces the generation of new groups from existing ones
5631 LinearVariation: forces the computation of rotation angles as linear
5632 variation of the given Angles along path steps
5635 list of created :class:`groups <SMESH.SMESH_GroupBase>` and
5636 :class:`error code <SMESH.SMESH_MeshEditor.Extrusion_Error>` if *MakeGroups* == True,
5637 only :class:`error code <SMESH.SMESH_MeshEditor.Extrusion_Error>` otherwise
5638 Example: :ref:`tui_extrusion_along_path`
5641 n,e,f = [],theObject,[]
5642 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
5643 HasAngles, Angles, LinearVariation,
5644 HasRefPoint, RefPoint, MakeGroups)
5645 if MakeGroups: return gr,er
5648 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
5649 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5650 MakeGroups=False, LinearVariation=False):
5652 Generate new elements by extrusion of faces which belong to the object.
5653 The path of extrusion must be a meshed edge.
5656 theObject: the object whose 2D elements should be processed.
5657 It can be a :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`.
5658 PathMesh: mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
5659 PathShape: shape (edge) defines the sub-mesh for the path
5660 NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5661 HasAngles: allows the shape to be rotated around the path
5662 to get the resulting mesh in a helical fashion
5663 Angles: list of angles
5664 HasRefPoint: allows using the reference point
5665 RefPoint: the reference point around which the shape is rotated (the mass center of the shape by default).
5666 The User can specify any point as the Reference Point.
5667 *RefPoint* can be either GEOM Vertex, [x,y,z] or :class:`SMESH.PointStruct`
5668 MakeGroups: forces the generation of new groups from existing ones
5669 LinearVariation: forces the computation of rotation angles as linear
5670 variation of the given Angles along path steps
5673 list of created :class:`groups <SMESH.SMESH_GroupBase>` and
5674 :class:`error code <SMESH.SMESH_MeshEditor.Extrusion_Error>` if *MakeGroups* == True,
5675 only :class:`error code <SMESH.SMESH_MeshEditor.Extrusion_Error>` otherwise
5676 Example: :ref:`tui_extrusion_along_path`
5679 n,e,f = [],[],theObject
5680 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
5681 HasAngles, Angles, LinearVariation,
5682 HasRefPoint, RefPoint, MakeGroups)
5683 if MakeGroups: return gr,er
5686 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
5688 Create a symmetrical copy of mesh elements
5691 IDsOfElements: list of elements ids
5692 Mirror: is :class:`SMESH.AxisStruct` or geom object (point, line, plane)
5693 theMirrorType: smesh.POINT, smesh.AXIS or smesh.PLANE.
5694 If the *Mirror* is a geom object this parameter is unnecessary
5695 Copy: allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
5696 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5699 list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True, empty list otherwise
5702 if IDsOfElements == []:
5703 IDsOfElements = self.GetElementsId()
5704 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5705 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
5706 theMirrorType = Mirror._mirrorType
5708 self.mesh.SetParameters(Mirror.parameters)
5709 if Copy and MakeGroups:
5710 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
5711 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
5714 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
5716 Create a new mesh by a symmetrical copy of mesh elements
5719 IDsOfElements: the list of elements ids
5720 Mirror: is :class:`SMESH.AxisStruct` or geom object (point, line, plane)
5721 theMirrorType: smesh.POINT, smesh.AXIS or smesh.PLANE.
5722 If the *Mirror* is a geom object this parameter is unnecessary
5723 MakeGroups: to generate new groups from existing ones
5724 NewMeshName: a name of the new mesh to create
5727 instance of class :class:`Mesh`
5730 if IDsOfElements == []:
5731 IDsOfElements = self.GetElementsId()
5732 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5733 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
5734 theMirrorType = Mirror._mirrorType
5736 self.mesh.SetParameters(Mirror.parameters)
5737 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
5738 MakeGroups, NewMeshName)
5739 return Mesh(self.smeshpyD,self.geompyD,mesh)
5741 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
5743 Create a symmetrical copy of the object
5746 theObject: :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
5747 Mirror: :class:`SMESH.AxisStruct` or geom object (point, line, plane)
5748 theMirrorType: smesh.POINT, smesh.AXIS or smesh.PLANE.
5749 If the *Mirror* is a geom object this parameter is unnecessary
5750 Copy: allows copying the element (Copy==True) or replacing it with its mirror (Copy==False)
5751 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5754 list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True, empty list otherwise
5757 if ( isinstance( theObject, Mesh )):
5758 theObject = theObject.GetMesh()
5759 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5760 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
5761 theMirrorType = Mirror._mirrorType
5763 self.mesh.SetParameters(Mirror.parameters)
5764 if Copy and MakeGroups:
5765 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
5766 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
5769 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
5771 Create a new mesh by a symmetrical copy of the object
5774 theObject: :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
5775 Mirror: :class:`SMESH.AxisStruct` or geom object (point, line, plane)
5776 theMirrorType: smesh.POINT, smesh.AXIS or smesh.PLANE.
5777 If the *Mirror* is a geom object this parameter is unnecessary
5778 MakeGroups: forces the generation of new groups from existing ones
5779 NewMeshName: the name of the new mesh to create
5782 instance of class :class:`Mesh`
5785 if ( isinstance( theObject, Mesh )):
5786 theObject = theObject.GetMesh()
5787 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5788 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
5789 theMirrorType = Mirror._mirrorType
5791 self.mesh.SetParameters(Mirror.parameters)
5792 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
5793 MakeGroups, NewMeshName)
5794 return Mesh( self.smeshpyD,self.geompyD,mesh )
5796 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
5798 Translate the elements
5801 IDsOfElements: list of elements ids
5802 Vector: the direction of translation (:class:`SMESH.DirStruct` or vector or 3 vector components)
5803 Copy: allows copying the translated elements
5804 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5807 list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True, empty list otherwise
5810 if IDsOfElements == []:
5811 IDsOfElements = self.GetElementsId()
5812 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
5813 Vector = self.smeshpyD.GetDirStruct(Vector)
5814 if isinstance( Vector, list ):
5815 Vector = self.smeshpyD.MakeDirStruct(*Vector)
5816 self.mesh.SetParameters(Vector.PS.parameters)
5817 if Copy and MakeGroups:
5818 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
5819 self.editor.Translate(IDsOfElements, Vector, Copy)
5822 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
5824 Create a new mesh of translated elements
5827 IDsOfElements: list of elements ids
5828 Vector: the direction of translation (:class:`SMESH.DirStruct` or vector or 3 vector components)
5829 MakeGroups: forces the generation of new groups from existing ones
5830 NewMeshName: the name of the newly created mesh
5833 instance of class :class:`Mesh`
5836 if IDsOfElements == []:
5837 IDsOfElements = self.GetElementsId()
5838 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
5839 Vector = self.smeshpyD.GetDirStruct(Vector)
5840 if isinstance( Vector, list ):
5841 Vector = self.smeshpyD.MakeDirStruct(*Vector)
5842 self.mesh.SetParameters(Vector.PS.parameters)
5843 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
5844 return Mesh ( self.smeshpyD, self.geompyD, mesh )
5846 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
5848 Translate the object
5851 theObject: the object to translate (:class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`)
5852 Vector: direction of translation (:class:`SMESH.DirStruct` or geom vector or 3 vector components)
5853 Copy: allows copying the translated elements
5854 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5857 list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True, empty list otherwise
5860 if ( isinstance( theObject, Mesh )):
5861 theObject = theObject.GetMesh()
5862 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
5863 Vector = self.smeshpyD.GetDirStruct(Vector)
5864 if isinstance( Vector, list ):
5865 Vector = self.smeshpyD.MakeDirStruct(*Vector)
5866 self.mesh.SetParameters(Vector.PS.parameters)
5867 if Copy and MakeGroups:
5868 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
5869 self.editor.TranslateObject(theObject, Vector, Copy)
5872 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
5874 Create a new mesh from the translated object
5877 theObject: the object to translate (:class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`)
5878 Vector: the direction of translation (:class:`SMESH.DirStruct` or geom vector or 3 vector components)
5879 MakeGroups: forces the generation of new groups from existing ones
5880 NewMeshName: the name of the newly created mesh
5883 instance of class :class:`Mesh`
5886 if isinstance( theObject, Mesh ):
5887 theObject = theObject.GetMesh()
5888 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
5889 Vector = self.smeshpyD.GetDirStruct(Vector)
5890 if isinstance( Vector, list ):
5891 Vector = self.smeshpyD.MakeDirStruct(*Vector)
5892 self.mesh.SetParameters(Vector.PS.parameters)
5893 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
5894 return Mesh( self.smeshpyD, self.geompyD, mesh )
5898 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
5903 theObject: the object to translate (:class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`)
5904 thePoint: base point for scale (:class:`SMESH.PointStruct` or list of 3 coordinates)
5905 theScaleFact: list of 1-3 scale factors for axises
5906 Copy: allows copying the translated elements
5907 MakeGroups: forces the generation of new groups from existing
5911 list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True,
5912 empty list otherwise
5914 unRegister = genObjUnRegister()
5915 if ( isinstance( theObject, Mesh )):
5916 theObject = theObject.GetMesh()
5917 if ( isinstance( theObject, list )):
5918 theObject = self.GetIDSource(theObject, SMESH.ALL)
5919 unRegister.set( theObject )
5920 if ( isinstance( thePoint, list )):
5921 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
5922 if ( isinstance( theScaleFact, float )):
5923 theScaleFact = [theScaleFact]
5924 if ( isinstance( theScaleFact, int )):
5925 theScaleFact = [ float(theScaleFact)]
5927 self.mesh.SetParameters(thePoint.parameters)
5929 if Copy and MakeGroups:
5930 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
5931 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
5934 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
5936 Create a new mesh from the translated object
5939 theObject: the object to translate (:class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`)
5940 thePoint: base point for scale (:class:`SMESH.PointStruct` or list of 3 coordinates)
5941 theScaleFact: list of 1-3 scale factors for axises
5942 MakeGroups: forces the generation of new groups from existing ones
5943 NewMeshName: the name of the newly created mesh
5946 instance of class :class:`Mesh`
5948 unRegister = genObjUnRegister()
5949 if (isinstance(theObject, Mesh)):
5950 theObject = theObject.GetMesh()
5951 if ( isinstance( theObject, list )):
5952 theObject = self.GetIDSource(theObject,SMESH.ALL)
5953 unRegister.set( theObject )
5954 if ( isinstance( thePoint, list )):
5955 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
5956 if ( isinstance( theScaleFact, float )):
5957 theScaleFact = [theScaleFact]
5958 if ( isinstance( theScaleFact, int )):
5959 theScaleFact = [ float(theScaleFact)]
5961 self.mesh.SetParameters(thePoint.parameters)
5962 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
5963 MakeGroups, NewMeshName)
5964 return Mesh( self.smeshpyD, self.geompyD, mesh )
5968 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
5973 IDsOfElements: list of elements ids
5974 Axis: the axis of rotation (:class:`SMESH.AxisStruct` or geom line)
5975 AngleInRadians: the angle of rotation (in radians) or a name of variable which defines angle in degrees
5976 Copy: allows copying the rotated elements
5977 MakeGroups: forces the generation of new groups from existing ones (if Copy)
5980 list of created :class:`groups <SMESH.SMESH_GroupBase>` if *MakeGroups* == True, empty list otherwise
5984 if IDsOfElements == []:
5985 IDsOfElements = self.GetElementsId()
5986 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
5987 Axis = self.smeshpyD.GetAxisStruct(Axis)
5988 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
5989 Parameters = Axis.parameters + var_separator + Parameters
5990 self.mesh.SetParameters(Parameters)
5991 if Copy and MakeGroups:
5992 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
5993 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
5996 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
5998 Create a new mesh of rotated elements
6001 IDsOfElements: list of element ids
6002 Axis: the axis of rotation (:class:`SMESH.AxisStruct` or geom line)
6003 AngleInRadians: the angle of rotation (in radians) or a name of variable which defines angle in degrees
6004 MakeGroups: forces the generation of new groups from existing ones
6005 NewMeshName: the name of the newly created mesh
6008 instance of class :class:`Mesh`
6011 if IDsOfElements == []:
6012 IDsOfElements = self.GetElementsId()
6013 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
6014 Axis = self.smeshpyD.GetAxisStruct(Axis)
6015 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
6016 Parameters = Axis.parameters + var_separator + Parameters
6017 self.mesh.SetParameters(Parameters)
6018 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
6019 MakeGroups, NewMeshName)
6020 return Mesh( self.smeshpyD, self.geompyD, mesh )
6022 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
6027 theObject: the object to rotate (:class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`)
6028 Axis: the axis of rotation (:class:`SMESH.AxisStruct` or geom line)
6029 AngleInRadians: the angle of rotation (in radians) or a name of variable which defines angle in degrees
6030 Copy: allows copying the rotated elements
6031 MakeGroups: forces the generation of new groups from existing ones (if Copy)
6034 list of created :class:`groups <SMESH.SMESH_GroupBase>` if MakeGroups==True, empty list otherwise
6037 if (isinstance(theObject, Mesh)):
6038 theObject = theObject.GetMesh()
6039 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
6040 Axis = self.smeshpyD.GetAxisStruct(Axis)
6041 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
6042 Parameters = Axis.parameters + ":" + Parameters
6043 self.mesh.SetParameters(Parameters)
6044 if Copy and MakeGroups:
6045 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
6046 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
6049 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
6051 Create a new mesh from the rotated object
6054 theObject: the object to rotate (:class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`)
6055 Axis: the axis of rotation (:class:`SMESH.AxisStruct` or geom line)
6056 AngleInRadians: the angle of rotation (in radians) or a name of variable which defines angle in degrees
6057 MakeGroups: forces the generation of new groups from existing ones
6058 NewMeshName: the name of the newly created mesh
6061 instance of class :class:`Mesh`
6064 if (isinstance( theObject, Mesh )):
6065 theObject = theObject.GetMesh()
6066 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
6067 Axis = self.smeshpyD.GetAxisStruct(Axis)
6068 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
6069 Parameters = Axis.parameters + ":" + Parameters
6070 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
6071 MakeGroups, NewMeshName)
6072 self.mesh.SetParameters(Parameters)
6073 return Mesh( self.smeshpyD, self.geompyD, mesh )
6075 def Offset(self, theObject, Value, MakeGroups=False, CopyElements=False, NewMeshName=''):
6077 Create an offset mesh from the given 2D object
6080 theObject (SMESH.SMESH_IDSource): the source object (mesh, sub-mesh, group or filter)
6081 theValue (float): signed offset size
6082 MakeGroups (boolean): forces the generation of new groups from existing ones
6083 CopyElements (boolean): if *NewMeshName* is empty, True means to keep original elements,
6084 False means to remove original elements.
6085 NewMeshName (string): the name of a mesh to create. If empty, offset elements are added to this mesh
6088 A tuple (:class:`Mesh`, list of :class:`groups <SMESH.SMESH_Group>`)
6091 if isinstance( theObject, Mesh ):
6092 theObject = theObject.GetMesh()
6093 theValue,Parameters,hasVars = ParseParameters(Value)
6094 mesh_groups = self.editor.Offset(theObject, Value, MakeGroups, CopyElements, NewMeshName)
6095 self.mesh.SetParameters(Parameters)
6096 # if mesh_groups[0]:
6097 # return Mesh( self.smeshpyD, self.geompyD, mesh_groups[0] ), mesh_groups[1]
6100 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
6102 Find groups of adjacent nodes within Tolerance.
6105 Tolerance (float): the value of tolerance
6106 SeparateCornerAndMediumNodes (boolean): if *True*, in quadratic mesh puts
6107 corner and medium nodes in separate groups thus preventing
6108 their further merge.
6111 the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
6114 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
6116 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
6117 exceptNodes=[], SeparateCornerAndMediumNodes=False):
6119 Find groups of adjacent nodes within Tolerance.
6122 Tolerance: the value of tolerance
6123 SubMeshOrGroup: :class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>`
6124 exceptNodes: list of either SubMeshes, Groups or node IDs to exclude from search
6125 SeparateCornerAndMediumNodes: if *True*, in quadratic mesh puts
6126 corner and medium nodes in separate groups thus preventing
6127 their further merge.
6130 the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
6133 unRegister = genObjUnRegister()
6134 if (isinstance( SubMeshOrGroup, Mesh )):
6135 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
6136 if not isinstance( exceptNodes, list ):
6137 exceptNodes = [ exceptNodes ]
6138 if exceptNodes and isinstance( exceptNodes[0], int ):
6139 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
6140 unRegister.set( exceptNodes )
6141 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
6142 exceptNodes, SeparateCornerAndMediumNodes)
6144 def MergeNodes (self, GroupsOfNodes, NodesToKeep=[], AvoidMakingHoles=False):
6149 GroupsOfNodes: a list of groups of nodes IDs for merging.
6150 E.g. [[1,12,13],[25,4]] means that nodes 12, 13 and 4 will be removed and replaced
6151 in all elements and groups by nodes 1 and 25 correspondingly
6152 NodesToKeep: nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
6153 If *NodesToKeep* does not include a node to keep for some group to merge,
6154 then the first node in the group is kept.
6155 AvoidMakingHoles: prevent merging nodes which cause removal of elements becoming
6158 # NodesToKeep are converted to SMESH.SMESH_IDSource in meshEditor.MergeNodes()
6159 self.editor.MergeNodes( GroupsOfNodes, NodesToKeep, AvoidMakingHoles )
6161 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
6163 Find the elements built on the same nodes.
6166 MeshOrSubMeshOrGroup: :class:`mesh, sub-mesh, group or filter <SMESH.SMESH_IDSource>`
6169 the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
6172 if not MeshOrSubMeshOrGroup:
6173 MeshOrSubMeshOrGroup=self.mesh
6174 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
6175 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
6176 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
6178 def MergeElements(self, GroupsOfElementsID):
6180 Merge elements in each given group.
6183 GroupsOfElementsID: a list of groups (lists) of elements IDs for merging
6184 (e.g. [[1,12,13],[25,4]] means that elements 12, 13 and 4 will be removed and
6185 replaced in all groups by elements 1 and 25)
6188 self.editor.MergeElements(GroupsOfElementsID)
6190 def MergeEqualElements(self):
6192 Leave one element and remove all other elements built on the same nodes.
6195 self.editor.MergeEqualElements()
6197 def FindFreeBorders(self, ClosedOnly=True):
6199 Returns all or only closed free borders
6202 list of SMESH.FreeBorder's
6205 return self.editor.FindFreeBorders( ClosedOnly )
6207 def FillHole(self, holeNodes, groupName=""):
6209 Fill with 2D elements a hole defined by a SMESH.FreeBorder.
6212 holeNodes: either a SMESH.FreeBorder or a list on node IDs. These nodes
6213 must describe all sequential nodes of the hole border. The first and the last
6214 nodes must be the same. Use :meth:`FindFreeBorders` to get nodes of holes.
6215 groupName (string): name of a group to add new faces
6217 a :class:`group <SMESH.SMESH_GroupBase>` containing the new faces; or :code:`None` if `groupName` == ""
6221 if holeNodes and isinstance( holeNodes, list ) and isinstance( holeNodes[0], int ):
6222 holeNodes = SMESH.FreeBorder(nodeIDs=holeNodes)
6223 if not isinstance( holeNodes, SMESH.FreeBorder ):
6224 raise TypeError("holeNodes must be either SMESH.FreeBorder or list of integer and not %s" % holeNodes)
6225 self.editor.FillHole( holeNodes, groupName )
6227 def FindCoincidentFreeBorders (self, tolerance=0.):
6229 Return groups of FreeBorder's coincident within the given tolerance.
6232 tolerance: the tolerance. If the tolerance <= 0.0 then one tenth of an average
6233 size of elements adjacent to free borders being compared is used.
6236 SMESH.CoincidentFreeBorders structure
6239 return self.editor.FindCoincidentFreeBorders( tolerance )
6241 def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
6243 Sew FreeBorder's of each group
6246 freeBorders: either a SMESH.CoincidentFreeBorders structure or a list of lists
6247 where each enclosed list contains node IDs of a group of coincident free
6248 borders such that each consequent triple of IDs within a group describes
6249 a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
6250 last node of a border.
6251 For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
6252 groups of coincident free borders, each group including two borders.
6253 createPolygons: if :code:`True` faces adjacent to free borders are converted to
6254 polygons if a node of opposite border falls on a face edge, else such
6255 faces are split into several ones.
6256 createPolyhedra: if :code:`True` volumes adjacent to free borders are converted to
6257 polyhedra if a node of opposite border falls on a volume edge, else such
6258 volumes, if any, remain intact and the mesh becomes non-conformal.
6261 a number of successfully sewed groups
6264 if freeBorders and isinstance( freeBorders, list ):
6265 # construct SMESH.CoincidentFreeBorders
6266 if isinstance( freeBorders[0], int ):
6267 freeBorders = [freeBorders]
6269 coincidentGroups = []
6270 for nodeList in freeBorders:
6271 if not nodeList or len( nodeList ) % 3:
6272 raise ValueError("Wrong number of nodes in this group: %s" % nodeList)
6275 group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
6276 borders.append( SMESH.FreeBorder( nodeList[:3] ))
6277 nodeList = nodeList[3:]
6279 coincidentGroups.append( group )
6281 freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
6283 return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
6285 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
6286 FirstNodeID2, SecondNodeID2, LastNodeID2,
6287 CreatePolygons, CreatePolyedrs):
6292 :class:`error code <SMESH.SMESH_MeshEditor.Sew_Error>`
6295 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
6296 FirstNodeID2, SecondNodeID2, LastNodeID2,
6297 CreatePolygons, CreatePolyedrs)
6299 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
6300 FirstNodeID2, SecondNodeID2):
6302 Sew conform free borders
6305 :class:`error code <SMESH.SMESH_MeshEditor.Sew_Error>`
6308 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
6309 FirstNodeID2, SecondNodeID2)
6311 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
6312 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
6317 :class:`error code <SMESH.SMESH_MeshEditor.Sew_Error>`
6320 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
6321 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
6323 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
6324 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
6325 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
6327 Sew two sides of a mesh. The nodes belonging to Side1 are
6328 merged with the nodes of elements of Side2.
6329 The number of elements in theSide1 and in theSide2 must be
6330 equal and they should have similar nodal connectivity.
6331 The nodes to merge should belong to side borders and
6332 the first node should be linked to the second.
6335 :class:`error code <SMESH.SMESH_MeshEditor.Sew_Error>`
6338 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
6339 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
6340 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
6342 def ChangeElemNodes(self, ide, newIDs):
6344 Set new nodes for the given element.
6351 False if the number of nodes does not correspond to the type of element
6354 return self.editor.ChangeElemNodes(ide, newIDs)
6356 def GetLastCreatedNodes(self):
6358 If during the last operation of :class:`SMESH.SMESH_MeshEditor` some nodes were
6359 created, this method return the list of their IDs.
6360 If new nodes were not created - return empty list
6363 the list of integer values (can be empty)
6366 return self.editor.GetLastCreatedNodes()
6368 def GetLastCreatedElems(self):
6370 If during the last operation of :class:`SMESH.SMESH_MeshEditor` some elements were
6371 created this method return the list of their IDs.
6372 If new elements were not created - return empty list
6375 the list of integer values (can be empty)
6378 return self.editor.GetLastCreatedElems()
6380 def ClearLastCreated(self):
6382 Forget what nodes and elements were created by the last mesh edition operation
6385 self.editor.ClearLastCreated()
6387 def DoubleElements(self, theElements, theGroupName=""):
6389 Create duplicates of given elements, i.e. create new elements based on the
6390 same nodes as the given ones.
6393 theElements: container of elements to duplicate. It can be a
6394 :class:`mesh, sub-mesh, group, filter <SMESH.SMESH_IDSource>`
6395 or a list of element IDs. If *theElements* is
6396 a :class:`Mesh`, elements of highest dimension are duplicated
6397 theGroupName: a name of group to contain the generated elements.
6398 If a group with such a name already exists, the new elements
6399 are added to the existing group, else a new group is created.
6400 If *theGroupName* is empty, new elements are not added
6404 a :class:`group <SMESH.SMESH_Group>` where the new elements are added.
6405 None if *theGroupName* == "".
6408 unRegister = genObjUnRegister()
6409 if isinstance( theElements, Mesh ):
6410 theElements = theElements.mesh
6411 elif isinstance( theElements, list ):
6412 theElements = self.GetIDSource( theElements, SMESH.ALL )
6413 unRegister.set( theElements )
6414 return self.editor.DoubleElements(theElements, theGroupName)
6416 def DoubleNodes(self, theNodes, theModifiedElems):
6418 Create a hole in a mesh by doubling the nodes of some particular elements
6421 theNodes: IDs of nodes to be doubled
6422 theModifiedElems: IDs of elements to be updated by the new (doubled)
6423 nodes. If list of element identifiers is empty then nodes are doubled but
6424 they not assigned to elements
6427 True if operation has been completed successfully, False otherwise
6430 return self.editor.DoubleNodes(theNodes, theModifiedElems)
6432 def DoubleNode(self, theNodeId, theModifiedElems):
6434 Create a hole in a mesh by doubling the nodes of some particular elements.
6435 This method provided for convenience works as :meth:`DoubleNodes`.
6438 theNodeId: IDs of node to double
6439 theModifiedElems: IDs of elements to update
6442 True if operation has been completed successfully, False otherwise
6445 return self.editor.DoubleNode(theNodeId, theModifiedElems)
6447 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
6449 Create a hole in a mesh by doubling the nodes of some particular elements.
6450 This method provided for convenience works as :meth:`DoubleNodes`.
6453 theNodes: group of nodes to double.
6454 theModifiedElems: group of elements to update.
6455 theMakeGroup: forces the generation of a group containing new nodes.
6458 True or a created group if operation has been completed successfully,
6459 False or None otherwise
6463 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
6464 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
6466 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
6468 Create a hole in a mesh by doubling the nodes of some particular elements.
6469 This method provided for convenience works as :meth:`DoubleNodes`.
6472 theNodes: list of groups of nodes to double.
6473 theModifiedElems: list of groups of elements to update.
6474 theMakeGroup: forces the generation of a group containing new nodes.
6477 True if operation has been completed successfully, False otherwise
6481 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
6482 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
6484 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
6486 Create a hole in a mesh by doubling the nodes of some particular elements
6489 theElems: the list of elements (edges or faces) to replicate.
6490 The nodes for duplication could be found from these elements
6491 theNodesNot: list of nodes NOT to replicate
6492 theAffectedElems: the list of elements (cells and edges) to which the
6493 replicated nodes should be associated to
6496 True if operation has been completed successfully, False otherwise
6499 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
6501 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
6503 Create a hole in a mesh by doubling the nodes of some particular elements
6506 theElems: the list of elements (edges or faces) to replicate.
6507 The nodes for duplication could be found from these elements
6508 theNodesNot: list of nodes NOT to replicate
6509 theShape: shape to detect affected elements (element which geometric center
6510 located on or inside shape).
6511 The replicated nodes should be associated to affected elements.
6514 True if operation has been completed successfully, False otherwise
6517 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
6519 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
6520 theMakeGroup=False, theMakeNodeGroup=False):
6522 Create a hole in a mesh by doubling the nodes of some particular elements.
6523 This method provided for convenience works as :meth:`DoubleNodes`.
6526 theElems: group of of elements (edges or faces) to replicate.
6527 theNodesNot: group of nodes NOT to replicate.
6528 theAffectedElems: group of elements to which the replicated nodes
6529 should be associated to.
6530 theMakeGroup: forces the generation of a group containing new elements.
6531 theMakeNodeGroup: forces the generation of a group containing new nodes.
6534 True or created groups (one or two) if operation has been completed successfully,
6535 False or None otherwise
6538 if theMakeGroup or theMakeNodeGroup:
6539 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
6541 theMakeGroup, theMakeNodeGroup)
6542 if theMakeGroup and theMakeNodeGroup:
6545 return twoGroups[ int(theMakeNodeGroup) ]
6546 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
6548 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
6550 Create a hole in a mesh by doubling the nodes of some particular elements.
6551 This method provided for convenience works as :meth:`DoubleNodes`.
6554 theElems: group of of elements (edges or faces) to replicate
6555 theNodesNot: group of nodes not to replicate
6556 theShape: shape to detect affected elements (element which geometric center
6557 located on or inside shape).
6558 The replicated nodes should be associated to affected elements
6561 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
6563 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
6564 theMakeGroup=False, theMakeNodeGroup=False):
6566 Create a hole in a mesh by doubling the nodes of some particular elements.
6567 This method provided for convenience works as :meth:`DoubleNodes`.
6570 theElems: list of groups of elements (edges or faces) to replicate
6571 theNodesNot: list of groups of nodes NOT to replicate
6572 theAffectedElems: group of elements to which the replicated nodes
6573 should be associated to
6574 theMakeGroup: forces generation of a group containing new elements.
6575 theMakeNodeGroup: forces generation of a group containing new nodes
6578 True or created groups (one or two) if operation has been completed successfully,
6579 False or None otherwise
6582 if theMakeGroup or theMakeNodeGroup:
6583 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
6585 theMakeGroup, theMakeNodeGroup)
6586 if theMakeGroup and theMakeNodeGroup:
6589 return twoGroups[ int(theMakeNodeGroup) ]
6590 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
6592 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
6594 Create a hole in a mesh by doubling the nodes of some particular elements.
6595 This method provided for convenience works as :meth:`DoubleNodes`.
6598 theElems: list of groups of elements (edges or faces) to replicate
6599 theNodesNot: list of groups of nodes NOT to replicate
6600 theShape: shape to detect affected elements (element which geometric center
6601 located on or inside shape).
6602 The replicated nodes should be associated to affected elements
6605 True if operation has been completed successfully, False otherwise
6608 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
6610 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
6612 Identify the elements that will be affected by node duplication (actual duplication is not performed).
6613 This method is the first step of :meth:`DoubleNodeElemGroupsInRegion`.
6616 theElems: list of groups of nodes or elements (edges or faces) to replicate
6617 theNodesNot: list of groups of nodes NOT to replicate
6618 theShape: shape to detect affected elements (element which geometric center
6619 located on or inside shape).
6620 The replicated nodes should be associated to affected elements
6623 groups of affected elements in order: volumes, faces, edges
6626 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
6628 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
6631 Double nodes on shared faces between groups of volumes and create flat elements on demand.
6632 The list of groups must describe a partition of the mesh volumes.
6633 The nodes of the internal faces at the boundaries of the groups are doubled.
6634 In option, the internal faces are replaced by flat elements.
6635 Triangles are transformed to prisms, and quadrangles to hexahedrons.
6638 theDomains: list of groups of volumes
6639 createJointElems: if True, create the elements
6640 onAllBoundaries: if True, the nodes and elements are also created on
6641 the boundary between *theDomains* and the rest mesh
6644 True if operation has been completed successfully, False otherwise
6647 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
6649 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
6651 Double nodes on some external faces and create flat elements.
6652 Flat elements are mainly used by some types of mechanic calculations.
6654 Each group of the list must be constituted of faces.
6655 Triangles are transformed in prisms, and quadrangles in hexahedrons.
6658 theGroupsOfFaces: list of groups of faces
6661 True if operation has been completed successfully, False otherwise
6664 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
6666 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
6668 Identify all the elements around a geom shape, get the faces delimiting the hole
6670 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
6672 def MakePolyLine(self, segments, groupName='', isPreview=False ):
6674 Create a polyline consisting of 1D mesh elements each lying on a 2D element of
6675 the initial triangle mesh. Positions of new nodes are found by cutting the mesh by the
6676 plane passing through pairs of points specified by each :class:`SMESH.PolySegment` structure.
6677 If there are several paths connecting a pair of points, the shortest path is
6678 selected by the module. Position of the cutting plane is defined by the two
6679 points and an optional vector lying on the plane specified by a PolySegment.
6680 By default the vector is defined by Mesh module as following. A middle point
6681 of the two given points is computed. The middle point is projected to the mesh.
6682 The vector goes from the middle point to the projection point. In case of planar
6683 mesh, the vector is normal to the mesh.
6685 In preview mode, *segments* [i].vector returns the used vector which goes from the middle point to its projection.
6688 segments: list of :class:`SMESH.PolySegment` defining positions of cutting planes.
6689 groupName: optional name of a group where created mesh segments will be added.
6692 editor = self.editor
6694 editor = self.mesh.GetMeshEditPreviewer()
6695 segmentsRes = editor.MakePolyLine( segments, groupName )
6696 for i, seg in enumerate( segmentsRes ):
6697 segments[i].vector = seg.vector
6699 return editor.GetPreviewData()
6702 def GetFunctor(self, funcType ):
6704 Return a cached numerical functor by its type.
6707 funcType: functor type: an item of :class:`SMESH.FunctorType` enumeration.
6708 Note that not all items correspond to numerical functors.
6711 :class:`SMESH.NumericalFunctor`. The functor is already initialized with a mesh
6714 fn = self.functors[ funcType._v ]
6716 fn = self.smeshpyD.GetFunctor(funcType)
6717 fn.SetMesh(self.mesh)
6718 self.functors[ funcType._v ] = fn
6721 def FunctorValue(self, funcType, elemId, isElem=True):
6723 Return value of a functor for a given element
6726 funcType: an item of :class:`SMESH.FunctorType` enum.
6727 elemId: element or node ID
6728 isElem: *elemId* is ID of element or node
6731 the functor value or zero in case of invalid arguments
6734 fn = self.GetFunctor( funcType )
6735 if fn.GetElementType() == self.GetElementType(elemId, isElem):
6736 val = fn.GetValue(elemId)
6741 def GetLength(self, elemId=None):
6743 Get length of 1D element or sum of lengths of all 1D mesh elements
6746 elemId: mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
6749 element's length value if *elemId* is specified or sum of all 1D mesh elements' lengths otherwise
6754 length = self.smeshpyD.GetLength(self)
6756 length = self.FunctorValue(SMESH.FT_Length, elemId)
6759 def GetArea(self, elemId=None):
6761 Get area of 2D element or sum of areas of all 2D mesh elements
6762 elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
6765 element's area value if *elemId* is specified or sum of all 2D mesh elements' areas otherwise
6770 area = self.smeshpyD.GetArea(self)
6772 area = self.FunctorValue(SMESH.FT_Area, elemId)
6775 def GetVolume(self, elemId=None):
6777 Get volume of 3D element or sum of volumes of all 3D mesh elements
6780 elemId: mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
6783 element's volume value if *elemId* is specified or sum of all 3D mesh elements' volumes otherwise
6788 volume = self.smeshpyD.GetVolume(self)
6790 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
6793 def GetMaxElementLength(self, elemId):
6795 Get maximum element length.
6798 elemId: mesh element ID
6801 element's maximum length value
6804 if self.GetElementType(elemId, True) == SMESH.VOLUME:
6805 ftype = SMESH.FT_MaxElementLength3D
6807 ftype = SMESH.FT_MaxElementLength2D
6808 return self.FunctorValue(ftype, elemId)
6810 def GetAspectRatio(self, elemId):
6812 Get aspect ratio of 2D or 3D element.
6815 elemId: mesh element ID
6818 element's aspect ratio value
6821 if self.GetElementType(elemId, True) == SMESH.VOLUME:
6822 ftype = SMESH.FT_AspectRatio3D
6824 ftype = SMESH.FT_AspectRatio
6825 return self.FunctorValue(ftype, elemId)
6827 def GetWarping(self, elemId):
6829 Get warping angle of 2D element.
6832 elemId: mesh element ID
6835 element's warping angle value
6838 return self.FunctorValue(SMESH.FT_Warping, elemId)
6840 def GetMinimumAngle(self, elemId):
6842 Get minimum angle of 2D element.
6845 elemId: mesh element ID
6848 element's minimum angle value
6851 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
6853 def GetTaper(self, elemId):
6855 Get taper of 2D element.
6858 elemId: mesh element ID
6861 element's taper value
6864 return self.FunctorValue(SMESH.FT_Taper, elemId)
6866 def GetSkew(self, elemId):
6868 Get skew of 2D element.
6871 elemId: mesh element ID
6874 element's skew value
6877 return self.FunctorValue(SMESH.FT_Skew, elemId)
6879 def GetMinMax(self, funType, meshPart=None):
6881 Return minimal and maximal value of a given functor.
6884 funType (SMESH.FunctorType): a functor type.
6885 Note that not all items of :class:`SMESH.FunctorType` corresponds
6886 to numerical functors.
6887 meshPart: a part of mesh (:class:`sub-mesh, group or filter <SMESH.SMESH_IDSource>`) to treat
6893 unRegister = genObjUnRegister()
6894 if isinstance( meshPart, list ):
6895 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
6896 unRegister.set( meshPart )
6897 if isinstance( meshPart, Mesh ):
6898 meshPart = meshPart.mesh
6899 fun = self.GetFunctor( funType )
6902 if hasattr( meshPart, "SetMesh" ):
6903 meshPart.SetMesh( self.mesh ) # set mesh to filter
6904 hist = fun.GetLocalHistogram( 1, False, meshPart )
6906 hist = fun.GetHistogram( 1, False )
6908 return hist[0].min, hist[0].max
6911 pass # end of Mesh class
6914 class meshProxy(SMESH._objref_SMESH_Mesh):
6916 Private class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
6917 with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
6919 def __init__(self,*args):
6920 SMESH._objref_SMESH_Mesh.__init__(self,*args)
6921 def __deepcopy__(self, memo=None):
6922 new = self.__class__(self)
6924 def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
6925 if len( args ) == 3:
6926 args += SMESH.ALL_NODES, True
6927 return SMESH._objref_SMESH_Mesh.CreateDimGroup(self, *args)
6928 def ExportToMEDX(self, *args): # function removed
6929 print("WARNING: ExportToMEDX() is deprecated, use ExportMED() instead")
6930 #args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
6931 SMESH._objref_SMESH_Mesh.ExportMED(self, *args)
6932 def ExportToMED(self, *args): # function removed
6933 print("WARNING: ExportToMED() is deprecated, use ExportMED() instead")
6934 #args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
6936 while len(args2) < 5: # !!!! nb of parameters for ExportToMED IDL's method
6938 SMESH._objref_SMESH_Mesh.ExportMED(self, *args2)
6939 def ExportPartToMED(self, *args): # 'version' parameter removed
6940 #args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
6941 SMESH._objref_SMESH_Mesh.ExportPartToMED(self, *args)
6942 def ExportMED(self, *args): # signature of method changed
6943 #args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
6945 while len(args2) < 5: # !!!! nb of parameters for ExportToMED IDL's method
6947 SMESH._objref_SMESH_Mesh.ExportMED(self, *args2)
6949 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
6952 class submeshProxy(SMESH._objref_SMESH_subMesh):
6955 Private class wrapping SMESH.SMESH_SubMesh in order to add Compute()
6957 def __init__(self,*args):
6958 SMESH._objref_SMESH_subMesh.__init__(self,*args)
6960 def __deepcopy__(self, memo=None):
6961 new = self.__class__(self)
6964 def Compute(self,refresh=False):
6966 Compute the sub-mesh and return the status of the computation
6969 refresh: if *True*, Object Browser is automatically updated (when running in GUI)
6974 This is a method of SMESH.SMESH_submesh that can be obtained via Mesh.GetSubMesh() or
6975 :meth:`smeshBuilder.Mesh.GetSubMesh`.
6979 self.mesh = Mesh( smeshBuilder(), None, self.GetMesh())
6981 ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
6983 if salome.sg.hasDesktop():
6984 if refresh: salome.sg.updateObjBrowser()
6989 omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy)
6992 class meshEditor(SMESH._objref_SMESH_MeshEditor):
6994 Private class used to compensate change of CORBA API of SMESH_MeshEditor for backward
6995 compatibility with old dump scripts which call SMESH_MeshEditor directly and not via
6998 def __init__(self,*args):
6999 SMESH._objref_SMESH_MeshEditor.__init__( self, *args)
7001 def __getattr__(self, name ): # method called if an attribute not found
7002 if not self.mesh: # look for name() method in Mesh class
7003 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
7004 if hasattr( self.mesh, name ):
7005 return getattr( self.mesh, name )
7006 if name == "ExtrusionAlongPathObjX":
7007 return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
7008 print("meshEditor: attribute '%s' NOT FOUND" % name)
7010 def __deepcopy__(self, memo=None):
7011 new = self.__class__(self)
7013 def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
7014 if len( args ) == 1: args += False,
7015 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
7016 def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
7017 if len( args ) == 2: args += False,
7018 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
7019 def MergeNodes(self,*args): # 2 args added (NodesToKeep,AvoidMakingHoles)
7020 if len( args ) == 1:
7021 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [], False )
7022 NodesToKeep = args[1]
7023 AvoidMakingHoles = args[2] if len( args ) == 3 else False
7024 unRegister = genObjUnRegister()
7026 if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
7027 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
7028 if not isinstance( NodesToKeep, list ):
7029 NodesToKeep = [ NodesToKeep ]
7030 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep, AvoidMakingHoles )
7032 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
7034 class Pattern(SMESH._objref_SMESH_Pattern):
7036 Private class wrapping SMESH.SMESH_Pattern CORBA class in order to treat Notebook
7037 variables in some methods
7040 def LoadFromFile(self, patternTextOrFile ):
7041 text = patternTextOrFile
7042 if os.path.exists( text ):
7043 text = open( patternTextOrFile ).read()
7045 return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
7047 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
7048 decrFun = lambda i: i-1
7049 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
7050 theMesh.SetParameters(Parameters)
7051 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
7053 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
7054 decrFun = lambda i: i-1
7055 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
7056 theMesh.SetParameters(Parameters)
7057 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
7059 def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
7060 if isinstance( mesh, Mesh ):
7061 mesh = mesh.GetMesh()
7062 return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
7064 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
7066 Registering the new proxy for Pattern
7071 Private class used to bind methods creating algorithms to the class Mesh
7074 def __init__(self, method):
7076 self.defaultAlgoType = ""
7077 self.algoTypeToClass = {}
7078 self.method = method
7080 def add(self, algoClass):
7082 Store a python class of algorithm
7084 if inspect.isclass(algoClass) and \
7085 hasattr( algoClass, "algoType"):
7086 self.algoTypeToClass[ algoClass.algoType ] = algoClass
7087 if not self.defaultAlgoType and \
7088 hasattr( algoClass, "isDefault") and algoClass.isDefault:
7089 self.defaultAlgoType = algoClass.algoType
7090 #print("Add",algoClass.algoType, "dflt",self.defaultAlgoType)
7092 def copy(self, mesh):
7094 Create a copy of self and assign mesh to the copy
7097 other = algoCreator( self.method )
7098 other.defaultAlgoType = self.defaultAlgoType
7099 other.algoTypeToClass = self.algoTypeToClass
7103 def __call__(self,algo="",geom=0,*args):
7105 Create an instance of algorithm
7109 if isinstance( algo, str ):
7111 elif ( isinstance( algo, geomBuilder.GEOM._objref_GEOM_Object ) and \
7112 not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object )):
7117 if isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
7119 elif not algoType and isinstance( geom, str ):
7124 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ) and not shape:
7126 elif isinstance( arg, str ) and not algoType:
7129 import traceback, sys
7130 msg = "Warning. Unexpected argument in mesh.%s() ---> %s" % ( self.method, arg )
7131 sys.stderr.write( msg + '\n' )
7132 tb = traceback.extract_stack(None,2)
7133 traceback.print_list( [tb[0]] )
7135 algoType = self.defaultAlgoType
7136 if not algoType and self.algoTypeToClass:
7137 algoType = sorted( self.algoTypeToClass.keys() )[0]
7138 if algoType in self.algoTypeToClass:
7139 #print("Create algo",algoType)
7140 return self.algoTypeToClass[ algoType ]( self.mesh, shape )
7141 raise RuntimeError( "No class found for algo type %s" % algoType)
7144 class hypMethodWrapper:
7146 Private class used to substitute and store variable parameters of hypotheses.
7149 def __init__(self, hyp, method):
7151 self.method = method
7152 #print("REBIND:", method.__name__)
7155 def __call__(self,*args):
7157 call a method of hypothesis with calling SetVarParameter() before
7161 return self.method( self.hyp, *args ) # hypothesis method with no args
7163 #print("MethWrapper.__call__", self.method.__name__, args)
7165 parsed = ParseParameters(*args) # replace variables with their values
7166 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
7167 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
7168 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
7169 # maybe there is a replaced string arg which is not variable
7170 result = self.method( self.hyp, *args )
7171 except ValueError as detail: # raised by ParseParameters()
7173 result = self.method( self.hyp, *args )
7174 except omniORB.CORBA.BAD_PARAM:
7175 raise ValueError(detail) # wrong variable name
7180 class genObjUnRegister:
7182 A helper class that calls UnRegister() of SALOME.GenericObj'es stored in it
7185 def __init__(self, genObj=None):
7186 self.genObjList = []
7190 def set(self, genObj):
7191 "Store one or a list of of SALOME.GenericObj'es"
7192 if isinstance( genObj, list ):
7193 self.genObjList.extend( genObj )
7195 self.genObjList.append( genObj )
7199 for genObj in self.genObjList:
7200 if genObj and hasattr( genObj, "UnRegister" ):
7203 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
7205 Bind methods creating mesher plug-ins to the Mesh class
7208 # print("pluginName: ", pluginName)
7209 pluginBuilderName = pluginName + "Builder"
7211 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
7212 except Exception as e:
7213 from salome_utils import verbose
7214 if verbose(): print("Exception while loading %s: %s" % ( pluginBuilderName, e ))
7216 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
7217 plugin = eval( pluginBuilderName )
7218 # print(" plugin:" , str(plugin))
7220 # add methods creating algorithms to Mesh
7221 for k in dir( plugin ):
7222 if k[0] == '_': continue
7223 algo = getattr( plugin, k )
7224 #print(" algo:", str(algo))
7225 if inspect.isclass(algo) and hasattr(algo, "meshMethod"):
7226 #print(" meshMethod:" , str(algo.meshMethod))
7227 if not hasattr( Mesh, algo.meshMethod ):
7228 setattr( Mesh, algo.meshMethod, algoCreator( algo.meshMethod ))
7230 _mmethod = getattr( Mesh, algo.meshMethod )
7231 if hasattr( _mmethod, "add" ):