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
23 ## @package smeshBuilder
24 # Python API for SALOME %Mesh module
26 ## @defgroup l1_auxiliary Auxiliary methods and structures
27 ## @defgroup l1_creating Creating meshes
29 ## @defgroup l2_impexp Importing and exporting meshes
32 ## These are methods of class \ref smeshBuilder.smeshBuilder "smeshBuilder"
34 ## @defgroup l2_construct Constructing meshes
35 ## @defgroup l2_algorithms Defining Algorithms
37 ## @defgroup l3_algos_basic Basic meshing algorithms
38 ## @defgroup l3_algos_proj Projection Algorithms
39 ## @defgroup l3_algos_segmarv Segments around Vertex
40 ## @defgroup l3_algos_3dextr 3D extrusion meshing algorithm
43 ## @defgroup l2_hypotheses Defining hypotheses
45 ## @defgroup l3_hypos_1dhyps 1D Meshing Hypotheses
46 ## @defgroup l3_hypos_2dhyps 2D Meshing Hypotheses
47 ## @defgroup l3_hypos_maxvol Max Element Volume hypothesis
48 ## @defgroup l3_hypos_quad Quadrangle Parameters hypothesis
49 ## @defgroup l3_hypos_additi Additional Hypotheses
52 ## @defgroup l2_submeshes Constructing sub-meshes
53 ## @defgroup l2_editing Editing Meshes
56 ## @defgroup l1_meshinfo Mesh Information
57 ## @defgroup l1_controls Quality controls and Filtering
58 ## @defgroup l1_grouping Grouping elements
60 ## @defgroup l2_grps_create Creating groups
61 ## @defgroup l2_grps_operon Using operations on groups
62 ## @defgroup l2_grps_delete Deleting Groups
65 ## @defgroup l1_modifying Modifying meshes
67 ## @defgroup l2_modif_add Adding nodes and elements
68 ## @defgroup l2_modif_del Removing nodes and elements
69 ## @defgroup l2_modif_edit Modifying nodes and elements
70 ## @defgroup l2_modif_renumber Renumbering nodes and elements
71 ## @defgroup l2_modif_trsf Transforming meshes (Translation, Rotation, Symmetry, Sewing, Merging)
72 ## @defgroup l2_modif_unitetri Uniting triangles
73 ## @defgroup l2_modif_cutquadr Cutting elements
74 ## @defgroup l2_modif_changori Changing orientation of elements
75 ## @defgroup l2_modif_smooth Smoothing
76 ## @defgroup l2_modif_extrurev Extrusion and Revolution
77 ## @defgroup l2_modif_tofromqu Convert to/from Quadratic Mesh
78 ## @defgroup l2_modif_duplicat Duplication of nodes and elements (to emulate cracks)
81 ## @defgroup l1_measurements Measurements
84 from salome.geom import geomBuilder
86 import SMESH # This is necessary for back compatibility
87 import omniORB # back compatibility
88 SMESH.MED_V2_1 = omniORB.EnumItem("MED_V2_1", 0) # back compatibility
89 SMESH.MED_V2_2 = omniORB.EnumItem("MED_V2_2", 1) # back compatibility
92 from salome.smesh.smesh_algorithm import Mesh_Algorithm
99 # In case the omniORBpy EnumItem class does not fully support Python 3
100 # (for instance in version 4.2.1-2), the comparison ordering methods must be
104 SMESH.Entity_Triangle < SMESH.Entity_Quadrangle
106 def enumitem_eq(self, other):
108 if isinstance(other, omniORB.EnumItem):
109 if other._parent_id == self._parent_id:
110 return self._v == other._v
112 return self._parent_id == other._parent_id
114 return id(self) == id(other)
116 return id(self) == id(other)
118 def enumitem_lt(self, other):
120 if isinstance(other, omniORB.EnumItem):
121 if other._parent_id == self._parent_id:
122 return self._v < other._v
124 return self._parent_id < other._parent_id
126 return id(self) < id(other)
128 return id(self) < id(other)
130 def enumitem_le(self, other):
132 if isinstance(other, omniORB.EnumItem):
133 if other._parent_id == self._parent_id:
134 return self._v <= other._v
136 return self._parent_id <= other._parent_id
138 return id(self) <= id(other)
140 return id(self) <= id(other)
142 def enumitem_gt(self, other):
144 if isinstance(other, omniORB.EnumItem):
145 if other._parent_id == self._parent_id:
146 return self._v > other._v
148 return self._parent_id > other._parent_id
150 return id(self) > id(other)
152 return id(self) > id(other)
154 def enumitem_ge(self, other):
156 if isinstance(other, omniORB.EnumItem):
157 if other._parent_id == self._parent_id:
158 return self._v >= other._v
160 return self._parent_id >= other._parent_id
162 return id(self) >= id(other)
164 return id(self) >= id(other)
166 omniORB.EnumItem.__eq__ = enumitem_eq
167 omniORB.EnumItem.__lt__ = enumitem_lt
168 omniORB.EnumItem.__le__ = enumitem_le
169 omniORB.EnumItem.__gt__ = enumitem_gt
170 omniORB.EnumItem.__ge__ = enumitem_ge
173 ## Private class used to workaround a problem that sometimes isinstance(m, Mesh) returns False
175 class MeshMeta(type):
176 def __instancecheck__(cls, inst):
177 """Implement isinstance(inst, cls)."""
178 return any(cls.__subclasscheck__(c)
179 for c in {type(inst), inst.__class__})
181 def __subclasscheck__(cls, sub):
182 """Implement issubclass(sub, cls)."""
183 return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
185 ## @addtogroup l1_auxiliary
188 ## Convert an angle from degrees to radians
189 def DegreesToRadians(AngleInDegrees):
191 return AngleInDegrees * pi / 180.0
193 import salome_notebook
194 notebook = salome_notebook.notebook
195 # Salome notebook variable separator
198 ## Return list of variable values from salome notebook.
199 # The last argument, if is callable, is used to modify values got from notebook
200 def ParseParameters(*args):
205 if args and callable(args[-1]):
206 args, varModifFun = args[:-1], args[-1]
207 for parameter in args:
209 Parameters += str(parameter) + var_separator
211 if isinstance(parameter,str):
212 # check if there is an inexistent variable name
213 if not notebook.isVariable(parameter):
214 raise ValueError("Variable with name '" + parameter + "' doesn't exist!!!")
215 parameter = notebook.get(parameter)
218 parameter = varModifFun(parameter)
221 Result.append(parameter)
224 Parameters = Parameters[:-1]
225 Result.append( Parameters )
226 Result.append( hasVariables )
229 ## Parse parameters while converting variables to radians
230 def ParseAngles(*args):
231 return ParseParameters( *( args + (DegreesToRadians, )))
233 ## Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
234 # Parameters are stored in PointStruct.parameters attribute
235 def __initPointStruct(point,*args):
236 point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
238 SMESH.PointStruct.__init__ = __initPointStruct
240 ## Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
241 # Parameters are stored in AxisStruct.parameters attribute
242 def __initAxisStruct(ax,*args):
244 raise RuntimeError("Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args )))
245 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
247 SMESH.AxisStruct.__init__ = __initAxisStruct
249 smeshPrecisionConfusion = 1.e-07
250 ## Compare real values using smeshPrecisionConfusion as tolerance
251 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
252 if abs(val1 - val2) < tol:
258 ## Return object name
262 if isinstance(obj, SALOMEDS._objref_SObject):
266 ior = salome.orb.object_to_string(obj)
270 sobj = salome.myStudy.FindObjectIOR(ior)
272 return sobj.GetName()
273 if hasattr(obj, "GetName"):
274 # unknown CORBA object, having GetName() method
277 # unknown CORBA object, no GetName() method
280 if hasattr(obj, "GetName"):
281 # unknown non-CORBA object, having GetName() method
284 raise RuntimeError("Null or invalid object")
286 ## Print error message if a hypothesis was not assigned.
287 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
289 hypType = "algorithm"
291 hypType = "hypothesis"
294 if hasattr( status, "__getitem__" ):
295 status, reason = status[0], status[1]
296 if status == HYP_UNKNOWN_FATAL:
297 reason = "for unknown reason"
298 elif status == HYP_INCOMPATIBLE:
299 reason = "this hypothesis mismatches the algorithm"
300 elif status == HYP_NOTCONFORM:
301 reason = "a non-conform mesh would be built"
302 elif status == HYP_ALREADY_EXIST:
303 if isAlgo: return # it does not influence anything
304 reason = hypType + " of the same dimension is already assigned to this shape"
305 elif status == HYP_BAD_DIM:
306 reason = hypType + " mismatches the shape"
307 elif status == HYP_CONCURENT:
308 reason = "there are concurrent hypotheses on sub-shapes"
309 elif status == HYP_BAD_SUBSHAPE:
310 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
311 elif status == HYP_BAD_GEOMETRY:
312 reason = "the algorithm is not applicable to this geometry"
313 elif status == HYP_HIDDEN_ALGO:
314 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
315 elif status == HYP_HIDING_ALGO:
316 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
317 elif status == HYP_NEED_SHAPE:
318 reason = "algorithm can't work without shape"
319 elif status == HYP_INCOMPAT_HYPS:
325 where = '"%s"' % geomName
327 meshName = GetName( mesh )
328 if meshName and meshName != NO_NAME:
329 where = '"%s" shape in "%s" mesh ' % ( geomName, meshName )
330 if status < HYP_UNKNOWN_FATAL and where:
331 print('"%s" was assigned to %s but %s' %( hypName, where, reason ))
333 print('"%s" was not assigned to %s : %s' %( hypName, where, reason ))
335 print('"%s" was not assigned : %s' %( hypName, reason ))
338 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
339 def AssureGeomPublished(mesh, geom, name=''):
340 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
342 if not geom.GetStudyEntry():
344 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
345 # for all groups SubShapeName() return "Compound_-1"
346 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
348 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
350 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
353 ## Return the first vertex of a geometrical edge by ignoring orientation
354 def FirstVertexOnCurve(mesh, edge):
355 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
357 raise TypeError("Given object has no vertices")
358 if len( vv ) == 1: return vv[0]
359 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
360 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
361 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
362 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
365 dist1 += abs( xyz[i] - xyz1[i] )
366 dist2 += abs( xyz[i] - xyz2[i] )
372 ## Return a long value from enumeration
373 def EnumToLong(theItem):
376 # end of l1_auxiliary
380 # Warning: smeshInst is a singleton
386 ## This class allows to create, load or manipulate meshes.
387 # It has a set of methods to create, load or copy meshes, to combine several meshes, etc.
388 # It also has methods to get infos and measure meshes.
389 class smeshBuilder(SMESH._objref_SMESH_Gen):
391 # MirrorType enumeration
392 POINT = SMESH_MeshEditor.POINT
393 AXIS = SMESH_MeshEditor.AXIS
394 PLANE = SMESH_MeshEditor.PLANE
396 # Smooth_Method enumeration
397 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
398 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
400 PrecisionConfusion = smeshPrecisionConfusion
402 # TopAbs_State enumeration
403 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = list(range(4))
405 # Methods of splitting a hexahedron into tetrahedra
406 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
408 def __new__(cls, *args):
412 #print "==== __new__", engine, smeshInst, doLcc
414 if smeshInst is None:
415 # smesh engine is either retrieved from engine, or created
417 # Following test avoids a recursive loop
419 if smeshInst is not None:
420 # smesh engine not created: existing engine found
424 # FindOrLoadComponent called:
425 # 1. CORBA resolution of server
426 # 2. the __new__ method is called again
427 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
428 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
430 # FindOrLoadComponent not called
431 if smeshInst is None:
432 # smeshBuilder instance is created from lcc.FindOrLoadComponent
433 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
434 smeshInst = super(smeshBuilder,cls).__new__(cls)
436 # smesh engine not created: existing engine found
437 #print "==== existing ", engine, smeshInst, doLcc
439 #print "====1 ", smeshInst
442 #print "====2 ", smeshInst
445 def __init__(self, *args):
447 #print "--------------- smeshbuilder __init__ ---", created
450 SMESH._objref_SMESH_Gen.__init__(self, *args)
452 ## Dump component to the Python script
453 # This method overrides IDL function to allow default values for the parameters.
454 # @ingroup l1_auxiliary
455 def DumpPython(self, theIsPublished=True, theIsMultiFile=True):
456 return SMESH._objref_SMESH_Gen.DumpPython(self, theIsPublished, theIsMultiFile)
458 ## Set mode of DumpPython(), \a historical or \a snapshot.
459 # In the \a historical mode, the Python Dump script includes all commands
460 # performed by SMESH engine. In the \a snapshot mode, commands
461 # relating to objects removed from the Study are excluded from the script
462 # as well as commands not influencing the current state of meshes
463 # @ingroup l1_auxiliary
464 def SetDumpPythonHistorical(self, isHistorical):
465 if isHistorical: val = "true"
467 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
469 ## Set Geometry component
470 # @ingroup l1_auxiliary
471 def init_smesh(self,isPublished = True,geompyD = None):
473 self.UpdateStudy(geompyD)
476 notebook.myStudy = salome.myStudy
478 ## Create a mesh. This can be either an empty mesh, possibly having an underlying geometry,
479 # or a mesh wrapping a CORBA mesh given as a parameter.
480 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
481 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
482 # (2) a Geometrical object for meshing or
484 # @param name the name for the new mesh.
485 # @return an instance of Mesh class.
486 # @ingroup l2_construct
487 def Mesh(self, obj=0, name=0):
488 if isinstance(obj,str):
490 return Mesh(self,self.geompyD,obj,name)
492 ## Return a string representation of the color.
493 # To be used with filters.
494 # @param c color value (SALOMEDS.Color)
495 # @ingroup l1_auxiliary
496 def ColorToString(self,c):
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 ## Get PointStruct from vertex
507 # @param theVertex a GEOM object(vertex)
508 # @return SMESH.PointStruct
509 # @ingroup l1_auxiliary
510 def GetPointStruct(self,theVertex):
511 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
512 return PointStruct(x,y,z)
514 ## Get DirStruct from vector
515 # @param theVector a GEOM object(vector)
516 # @return SMESH.DirStruct
517 # @ingroup l1_auxiliary
518 def GetDirStruct(self,theVector):
519 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
520 if(len(vertices) != 2):
521 print("Error: vector object is incorrect.")
523 p1 = self.geompyD.PointCoordinates(vertices[0])
524 p2 = self.geompyD.PointCoordinates(vertices[1])
525 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
526 dirst = DirStruct(pnt)
529 ## Make DirStruct from a triplet
530 # @param x,y,z vector components
531 # @return SMESH.DirStruct
532 # @ingroup l1_auxiliary
533 def MakeDirStruct(self,x,y,z):
534 pnt = PointStruct(x,y,z)
535 return DirStruct(pnt)
537 ## Get AxisStruct from object
538 # @param theObj a GEOM object (line or plane)
539 # @return SMESH.AxisStruct
540 # @ingroup l1_auxiliary
541 def GetAxisStruct(self,theObj):
543 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
546 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
547 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
548 vertex1 = self.geompyD.PointCoordinates(vertex1)
549 vertex2 = self.geompyD.PointCoordinates(vertex2)
550 vertex3 = self.geompyD.PointCoordinates(vertex3)
551 vertex4 = self.geompyD.PointCoordinates(vertex4)
552 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
553 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
554 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] ]
555 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
556 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
557 elif len(edges) == 1:
558 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
559 p1 = self.geompyD.PointCoordinates( vertex1 )
560 p2 = self.geompyD.PointCoordinates( vertex2 )
561 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
562 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
563 elif theObj.GetShapeType() == GEOM.VERTEX:
564 x,y,z = self.geompyD.PointCoordinates( theObj )
565 axis = AxisStruct( x,y,z, 1,0,0,)
566 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
569 # From SMESH_Gen interface:
570 # ------------------------
572 ## Set the given name to the object
573 # @param obj the object to rename
574 # @param name a new object name
575 # @ingroup l1_auxiliary
576 def SetName(self, obj, name):
577 if isinstance( obj, Mesh ):
579 elif isinstance( obj, Mesh_Algorithm ):
580 obj = obj.GetAlgorithm()
581 ior = salome.orb.object_to_string(obj)
582 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
584 ## Set the current mode
585 # @ingroup l1_auxiliary
586 def SetEmbeddedMode( self,theMode ):
587 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
589 ## Get the current mode
590 # @ingroup l1_auxiliary
591 def IsEmbeddedMode(self):
592 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
594 ## Update the current study. Calling UpdateStudy() allows to
595 # update meshes at switching GEOM->SMESH
596 # @ingroup l1_auxiliary
597 def UpdateStudy( self, geompyD = None ):
600 from salome.geom import geomBuilder
601 geompyD = geomBuilder.geom
604 self.SetGeomEngine(geompyD)
605 SMESH._objref_SMESH_Gen.UpdateStudy(self)
606 sb = salome.myStudy.NewBuilder()
607 sc = salome.myStudy.FindComponent("SMESH")
608 if sc: sb.LoadWith(sc, self)
611 ## Sets enable publishing in the study. Calling SetEnablePublish( false ) allows to
612 # switch OFF publishing in the Study of mesh objects.
613 # @ingroup l1_auxiliary
614 def SetEnablePublish( self, theIsEnablePublish ):
615 #self.SetEnablePublish(theIsEnablePublish)
616 SMESH._objref_SMESH_Gen.SetEnablePublish(self,theIsEnablePublish)
618 notebook = salome_notebook.NoteBook( theIsEnablePublish )
620 ## Create a Mesh object importing data from the given UNV file
621 # @return an instance of Mesh class
623 def CreateMeshesFromUNV( self,theFileName ):
624 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
625 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
628 ## Create a Mesh object(s) importing data from the given MED file
629 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
631 def CreateMeshesFromMED( self,theFileName ):
632 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
633 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
634 return aMeshes, aStatus
636 ## Create a Mesh object(s) importing data from the given SAUV file
637 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
639 def CreateMeshesFromSAUV( self,theFileName ):
640 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
641 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
642 return aMeshes, aStatus
644 ## Create a Mesh object importing data from the given STL file
645 # @return an instance of Mesh class
647 def CreateMeshesFromSTL( self, theFileName ):
648 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
649 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
652 ## Create Mesh objects importing data from the given CGNS file
653 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
655 def CreateMeshesFromCGNS( self, theFileName ):
656 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
657 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
658 return aMeshes, aStatus
660 ## Create a Mesh object importing data from the given GMF file.
661 # GMF files must have .mesh extension for the ASCII format and .meshb for
663 # @return [ an instance of Mesh class, SMESH.ComputeError ]
665 def CreateMeshesFromGMF( self, theFileName ):
666 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
669 if error.comment: print("*** CreateMeshesFromGMF() errors:\n", error.comment)
670 return Mesh(self, self.geompyD, aSmeshMesh), error
672 ## Concatenate the given meshes into one mesh. All groups of input meshes will be
673 # present in the new mesh.
674 # @param meshes the meshes, sub-meshes and groups to combine into one mesh
675 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
676 # @param mergeNodesAndElements if true, equal nodes and elements are merged
677 # @param mergeTolerance tolerance for merging nodes
678 # @param allGroups forces creation of groups corresponding to every input mesh
679 # @param name name of a new mesh
680 # @return an instance of Mesh class
681 # @ingroup l1_creating
682 def Concatenate( self, meshes, uniteIdenticalGroups,
683 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
685 if not meshes: return None
686 for i,m in enumerate(meshes):
687 if isinstance(m, Mesh):
688 meshes[i] = m.GetMesh()
689 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
690 meshes[0].SetParameters(Parameters)
692 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
693 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
695 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
696 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
697 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
700 ## Create a mesh by copying a part of another mesh.
701 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
702 # to copy nodes or elements not contained in any mesh object,
703 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
704 # @param meshName a name of the new mesh
705 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
706 # @param toKeepIDs to preserve order of the copied elements or not
707 # @return an instance of Mesh class
708 # @ingroup l1_creating
709 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
710 if (isinstance( meshPart, Mesh )):
711 meshPart = meshPart.GetMesh()
712 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
713 return Mesh(self, self.geompyD, mesh)
715 ## Return IDs of sub-shapes
716 # @return the list of integer values
717 # @ingroup l1_auxiliary
718 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
719 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
721 ## Create a pattern mapper.
722 # @return an instance of SMESH_Pattern
724 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
725 # @ingroup l1_modifying
726 def GetPattern(self):
727 return SMESH._objref_SMESH_Gen.GetPattern(self)
729 ## Set number of segments per diagonal of boundary box of geometry, by which
730 # default segment length of appropriate 1D hypotheses is defined in GUI.
731 # Default value is 10.
732 # @ingroup l1_auxiliary
733 def SetBoundaryBoxSegmentation(self, nbSegments):
734 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
736 # Filtering. Auxiliary functions:
737 # ------------------------------
739 ## Create an empty criterion
740 # @return SMESH.Filter.Criterion
741 # @ingroup l1_controls
742 def GetEmptyCriterion(self):
743 Type = EnumToLong(FT_Undefined)
744 Compare = EnumToLong(FT_Undefined)
748 UnaryOp = EnumToLong(FT_Undefined)
749 BinaryOp = EnumToLong(FT_Undefined)
752 Precision = -1 ##@1e-07
753 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
754 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
756 ## Create a criterion by the given parameters
757 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
758 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
759 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
760 # Type SMESH.FunctorType._items in the Python Console to see all values.
761 # Note that the items starting from FT_LessThan are not suitable for CritType.
762 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
763 # @param Threshold the threshold value (range of ids as string, shape, numeric)
764 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
765 # @param BinaryOp a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or
767 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
768 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
769 # @return SMESH.Filter.Criterion
771 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
772 # @ingroup l1_controls
773 def GetCriterion(self,elementType,
775 Compare = FT_EqualTo,
777 UnaryOp=FT_Undefined,
778 BinaryOp=FT_Undefined,
780 if not CritType in SMESH.FunctorType._items:
781 raise TypeError("CritType should be of SMESH.FunctorType")
782 aCriterion = self.GetEmptyCriterion()
783 aCriterion.TypeOfElement = elementType
784 aCriterion.Type = EnumToLong(CritType)
785 aCriterion.Tolerance = Tolerance
787 aThreshold = Threshold
789 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
790 aCriterion.Compare = EnumToLong(Compare)
791 elif Compare == "=" or Compare == "==":
792 aCriterion.Compare = EnumToLong(FT_EqualTo)
794 aCriterion.Compare = EnumToLong(FT_LessThan)
796 aCriterion.Compare = EnumToLong(FT_MoreThan)
797 elif Compare != FT_Undefined:
798 aCriterion.Compare = EnumToLong(FT_EqualTo)
801 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
802 FT_BelongToCylinder, FT_LyingOnGeom]:
803 # Check that Threshold is GEOM object
804 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
805 aCriterion.ThresholdStr = GetName(aThreshold)
806 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
807 if not aCriterion.ThresholdID:
808 name = aCriterion.ThresholdStr
810 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
811 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
812 # or a name of GEOM object
813 elif isinstance( aThreshold, str ):
814 aCriterion.ThresholdStr = aThreshold
816 raise TypeError("The Threshold should be a shape.")
817 if isinstance(UnaryOp,float):
818 aCriterion.Tolerance = UnaryOp
819 UnaryOp = FT_Undefined
821 elif CritType == FT_BelongToMeshGroup:
822 # Check that Threshold is a group
823 if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
824 if aThreshold.GetType() != elementType:
825 raise ValueError("Group type mismatches Element type")
826 aCriterion.ThresholdStr = aThreshold.GetName()
827 aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
828 study = salome.myStudy
830 so = study.FindObjectIOR( aCriterion.ThresholdID )
834 aCriterion.ThresholdID = entry
836 raise TypeError("The Threshold should be a Mesh Group")
837 elif CritType == FT_RangeOfIds:
838 # Check that Threshold is string
839 if isinstance(aThreshold, str):
840 aCriterion.ThresholdStr = aThreshold
842 raise TypeError("The Threshold should be a string.")
843 elif CritType == FT_CoplanarFaces:
844 # Check the Threshold
845 if isinstance(aThreshold, int):
846 aCriterion.ThresholdID = str(aThreshold)
847 elif isinstance(aThreshold, str):
850 raise ValueError("Invalid ID of mesh face: '%s'"%aThreshold)
851 aCriterion.ThresholdID = aThreshold
853 raise TypeError("The Threshold should be an ID of mesh face and not '%s'"%aThreshold)
854 elif CritType == FT_ConnectedElements:
855 # Check the Threshold
856 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
857 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
858 if not aCriterion.ThresholdID:
859 name = aThreshold.GetName()
861 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
862 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
863 elif isinstance(aThreshold, int): # node id
864 aCriterion.Threshold = aThreshold
865 elif isinstance(aThreshold, list): # 3 point coordinates
866 if len( aThreshold ) < 3:
867 raise ValueError("too few point coordinates, must be 3")
868 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
869 elif isinstance(aThreshold, str):
870 if aThreshold.isdigit():
871 aCriterion.Threshold = aThreshold # node id
873 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
875 raise TypeError("The Threshold should either a VERTEX, or a node ID, "\
876 "or a list of point coordinates and not '%s'"%aThreshold)
877 elif CritType == FT_ElemGeomType:
878 # Check the Threshold
880 aCriterion.Threshold = EnumToLong(aThreshold)
881 assert( aThreshold in SMESH.GeometryType._items )
883 if isinstance(aThreshold, int):
884 aCriterion.Threshold = aThreshold
886 raise TypeError("The Threshold should be an integer or SMESH.GeometryType.")
889 elif CritType == FT_EntityType:
890 # Check the Threshold
892 aCriterion.Threshold = EnumToLong(aThreshold)
893 assert( aThreshold in SMESH.EntityType._items )
895 if isinstance(aThreshold, int):
896 aCriterion.Threshold = aThreshold
898 raise TypeError("The Threshold should be an integer or SMESH.EntityType.")
902 elif CritType == FT_GroupColor:
903 # Check the Threshold
905 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
907 raise TypeError("The threshold value should be of SALOMEDS.Color type")
909 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
910 FT_LinearOrQuadratic, FT_BadOrientedVolume,
911 FT_BareBorderFace, FT_BareBorderVolume,
912 FT_OverConstrainedFace, FT_OverConstrainedVolume,
913 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
914 # At this point the Threshold is unnecessary
915 if aThreshold == FT_LogicalNOT:
916 aCriterion.UnaryOp = EnumToLong(FT_LogicalNOT)
917 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
918 aCriterion.BinaryOp = aThreshold
922 aThreshold = float(aThreshold)
923 aCriterion.Threshold = aThreshold
925 raise TypeError("The Threshold should be a number.")
928 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
929 aCriterion.UnaryOp = EnumToLong(FT_LogicalNOT)
931 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
932 aCriterion.BinaryOp = EnumToLong(Threshold)
934 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
935 aCriterion.BinaryOp = EnumToLong(UnaryOp)
937 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
938 aCriterion.BinaryOp = EnumToLong(BinaryOp)
942 ## Create a filter with the given parameters
943 # @param elementType the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
944 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
945 # Type SMESH.FunctorType._items in the Python Console to see all values.
946 # Note that the items starting from FT_LessThan are not suitable for CritType.
947 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
948 # @param Threshold the threshold value (range of ids as string, shape, numeric)
949 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
950 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
951 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
952 # @param mesh the mesh to initialize the filter with
953 # @return SMESH_Filter
955 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
956 # @ingroup l1_controls
957 def GetFilter(self,elementType,
958 CritType=FT_Undefined,
961 UnaryOp=FT_Undefined,
964 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
965 aFilterMgr = self.CreateFilterManager()
966 aFilter = aFilterMgr.CreateFilter()
968 aCriteria.append(aCriterion)
969 aFilter.SetCriteria(aCriteria)
971 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
972 else : aFilter.SetMesh( mesh )
973 aFilterMgr.UnRegister()
976 ## Create a filter from criteria
977 # @param criteria a list of criteria
978 # @param binOp binary operator used when binary operator of criteria is undefined
979 # @return SMESH_Filter
981 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
982 # @ingroup l1_controls
983 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
984 for i in range( len( criteria ) - 1 ):
985 if criteria[i].BinaryOp == EnumToLong( SMESH.FT_Undefined ):
986 criteria[i].BinaryOp = EnumToLong( binOp )
987 aFilterMgr = self.CreateFilterManager()
988 aFilter = aFilterMgr.CreateFilter()
989 aFilter.SetCriteria(criteria)
990 aFilterMgr.UnRegister()
993 ## Create a numerical functor by its type
994 # @param theCriterion functor type - an item of SMESH.FunctorType enumeration.
995 # Type SMESH.FunctorType._items in the Python Console to see all items.
996 # Note that not all items correspond to numerical functors.
997 # @return SMESH_NumericalFunctor
998 # @ingroup l1_controls
999 def GetFunctor(self,theCriterion):
1000 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
1002 aFilterMgr = self.CreateFilterManager()
1004 if theCriterion == FT_AspectRatio:
1005 functor = aFilterMgr.CreateAspectRatio()
1006 elif theCriterion == FT_AspectRatio3D:
1007 functor = aFilterMgr.CreateAspectRatio3D()
1008 elif theCriterion == FT_Warping:
1009 functor = aFilterMgr.CreateWarping()
1010 elif theCriterion == FT_MinimumAngle:
1011 functor = aFilterMgr.CreateMinimumAngle()
1012 elif theCriterion == FT_Taper:
1013 functor = aFilterMgr.CreateTaper()
1014 elif theCriterion == FT_Skew:
1015 functor = aFilterMgr.CreateSkew()
1016 elif theCriterion == FT_Area:
1017 functor = aFilterMgr.CreateArea()
1018 elif theCriterion == FT_Volume3D:
1019 functor = aFilterMgr.CreateVolume3D()
1020 elif theCriterion == FT_MaxElementLength2D:
1021 functor = aFilterMgr.CreateMaxElementLength2D()
1022 elif theCriterion == FT_MaxElementLength3D:
1023 functor = aFilterMgr.CreateMaxElementLength3D()
1024 elif theCriterion == FT_MultiConnection:
1025 functor = aFilterMgr.CreateMultiConnection()
1026 elif theCriterion == FT_MultiConnection2D:
1027 functor = aFilterMgr.CreateMultiConnection2D()
1028 elif theCriterion == FT_Length:
1029 functor = aFilterMgr.CreateLength()
1030 elif theCriterion == FT_Length2D:
1031 functor = aFilterMgr.CreateLength2D()
1032 elif theCriterion == FT_Deflection2D:
1033 functor = aFilterMgr.CreateDeflection2D()
1034 elif theCriterion == FT_NodeConnectivityNumber:
1035 functor = aFilterMgr.CreateNodeConnectivityNumber()
1036 elif theCriterion == FT_BallDiameter:
1037 functor = aFilterMgr.CreateBallDiameter()
1039 print("Error: given parameter is not numerical functor type.")
1040 aFilterMgr.UnRegister()
1043 ## Create hypothesis
1044 # @param theHType mesh hypothesis type (string)
1045 # @param theLibName mesh plug-in library name
1046 # @return created hypothesis instance
1047 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
1048 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
1050 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
1053 # wrap hypothesis methods
1054 #print "HYPOTHESIS", theHType
1055 for meth_name in dir( hyp.__class__ ):
1056 if not meth_name.startswith("Get") and \
1057 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
1058 method = getattr ( hyp.__class__, meth_name )
1059 if callable(method):
1060 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
1064 ## Get the mesh statistic
1065 # @return dictionary "element type" - "count of elements"
1066 # @ingroup l1_meshinfo
1067 def GetMeshInfo(self, obj):
1068 if isinstance( obj, Mesh ):
1071 if hasattr(obj, "GetMeshInfo"):
1072 values = obj.GetMeshInfo()
1073 for i in range(EnumToLong(SMESH.Entity_Last)):
1074 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1078 ## Get minimum distance between two objects
1080 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1081 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1083 # @param src1 first source object
1084 # @param src2 second source object
1085 # @param id1 node/element id from the first source
1086 # @param id2 node/element id from the second (or first) source
1087 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1088 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1089 # @return minimum distance value
1090 # @sa GetMinDistance()
1091 # @ingroup l1_measurements
1092 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1093 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1097 result = result.value
1100 ## Get measure structure specifying minimum distance data between two objects
1102 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1103 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1105 # @param src1 first source object
1106 # @param src2 second source object
1107 # @param id1 node/element id from the first source
1108 # @param id2 node/element id from the second (or first) source
1109 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1110 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1111 # @return Measure structure or None if input data is invalid
1113 # @ingroup l1_measurements
1114 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1115 if isinstance(src1, Mesh): src1 = src1.mesh
1116 if isinstance(src2, Mesh): src2 = src2.mesh
1117 if src2 is None and id2 != 0: src2 = src1
1118 if not hasattr(src1, "_narrow"): return None
1119 src1 = src1._narrow(SMESH.SMESH_IDSource)
1120 if not src1: return None
1121 unRegister = genObjUnRegister()
1124 e = m.GetMeshEditor()
1126 src1 = e.MakeIDSource([id1], SMESH.FACE)
1128 src1 = e.MakeIDSource([id1], SMESH.NODE)
1129 unRegister.set( src1 )
1131 if hasattr(src2, "_narrow"):
1132 src2 = src2._narrow(SMESH.SMESH_IDSource)
1133 if src2 and id2 != 0:
1135 e = m.GetMeshEditor()
1137 src2 = e.MakeIDSource([id2], SMESH.FACE)
1139 src2 = e.MakeIDSource([id2], SMESH.NODE)
1140 unRegister.set( src2 )
1143 aMeasurements = self.CreateMeasurements()
1144 unRegister.set( aMeasurements )
1145 result = aMeasurements.MinDistance(src1, src2)
1148 ## Get bounding box of the specified object(s)
1149 # @param objects single source object or list of source objects
1150 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1151 # @sa GetBoundingBox()
1152 # @ingroup l1_measurements
1153 def BoundingBox(self, objects):
1154 result = self.GetBoundingBox(objects)
1158 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1161 ## Get measure structure specifying bounding box data of the specified object(s)
1162 # @param objects single source object or list of source objects
1163 # @return Measure structure
1165 # @ingroup l1_measurements
1166 def GetBoundingBox(self, objects):
1167 if isinstance(objects, tuple):
1168 objects = list(objects)
1169 if not isinstance(objects, list):
1173 if isinstance(o, Mesh):
1174 srclist.append(o.mesh)
1175 elif hasattr(o, "_narrow"):
1176 src = o._narrow(SMESH.SMESH_IDSource)
1177 if src: srclist.append(src)
1180 aMeasurements = self.CreateMeasurements()
1181 result = aMeasurements.BoundingBox(srclist)
1182 aMeasurements.UnRegister()
1185 ## Get sum of lengths of all 1D elements in the mesh object.
1186 # @param obj mesh, submesh or group
1187 # @return sum of lengths of all 1D elements
1188 # @ingroup l1_measurements
1189 def GetLength(self, obj):
1190 if isinstance(obj, Mesh): obj = obj.mesh
1191 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1192 aMeasurements = self.CreateMeasurements()
1193 value = aMeasurements.Length(obj)
1194 aMeasurements.UnRegister()
1197 ## Get sum of areas of all 2D elements in the mesh object.
1198 # @param obj mesh, submesh or group
1199 # @return sum of areas of all 2D elements
1200 # @ingroup l1_measurements
1201 def GetArea(self, obj):
1202 if isinstance(obj, Mesh): obj = obj.mesh
1203 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1204 aMeasurements = self.CreateMeasurements()
1205 value = aMeasurements.Area(obj)
1206 aMeasurements.UnRegister()
1209 ## Get sum of volumes of all 3D elements in the mesh object.
1210 # @param obj mesh, submesh or group
1211 # @return sum of volumes of all 3D elements
1212 # @ingroup l1_measurements
1213 def GetVolume(self, obj):
1214 if isinstance(obj, Mesh): obj = obj.mesh
1215 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1216 aMeasurements = self.CreateMeasurements()
1217 value = aMeasurements.Volume(obj)
1218 aMeasurements.UnRegister()
1221 ## Get gravity center of all nodes of the mesh object.
1222 # @param obj mesh, submesh or group
1223 # @return three components of the gravity center: x,y,z
1224 # @ingroup l1_measurements
1225 def GetGravityCenter(self, obj):
1226 if isinstance(obj, Mesh): obj = obj.mesh
1227 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1228 aMeasurements = self.CreateMeasurements()
1229 pointStruct = aMeasurements.GravityCenter(obj)
1230 aMeasurements.UnRegister()
1231 return pointStruct.x, pointStruct.y, pointStruct.z
1233 pass # end of class smeshBuilder
1236 #Registering the new proxy for SMESH_Gen
1237 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1239 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1240 # interface to create or load meshes.
1245 # salome.salome_init()
1246 # from salome.smesh import smeshBuilder
1247 # smesh = smeshBuilder.New()
1249 # @param isPublished If False, the notebool will not be used.
1250 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1251 # @return smeshBuilder instance
1253 def New( isPublished = True, instance=None):
1255 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1256 interface to create or load meshes.
1260 salome.salome_init()
1261 from salome.smesh import smeshBuilder
1262 smesh = smeshBuilder.New()
1265 isPublished If False, the notebool will not be used.
1266 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1268 smeshBuilder instance
1276 smeshInst = smeshBuilder()
1277 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1278 smeshInst.init_smesh(isPublished)
1282 # Public class: Mesh
1283 # ==================
1285 ## This class allows defining and managing a mesh.
1286 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1287 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1288 # new nodes and elements and by changing the existing entities), to get information
1289 # about a mesh and to export a mesh in different formats.
1290 class Mesh(metaclass=MeshMeta):
1297 # Create a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1298 # sets the GUI name of this mesh to \a name.
1299 # @param smeshpyD an instance of smeshBuilder class
1300 # @param geompyD an instance of geomBuilder class
1301 # @param obj Shape to be meshed or SMESH_Mesh object
1302 # @param name Study name of the mesh
1303 # @ingroup l2_construct
1304 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1305 self.smeshpyD = smeshpyD
1306 self.geompyD = geompyD
1311 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1314 # publish geom of mesh (issue 0021122)
1315 if not self.geom.GetStudyEntry():
1319 geo_name = name + " shape"
1321 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1322 geompyD.addToStudy( self.geom, geo_name )
1323 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1325 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1328 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1330 self.smeshpyD.SetName(self.mesh, name)
1332 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1335 self.geom = self.mesh.GetShapeToMesh()
1337 self.editor = self.mesh.GetMeshEditor()
1338 self.functors = [None] * EnumToLong(SMESH.FT_Undefined)
1340 # set self to algoCreator's
1341 for attrName in dir(self):
1342 attr = getattr( self, attrName )
1343 if isinstance( attr, algoCreator ):
1344 setattr( self, attrName, attr.copy( self ))
1349 ## Destructor. Clean-up resources
1352 #self.mesh.UnRegister()
1356 ## Initialize the Mesh object from an instance of SMESH_Mesh interface
1357 # @param theMesh a SMESH_Mesh object
1358 # @ingroup l2_construct
1359 def SetMesh(self, theMesh):
1360 # do not call Register() as this prevents mesh servant deletion at closing study
1361 #if self.mesh: self.mesh.UnRegister()
1364 #self.mesh.Register()
1365 self.geom = self.mesh.GetShapeToMesh()
1368 ## Return the mesh, that is an instance of SMESH_Mesh interface
1369 # @return a SMESH_Mesh object
1370 # @ingroup l2_construct
1374 ## Get the name of the mesh
1375 # @return the name of the mesh as a string
1376 # @ingroup l2_construct
1378 name = GetName(self.GetMesh())
1381 ## Set a name to the mesh
1382 # @param name a new name of the mesh
1383 # @ingroup l2_construct
1384 def SetName(self, name):
1385 self.smeshpyD.SetName(self.GetMesh(), name)
1387 ## Get a sub-mesh object associated to a \a geom geometrical object.
1388 # @param geom a geometrical object (shape)
1389 # @param name a name for the sub-mesh in the Object Browser
1390 # @return an object of type SMESH.SMESH_subMesh, representing a part of mesh,
1391 # which lies on the given shape
1393 # The sub-mesh object gives access to the IDs of nodes and elements.
1394 # The sub-mesh object has the following methods:
1395 # - SMESH.SMESH_subMesh.GetNumberOfElements()
1396 # - SMESH.SMESH_subMesh.GetNumberOfNodes( all )
1397 # - SMESH.SMESH_subMesh.GetElementsId()
1398 # - SMESH.SMESH_subMesh.GetElementsByType( ElementType )
1399 # - SMESH.SMESH_subMesh.GetNodesId()
1400 # - SMESH.SMESH_subMesh.GetSubShape()
1401 # - SMESH.SMESH_subMesh.GetFather()
1402 # - SMESH.SMESH_subMesh.GetId()
1403 # @note A sub-mesh is implicitly created when a sub-shape is specified at
1404 # creating an algorithm, for example: <code>algo1D = mesh.Segment(geom=Edge_1) </code>
1405 # creates a sub-mesh on @c Edge_1 and assign Wire Discretization algorithm to it.
1406 # The created sub-mesh can be retrieved from the algorithm:
1407 # <code>submesh = algo1D.GetSubMesh()</code>
1408 # @ingroup l2_submeshes
1409 def GetSubMesh(self, geom, name):
1410 AssureGeomPublished( self, geom, name )
1411 submesh = self.mesh.GetSubMesh( geom, name )
1414 ## Return the shape associated to the mesh
1415 # @return a GEOM_Object
1416 # @ingroup l2_construct
1420 ## Associate the given shape to the mesh (entails the recreation of the mesh)
1421 # @param geom the shape to be meshed (GEOM_Object)
1422 # @ingroup l2_construct
1423 def SetShape(self, geom):
1424 self.mesh = self.smeshpyD.CreateMesh(geom)
1426 ## Load mesh from the study after opening the study
1430 ## Return true if the hypotheses are defined well
1431 # @param theSubObject a sub-shape of a mesh shape
1432 # @return True or False
1433 # @ingroup l2_construct
1434 def IsReadyToCompute(self, theSubObject):
1435 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1437 ## Return errors of hypotheses definition.
1438 # The list of errors is empty if everything is OK.
1439 # @param theSubObject a sub-shape of a mesh shape
1440 # @return a list of errors
1441 # @ingroup l2_construct
1442 def GetAlgoState(self, theSubObject):
1443 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1445 ## Return a geometrical object on which the given element was built.
1446 # The returned geometrical object, if not nil, is either found in the
1447 # study or published by this method with the given name
1448 # @param theElementID the id of the mesh element
1449 # @param theGeomName the user-defined name of the geometrical object
1450 # @return GEOM::GEOM_Object instance
1451 # @ingroup l1_meshinfo
1452 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1453 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1455 ## Return the mesh dimension depending on the dimension of the underlying shape
1456 # or, if the mesh is not based on any shape, basing on deimension of elements
1457 # @return mesh dimension as an integer value [0,3]
1458 # @ingroup l1_meshinfo
1459 def MeshDimension(self):
1460 if self.mesh.HasShapeToMesh():
1461 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1462 if len( shells ) > 0 :
1464 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1466 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1471 if self.NbVolumes() > 0: return 3
1472 if self.NbFaces() > 0: return 2
1473 if self.NbEdges() > 0: return 1
1476 ## Evaluate size of prospective mesh on a shape
1477 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1478 # To know predicted number of e.g. edges, inquire it this way
1479 # Evaluate()[ EnumToLong( Entity_Edge )]
1480 # @ingroup l2_construct
1481 def Evaluate(self, geom=0):
1482 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1484 geom = self.mesh.GetShapeToMesh()
1487 return self.smeshpyD.Evaluate(self.mesh, geom)
1490 ## Compute the mesh and return the status of the computation
1491 # @param geom geomtrical shape on which mesh data should be computed
1492 # @param discardModifs if True and the mesh has been edited since
1493 # a last total re-compute and that may prevent successful partial re-compute,
1494 # then the mesh is cleaned before Compute()
1495 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1496 # @return True or False
1497 # @ingroup l2_construct
1498 def Compute(self, geom=0, discardModifs=False, refresh=False):
1499 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1501 geom = self.mesh.GetShapeToMesh()
1506 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1508 ok = self.smeshpyD.Compute(self.mesh, geom)
1509 except SALOME.SALOME_Exception as ex:
1510 print("Mesh computation failed, exception caught:")
1511 print(" ", ex.details.text)
1514 print("Mesh computation failed, exception caught:")
1515 traceback.print_exc()
1519 # Treat compute errors
1520 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1522 for err in computeErrors:
1523 if self.mesh.HasShapeToMesh():
1524 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1526 stdErrors = ["OK", #COMPERR_OK
1527 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1528 "std::exception", #COMPERR_STD_EXCEPTION
1529 "OCC exception", #COMPERR_OCC_EXCEPTION
1530 "..", #COMPERR_SLM_EXCEPTION
1531 "Unknown exception", #COMPERR_EXCEPTION
1532 "Memory allocation problem", #COMPERR_MEMORY_PB
1533 "Algorithm failed", #COMPERR_ALGO_FAILED
1534 "Unexpected geometry", #COMPERR_BAD_SHAPE
1535 "Warning", #COMPERR_WARNING
1536 "Computation cancelled",#COMPERR_CANCELED
1537 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1539 if err.code < len(stdErrors): errText = stdErrors[err.code]
1541 errText = "code %s" % -err.code
1542 if errText: errText += ". "
1543 errText += err.comment
1544 if allReasons: allReasons += "\n"
1546 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1548 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1552 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1554 if err.isGlobalAlgo:
1562 reason = '%s %sD algorithm is missing' % (glob, dim)
1563 elif err.state == HYP_MISSING:
1564 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1565 % (glob, dim, name, dim))
1566 elif err.state == HYP_NOTCONFORM:
1567 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1568 elif err.state == HYP_BAD_PARAMETER:
1569 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1570 % ( glob, dim, name ))
1571 elif err.state == HYP_BAD_GEOMETRY:
1572 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1573 'geometry' % ( glob, dim, name ))
1574 elif err.state == HYP_HIDDEN_ALGO:
1575 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1576 'algorithm of upper dimension generating %sD mesh'
1577 % ( glob, dim, name, glob, dim ))
1579 reason = ("For unknown reason. "
1580 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1582 if allReasons: allReasons += "\n"
1583 allReasons += "- " + reason
1585 if not ok or allReasons != "":
1586 msg = '"' + GetName(self.mesh) + '"'
1587 if ok: msg += " has been computed with warnings"
1588 else: msg += " has not been computed"
1589 if allReasons != "": msg += ":"
1594 if salome.sg.hasDesktop():
1595 if not isinstance( refresh, list): # not a call from subMesh.Compute()
1596 smeshgui = salome.ImportComponentGUI("SMESH")
1598 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1599 if refresh: salome.sg.updateObjBrowser()
1603 ## Return a list of error messages (SMESH.ComputeError) of the last Compute()
1604 # @ingroup l2_construct
1605 def GetComputeErrors(self, shape=0 ):
1607 shape = self.mesh.GetShapeToMesh()
1608 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1610 ## Return a name of a sub-shape by its ID
1611 # @param subShapeID a unique ID of a sub-shape
1612 # @return a string describing the sub-shape; possible variants:
1613 # - "Face_12" (published sub-shape)
1614 # - FACE #3 (not published sub-shape)
1615 # - sub-shape #3 (invalid sub-shape ID)
1616 # - #3 (error in this function)
1617 # @ingroup l1_auxiliary
1618 def GetSubShapeName(self, subShapeID ):
1619 if not self.mesh.HasShapeToMesh():
1623 mainIOR = salome.orb.object_to_string( self.GetShape() )
1625 mainSO = s.FindObjectIOR(mainIOR)
1628 shapeText = '"%s"' % mainSO.GetName()
1629 subIt = s.NewChildIterator(mainSO)
1631 subSO = subIt.Value()
1633 obj = subSO.GetObject()
1634 if not obj: continue
1635 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1638 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1641 if ids == subShapeID:
1642 shapeText = '"%s"' % subSO.GetName()
1644 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1646 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1648 shapeText = 'sub-shape #%s' % (subShapeID)
1650 shapeText = "#%s" % (subShapeID)
1653 ## Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1654 # error of an algorithm
1655 # @param publish if @c True, the returned groups will be published in the study
1656 # @return a list of GEOM groups each named after a failed algorithm
1657 # @ingroup l2_construct
1658 def GetFailedShapes(self, publish=False):
1661 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1662 for err in computeErrors:
1663 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1664 if not shape: continue
1665 if err.algoName in algo2shapes:
1666 algo2shapes[ err.algoName ].append( shape )
1668 algo2shapes[ err.algoName ] = [ shape ]
1672 for algoName, shapes in list(algo2shapes.items()):
1674 groupType = EnumToLong( shapes[0].GetShapeType() )
1675 otherTypeShapes = []
1677 group = self.geompyD.CreateGroup( self.geom, groupType )
1678 for shape in shapes:
1679 if shape.GetShapeType() == shapes[0].GetShapeType():
1680 sameTypeShapes.append( shape )
1682 otherTypeShapes.append( shape )
1683 self.geompyD.UnionList( group, sameTypeShapes )
1685 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1687 group.SetName( algoName )
1688 groups.append( group )
1689 shapes = otherTypeShapes
1692 for group in groups:
1693 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1696 ## Return sub-mesh objects list in meshing order
1697 # @return list of lists of sub-meshes
1698 # @ingroup l2_construct
1699 def GetMeshOrder(self):
1700 return self.mesh.GetMeshOrder()
1702 ## Set order in which concurrent sub-meshes should be meshed
1703 # @param submeshes list of lists of sub-meshes
1704 # @ingroup l2_construct
1705 def SetMeshOrder(self, submeshes):
1706 return self.mesh.SetMeshOrder(submeshes)
1708 ## Remove all nodes and elements generated on geometry. Imported elements remain.
1709 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1710 # @ingroup l2_construct
1711 def Clear(self, refresh=False):
1713 if ( salome.sg.hasDesktop() ):
1714 smeshgui = salome.ImportComponentGUI("SMESH")
1716 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1717 if refresh: salome.sg.updateObjBrowser()
1719 ## Remove all nodes and elements of indicated shape
1720 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1721 # @param geomId the ID of a sub-shape to remove elements on
1722 # @ingroup l2_submeshes
1723 def ClearSubMesh(self, geomId, refresh=False):
1724 self.mesh.ClearSubMesh(geomId)
1725 if salome.sg.hasDesktop():
1726 smeshgui = salome.ImportComponentGUI("SMESH")
1728 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1729 if refresh: salome.sg.updateObjBrowser()
1731 ## Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1732 # @param fineness [0.0,1.0] defines mesh fineness
1733 # @return True or False
1734 # @ingroup l3_algos_basic
1735 def AutomaticTetrahedralization(self, fineness=0):
1736 dim = self.MeshDimension()
1738 self.RemoveGlobalHypotheses()
1739 self.Segment().AutomaticLength(fineness)
1741 self.Triangle().LengthFromEdges()
1746 return self.Compute()
1748 ## Compute an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1749 # @param fineness [0.0, 1.0] defines mesh fineness
1750 # @return True or False
1751 # @ingroup l3_algos_basic
1752 def AutomaticHexahedralization(self, fineness=0):
1753 dim = self.MeshDimension()
1754 # assign the hypotheses
1755 self.RemoveGlobalHypotheses()
1756 self.Segment().AutomaticLength(fineness)
1763 return self.Compute()
1765 ## Assign a hypothesis
1766 # @param hyp a hypothesis to assign
1767 # @param geom a subhape of mesh geometry
1768 # @return SMESH.Hypothesis_Status
1769 # @ingroup l2_editing
1770 def AddHypothesis(self, hyp, geom=0):
1771 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1772 hyp, geom = geom, hyp
1773 if isinstance( hyp, Mesh_Algorithm ):
1774 hyp = hyp.GetAlgorithm()
1779 geom = self.mesh.GetShapeToMesh()
1782 if self.mesh.HasShapeToMesh():
1783 hyp_type = hyp.GetName()
1784 lib_name = hyp.GetLibName()
1785 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1786 # if checkAll and geom:
1787 # checkAll = geom.GetType() == 37
1789 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1791 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1792 status = self.mesh.AddHypothesis(geom, hyp)
1794 status = HYP_BAD_GEOMETRY, ""
1795 hyp_name = GetName( hyp )
1798 geom_name = geom.GetName()
1799 isAlgo = hyp._narrow( SMESH_Algo )
1800 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1803 ## Return True if an algorithm of hypothesis is assigned to a given shape
1804 # @param hyp a hypothesis to check
1805 # @param geom a subhape of mesh geometry
1806 # @return True of False
1807 # @ingroup l2_editing
1808 def IsUsedHypothesis(self, hyp, geom):
1809 if not hyp: # or not geom
1811 if isinstance( hyp, Mesh_Algorithm ):
1812 hyp = hyp.GetAlgorithm()
1814 hyps = self.GetHypothesisList(geom)
1816 if h.GetId() == hyp.GetId():
1820 ## Unassign a hypothesis
1821 # @param hyp a hypothesis to unassign
1822 # @param geom a sub-shape of mesh geometry
1823 # @return SMESH.Hypothesis_Status
1824 # @ingroup l2_editing
1825 def RemoveHypothesis(self, hyp, geom=0):
1828 if isinstance( hyp, Mesh_Algorithm ):
1829 hyp = hyp.GetAlgorithm()
1835 if self.IsUsedHypothesis( hyp, shape ):
1836 return self.mesh.RemoveHypothesis( shape, hyp )
1837 hypName = GetName( hyp )
1838 geoName = GetName( shape )
1839 print("WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName ))
1842 ## Get the list of hypotheses added on a geometry
1843 # @param geom a sub-shape of mesh geometry
1844 # @return the sequence of SMESH_Hypothesis
1845 # @ingroup l2_editing
1846 def GetHypothesisList(self, geom):
1847 return self.mesh.GetHypothesisList( geom )
1849 ## Remove all global hypotheses
1850 # @ingroup l2_editing
1851 def RemoveGlobalHypotheses(self):
1852 current_hyps = self.mesh.GetHypothesisList( self.geom )
1853 for hyp in current_hyps:
1854 self.mesh.RemoveHypothesis( self.geom, hyp )
1858 ## Export the mesh in a file in MED format
1859 ## allowing to overwrite the file if it exists or add the exported data to its contents
1860 # @param fileName is the file name
1861 # @param auto_groups boolean parameter for creating/not creating
1862 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1863 # the typical use is auto_groups=False.
1864 # @param overwrite boolean parameter for overwriting/not overwriting the file
1865 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1866 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1867 # - 1D if all mesh nodes lie on OX coordinate axis, or
1868 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1869 # - 3D in the rest cases.<br>
1870 # If @a autoDimension is @c False, the space dimension is always 3.
1871 # @param fields list of GEOM fields defined on the shape to mesh.
1872 # @param geomAssocFields each character of this string means a need to export a
1873 # corresponding field; correspondence between fields and characters is following:
1874 # - 'v' stands for "_vertices _" field;
1875 # - 'e' stands for "_edges _" field;
1876 # - 'f' stands for "_faces _" field;
1877 # - 's' stands for "_solids _" field.
1878 # @ingroup l2_impexp
1879 def ExportMED(self, *args, **kwargs):
1880 # process positional arguments
1881 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
1883 auto_groups = args[1] if len(args) > 1 else False
1884 overwrite = args[2] if len(args) > 2 else True
1885 meshPart = args[3] if len(args) > 3 else None
1886 autoDimension = args[4] if len(args) > 4 else True
1887 fields = args[5] if len(args) > 5 else []
1888 geomAssocFields = args[6] if len(args) > 6 else ''
1889 # process keywords arguments
1890 auto_groups = kwargs.get("auto_groups", auto_groups)
1891 overwrite = kwargs.get("overwrite", overwrite)
1892 meshPart = kwargs.get("meshPart", meshPart)
1893 autoDimension = kwargs.get("autoDimension", autoDimension)
1894 fields = kwargs.get("fields", fields)
1895 geomAssocFields = kwargs.get("geomAssocFields", geomAssocFields)
1896 # invoke engine's function
1897 if meshPart or fields or geomAssocFields:
1898 unRegister = genObjUnRegister()
1899 if isinstance( meshPart, list ):
1900 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1901 unRegister.set( meshPart )
1902 self.mesh.ExportPartToMED( meshPart, fileName, auto_groups, overwrite, autoDimension,
1903 fields, geomAssocFields)
1905 self.mesh.ExportMED(fileName, auto_groups, overwrite, autoDimension)
1907 ## Export the mesh in a file in SAUV format
1908 # @param f is the file name
1909 # @param auto_groups boolean parameter for creating/not creating
1910 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1911 # the typical use is auto_groups=false.
1912 # @ingroup l2_impexp
1913 def ExportSAUV(self, f, auto_groups=0):
1914 self.mesh.ExportSAUV(f, auto_groups)
1916 ## Export the mesh in a file in DAT format
1917 # @param f the file name
1918 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1919 # @ingroup l2_impexp
1920 def ExportDAT(self, f, meshPart=None):
1922 unRegister = genObjUnRegister()
1923 if isinstance( meshPart, list ):
1924 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1925 unRegister.set( meshPart )
1926 self.mesh.ExportPartToDAT( meshPart, f )
1928 self.mesh.ExportDAT(f)
1930 ## Export the mesh in a file in UNV format
1931 # @param f the file name
1932 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1933 # @ingroup l2_impexp
1934 def ExportUNV(self, f, meshPart=None):
1936 unRegister = genObjUnRegister()
1937 if isinstance( meshPart, list ):
1938 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1939 unRegister.set( meshPart )
1940 self.mesh.ExportPartToUNV( meshPart, f )
1942 self.mesh.ExportUNV(f)
1944 ## Export the mesh in a file in STL format
1945 # @param f the file name
1946 # @param ascii defines the file encoding
1947 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1948 # @ingroup l2_impexp
1949 def ExportSTL(self, f, ascii=1, meshPart=None):
1951 unRegister = genObjUnRegister()
1952 if isinstance( meshPart, list ):
1953 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1954 unRegister.set( meshPart )
1955 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1957 self.mesh.ExportSTL(f, ascii)
1959 ## Export the mesh in a file in CGNS format
1960 # @param f is the file name
1961 # @param overwrite boolean parameter for overwriting/not overwriting the file
1962 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1963 # @param groupElemsByType if true all elements of same entity type are exported at ones,
1964 # else elements are exported in order of their IDs which can cause creation
1965 # of multiple cgns sections
1966 # @ingroup l2_impexp
1967 def ExportCGNS(self, f, overwrite=1, meshPart=None, groupElemsByType=False):
1968 unRegister = genObjUnRegister()
1969 if isinstance( meshPart, list ):
1970 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1971 unRegister.set( meshPart )
1972 if isinstance( meshPart, Mesh ):
1973 meshPart = meshPart.mesh
1975 meshPart = self.mesh
1976 self.mesh.ExportCGNS(meshPart, f, overwrite, groupElemsByType)
1978 ## Export the mesh in a file in GMF format.
1979 # GMF files must have .mesh extension for the ASCII format and .meshb for
1980 # the bynary format. Other extensions are not allowed.
1981 # @param f is the file name
1982 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1983 # @ingroup l2_impexp
1984 def ExportGMF(self, f, meshPart=None):
1985 unRegister = genObjUnRegister()
1986 if isinstance( meshPart, list ):
1987 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1988 unRegister.set( meshPart )
1989 if isinstance( meshPart, Mesh ):
1990 meshPart = meshPart.mesh
1992 meshPart = self.mesh
1993 self.mesh.ExportGMF(meshPart, f, True)
1995 ## Deprecated, used only for compatibility! Please, use ExportMED() method instead.
1996 # Export the mesh in a file in MED format
1997 # allowing to overwrite the file if it exists or add the exported data to its contents
1998 # @param fileName the file name
1999 # @param opt boolean parameter for creating/not creating
2000 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
2001 # @param overwrite boolean parameter for overwriting/not overwriting the file
2002 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
2003 # - 1D if all mesh nodes lie on OX coordinate axis, or
2004 # - 2D if all mesh nodes lie on XOY coordinate plane, or
2005 # - 3D in the rest cases.<br>
2006 # If @a autoDimension is @c False, the space dimension is always 3.
2007 # @ingroup l2_impexp
2008 def ExportToMED(self, *args, **kwargs):
2009 print("WARNING: ExportToMED() is deprecated, use ExportMED() instead")
2010 # process positional arguments
2011 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
2013 auto_groups = args[1] if len(args) > 1 else False
2014 overwrite = args[2] if len(args) > 2 else True
2015 autoDimension = args[3] if len(args) > 3 else True
2016 # process keywords arguments
2017 auto_groups = kwargs.get("opt", auto_groups) # old keyword name
2018 auto_groups = kwargs.get("auto_groups", auto_groups) # new keyword name
2019 overwrite = kwargs.get("overwrite", overwrite)
2020 autoDimension = kwargs.get("autoDimension", autoDimension)
2021 # invoke engine's function
2022 self.mesh.ExportMED(fileName, auto_groups, overwrite, autoDimension)
2024 ## Deprecated, used only for compatibility! Please, use ExportMED() method instead.
2025 # Export the mesh in a file in MED format
2026 # allowing to overwrite the file if it exists or add the exported data to its contents
2027 # @param fileName the file name
2028 # @param opt boolean parameter for creating/not creating
2029 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
2030 # @param overwrite boolean parameter for overwriting/not overwriting the file
2031 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
2032 # - 1D if all mesh nodes lie on OX coordinate axis, or
2033 # - 2D if all mesh nodes lie on XOY coordinate plane, or
2034 # - 3D in the rest cases.<br>
2035 # If @a autoDimension is @c False, the space dimension is always 3.
2036 # @ingroup l2_impexp
2037 def ExportToMEDX(self, *args, **kwargs):
2038 print("WARNING: ExportToMEDX() is deprecated, use ExportMED() instead")
2039 # process positional arguments
2040 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
2042 auto_groups = args[1] if len(args) > 1 else False
2043 overwrite = args[2] if len(args) > 2 else True
2044 autoDimension = args[3] if len(args) > 3 else True
2045 # process keywords arguments
2046 auto_groups = kwargs.get("auto_groups", auto_groups)
2047 overwrite = kwargs.get("overwrite", overwrite)
2048 autoDimension = kwargs.get("autoDimension", autoDimension)
2049 # invoke engine's function
2050 self.mesh.ExportMED(fileName, auto_groups, overwrite, autoDimension)
2052 # Operations with groups:
2053 # ----------------------
2055 ## Create an empty mesh group
2056 # @param elementType the type of elements in the group; either of
2057 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2058 # @param name the name of the mesh group
2059 # @return SMESH_Group
2060 # @ingroup l2_grps_create
2061 def CreateEmptyGroup(self, elementType, name):
2062 return self.mesh.CreateGroup(elementType, name)
2064 ## Create a mesh group based on the geometric object \a grp
2065 # and gives a \a name, \n if this parameter is not defined
2066 # the name is the same as the geometric group name \n
2067 # Note: Works like GroupOnGeom().
2068 # @param grp a geometric group, a vertex, an edge, a face or a solid
2069 # @param name the name of the mesh group
2070 # @return SMESH_GroupOnGeom
2071 # @ingroup l2_grps_create
2072 def Group(self, grp, name=""):
2073 return self.GroupOnGeom(grp, name)
2075 ## Create a mesh group based on the geometrical object \a grp
2076 # and gives a \a name, \n if this parameter is not defined
2077 # the name is the same as the geometrical group name
2078 # @param grp a geometrical group, a vertex, an edge, a face or a solid
2079 # @param name the name of the mesh group
2080 # @param typ the type of elements in the group; either of
2081 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
2082 # automatically detected by the type of the geometry
2083 # @return SMESH_GroupOnGeom
2084 # @ingroup l2_grps_create
2085 def GroupOnGeom(self, grp, name="", typ=None):
2086 AssureGeomPublished( self, grp, name )
2088 name = grp.GetName()
2090 typ = self._groupTypeFromShape( grp )
2091 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
2093 ## Pivate method to get a type of group on geometry
2094 def _groupTypeFromShape( self, shape ):
2095 tgeo = str(shape.GetShapeType())
2096 if tgeo == "VERTEX":
2098 elif tgeo == "EDGE":
2100 elif tgeo == "FACE" or tgeo == "SHELL":
2102 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
2104 elif tgeo == "COMPOUND":
2105 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
2107 raise ValueError("_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape))
2108 return self._groupTypeFromShape( sub[0] )
2110 raise ValueError("_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape))
2113 ## Create a mesh group with given \a name based on the \a filter which
2114 ## is a special type of group dynamically updating it's contents during
2115 ## mesh modification
2116 # @param typ the type of elements in the group; either of
2117 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2118 # @param name the name of the mesh group
2119 # @param filter the filter defining group contents
2120 # @return SMESH_GroupOnFilter
2121 # @ingroup l2_grps_create
2122 def GroupOnFilter(self, typ, name, filter):
2123 return self.mesh.CreateGroupFromFilter(typ, name, filter)
2125 ## Create a mesh group by the given ids of elements
2126 # @param groupName the name of the mesh group
2127 # @param elementType the type of elements in the group; either of
2128 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2129 # @param elemIDs either the list of ids, group, sub-mesh, or filter
2130 # @return SMESH_Group
2131 # @ingroup l2_grps_create
2132 def MakeGroupByIds(self, groupName, elementType, elemIDs):
2133 group = self.mesh.CreateGroup(elementType, groupName)
2134 if isinstance( elemIDs, Mesh ):
2135 elemIDs = elemIDs.GetMesh()
2136 if hasattr( elemIDs, "GetIDs" ):
2137 if hasattr( elemIDs, "SetMesh" ):
2138 elemIDs.SetMesh( self.GetMesh() )
2139 group.AddFrom( elemIDs )
2144 ## Create a mesh group by the given conditions
2145 # @param groupName the name of the mesh group
2146 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2147 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
2148 # Type SMESH.FunctorType._items in the Python Console to see all values.
2149 # Note that the items starting from FT_LessThan are not suitable for CritType.
2150 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
2151 # @param Threshold the threshold value (range of ids as string, shape, numeric)
2152 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2153 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2154 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2155 # @return SMESH_GroupOnFilter
2156 # @ingroup l2_grps_create
2160 CritType=FT_Undefined,
2163 UnaryOp=FT_Undefined,
2165 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2166 group = self.MakeGroupByCriterion(groupName, aCriterion)
2169 ## Create a mesh group by the given criterion
2170 # @param groupName the name of the mesh group
2171 # @param Criterion the instance of Criterion class
2172 # @return SMESH_GroupOnFilter
2173 # @ingroup l2_grps_create
2174 def MakeGroupByCriterion(self, groupName, Criterion):
2175 return self.MakeGroupByCriteria( groupName, [Criterion] )
2177 ## Create a mesh group by the given criteria (list of criteria)
2178 # @param groupName the name of the mesh group
2179 # @param theCriteria the list of criteria
2180 # @param binOp binary operator used when binary operator of criteria is undefined
2181 # @return SMESH_GroupOnFilter
2182 # @ingroup l2_grps_create
2183 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2184 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2185 group = self.MakeGroupByFilter(groupName, aFilter)
2188 ## Create a mesh group by the given filter
2189 # @param groupName the name of the mesh group
2190 # @param theFilter the instance of Filter class
2191 # @return SMESH_GroupOnFilter
2192 # @ingroup l2_grps_create
2193 def MakeGroupByFilter(self, groupName, theFilter):
2194 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2195 #theFilter.SetMesh( self.mesh )
2196 #group.AddFrom( theFilter )
2197 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2201 # @ingroup l2_grps_delete
2202 def RemoveGroup(self, group):
2203 self.mesh.RemoveGroup(group)
2205 ## Remove a group with its contents
2206 # @ingroup l2_grps_delete
2207 def RemoveGroupWithContents(self, group):
2208 self.mesh.RemoveGroupWithContents(group)
2210 ## Get the list of groups existing in the mesh in the order
2211 # of creation (starting from the oldest one)
2212 # @param elemType type of elements the groups contain; either of
2213 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2214 # by default groups of elements of all types are returned
2215 # @return a sequence of SMESH_GroupBase
2216 # @ingroup l2_grps_create
2217 def GetGroups(self, elemType = SMESH.ALL):
2218 groups = self.mesh.GetGroups()
2219 if elemType == SMESH.ALL:
2223 if g.GetType() == elemType:
2224 typedGroups.append( g )
2229 ## Get the number of groups existing in the mesh
2230 # @return the quantity of groups as an integer value
2231 # @ingroup l2_grps_create
2233 return self.mesh.NbGroups()
2235 ## Get the list of names of groups existing in the mesh
2236 # @return list of strings
2237 # @ingroup l2_grps_create
2238 def GetGroupNames(self):
2239 groups = self.GetGroups()
2241 for group in groups:
2242 names.append(group.GetName())
2245 ## Find groups by name and type
2246 # @param name name of the group of interest
2247 # @param elemType type of elements the groups contain; either of
2248 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2249 # by default one group of any type of elements is returned
2250 # if elemType == SMESH.ALL then all groups of any type are returned
2251 # @return a list of SMESH_GroupBase's
2252 # @ingroup l2_grps_create
2253 def GetGroupByName(self, name, elemType = None):
2255 for group in self.GetGroups():
2256 if group.GetName() == name:
2257 if elemType is None:
2259 if ( elemType == SMESH.ALL or
2260 group.GetType() == elemType ):
2261 groups.append( group )
2264 ## Produce a union of two groups.
2265 # A new group is created. All mesh elements that are
2266 # present in the initial groups are added to the new one
2267 # @return an instance of SMESH_Group
2268 # @ingroup l2_grps_operon
2269 def UnionGroups(self, group1, group2, name):
2270 return self.mesh.UnionGroups(group1, group2, name)
2272 ## Produce a union list of groups.
2273 # New group is created. All mesh elements that are present in
2274 # initial groups are added to the new one
2275 # @return an instance of SMESH_Group
2276 # @ingroup l2_grps_operon
2277 def UnionListOfGroups(self, groups, name):
2278 return self.mesh.UnionListOfGroups(groups, name)
2280 ## Prodice an intersection of two groups.
2281 # A new group is created. All mesh elements that are common
2282 # for the two initial groups are added to the new one.
2283 # @return an instance of SMESH_Group
2284 # @ingroup l2_grps_operon
2285 def IntersectGroups(self, group1, group2, name):
2286 return self.mesh.IntersectGroups(group1, group2, name)
2288 ## Produce an intersection of groups.
2289 # New group is created. All mesh elements that are present in all
2290 # initial groups simultaneously are added to the new one
2291 # @return an instance of SMESH_Group
2292 # @ingroup l2_grps_operon
2293 def IntersectListOfGroups(self, groups, name):
2294 return self.mesh.IntersectListOfGroups(groups, name)
2296 ## Produce a cut of two groups.
2297 # A new group is created. All mesh elements that are present in
2298 # the main group but are not present in the tool group are added to the new one
2299 # @return an instance of SMESH_Group
2300 # @ingroup l2_grps_operon
2301 def CutGroups(self, main_group, tool_group, name):
2302 return self.mesh.CutGroups(main_group, tool_group, name)
2304 ## Produce a cut of groups.
2305 # A new group is created. All mesh elements that are present in main groups
2306 # but do not present in tool groups are added to the new one
2307 # @return an instance of SMESH_Group
2308 # @ingroup l2_grps_operon
2309 def CutListOfGroups(self, main_groups, tool_groups, name):
2310 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2313 # Create a standalone group of entities basing on nodes of other groups.
2314 # \param groups - list of reference groups, sub-meshes or filters, of any type.
2315 # \param elemType - a type of elements to include to the new group; either of
2316 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2317 # \param name - a name of the new group.
2318 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2319 # basing on number of element nodes common with reference \a groups.
2320 # Meaning of possible values are:
2321 # - SMESH.ALL_NODES - include if all nodes are common,
2322 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2323 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2324 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2325 # \param underlyingOnly - if \c True (default), an element is included to the
2326 # new group provided that it is based on nodes of an element of \a groups;
2327 # in this case the reference \a groups are supposed to be of higher dimension
2328 # than \a elemType, which can be useful for example to get all faces lying on
2329 # volumes of the reference \a groups.
2330 # @return an instance of SMESH_Group
2331 # @ingroup l2_grps_operon
2332 def CreateDimGroup(self, groups, elemType, name,
2333 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2334 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2336 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2339 ## Convert group on geom into standalone group
2340 # @ingroup l2_grps_operon
2341 def ConvertToStandalone(self, group):
2342 return self.mesh.ConvertToStandalone(group)
2344 # Get some info about mesh:
2345 # ------------------------
2347 ## Return the log of nodes and elements added or removed
2348 # since the previous clear of the log.
2349 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2350 # @return list of log_block structures:
2355 # @ingroup l1_auxiliary
2356 def GetLog(self, clearAfterGet):
2357 return self.mesh.GetLog(clearAfterGet)
2359 ## Clear the log of nodes and elements added or removed since the previous
2360 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2361 # @ingroup l1_auxiliary
2363 self.mesh.ClearLog()
2365 ## Toggle auto color mode on the object.
2366 # @param theAutoColor the flag which toggles auto color mode.
2368 # If switched on, a default color of a new group in Create Group dialog is chosen randomly.
2369 # @ingroup l1_grouping
2370 def SetAutoColor(self, theAutoColor):
2371 self.mesh.SetAutoColor(theAutoColor)
2373 ## Get flag of object auto color mode.
2374 # @return True or False
2375 # @ingroup l1_grouping
2376 def GetAutoColor(self):
2377 return self.mesh.GetAutoColor()
2379 ## Get the internal ID
2380 # @return integer value, which is the internal Id of the mesh
2381 # @ingroup l1_auxiliary
2383 return self.mesh.GetId()
2385 ## Check the group names for duplications.
2386 # Consider the maximum group name length stored in MED file.
2387 # @return True or False
2388 # @ingroup l1_grouping
2389 def HasDuplicatedGroupNamesMED(self):
2390 return self.mesh.HasDuplicatedGroupNamesMED()
2392 ## Obtain the mesh editor tool
2393 # @return an instance of SMESH_MeshEditor
2394 # @ingroup l1_modifying
2395 def GetMeshEditor(self):
2398 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2399 # can be passed as argument to a method accepting mesh, group or sub-mesh
2400 # @param ids list of IDs
2401 # @param elemType type of elements; this parameter is used to distinguish
2402 # IDs of nodes from IDs of elements; by default ids are treated as
2403 # IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2404 # @return an instance of SMESH_IDSource
2405 # @warning call UnRegister() for the returned object as soon as it is no more useful:
2406 # idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2407 # mesh.DoSomething( idSrc )
2408 # idSrc.UnRegister()
2409 # @ingroup l1_auxiliary
2410 def GetIDSource(self, ids, elemType = SMESH.ALL):
2411 if isinstance( ids, int ):
2413 return self.editor.MakeIDSource(ids, elemType)
2416 # Get information about mesh contents:
2417 # ------------------------------------
2419 ## Get the mesh statistic
2420 # @return dictionary type element - count of elements
2421 # @ingroup l1_meshinfo
2422 def GetMeshInfo(self, obj = None):
2423 if not obj: obj = self.mesh
2424 return self.smeshpyD.GetMeshInfo(obj)
2426 ## Return the number of nodes in the mesh
2427 # @return an integer value
2428 # @ingroup l1_meshinfo
2430 return self.mesh.NbNodes()
2432 ## Return the number of elements in the mesh
2433 # @return an integer value
2434 # @ingroup l1_meshinfo
2435 def NbElements(self):
2436 return self.mesh.NbElements()
2438 ## Return the number of 0d elements in the mesh
2439 # @return an integer value
2440 # @ingroup l1_meshinfo
2441 def Nb0DElements(self):
2442 return self.mesh.Nb0DElements()
2444 ## Return the number of ball discrete elements in the mesh
2445 # @return an integer value
2446 # @ingroup l1_meshinfo
2448 return self.mesh.NbBalls()
2450 ## Return the number of edges in the mesh
2451 # @return an integer value
2452 # @ingroup l1_meshinfo
2454 return self.mesh.NbEdges()
2456 ## Return the number of edges with the given order in the mesh
2457 # @param elementOrder the order of elements:
2458 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2459 # @return an integer value
2460 # @ingroup l1_meshinfo
2461 def NbEdgesOfOrder(self, elementOrder):
2462 return self.mesh.NbEdgesOfOrder(elementOrder)
2464 ## Return the number of faces in the mesh
2465 # @return an integer value
2466 # @ingroup l1_meshinfo
2468 return self.mesh.NbFaces()
2470 ## Return the number of faces with the given order in the mesh
2471 # @param elementOrder the order of elements:
2472 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2473 # @return an integer value
2474 # @ingroup l1_meshinfo
2475 def NbFacesOfOrder(self, elementOrder):
2476 return self.mesh.NbFacesOfOrder(elementOrder)
2478 ## Return the number of triangles in the mesh
2479 # @return an integer value
2480 # @ingroup l1_meshinfo
2481 def NbTriangles(self):
2482 return self.mesh.NbTriangles()
2484 ## Return the number of triangles with the given order in the mesh
2485 # @param elementOrder is the order of elements:
2486 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2487 # @return an integer value
2488 # @ingroup l1_meshinfo
2489 def NbTrianglesOfOrder(self, elementOrder):
2490 return self.mesh.NbTrianglesOfOrder(elementOrder)
2492 ## Return the number of biquadratic triangles in the mesh
2493 # @return an integer value
2494 # @ingroup l1_meshinfo
2495 def NbBiQuadTriangles(self):
2496 return self.mesh.NbBiQuadTriangles()
2498 ## Return the number of quadrangles in the mesh
2499 # @return an integer value
2500 # @ingroup l1_meshinfo
2501 def NbQuadrangles(self):
2502 return self.mesh.NbQuadrangles()
2504 ## Return the number of quadrangles with the given order in the mesh
2505 # @param elementOrder the order of elements:
2506 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2507 # @return an integer value
2508 # @ingroup l1_meshinfo
2509 def NbQuadranglesOfOrder(self, elementOrder):
2510 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2512 ## Return the number of biquadratic quadrangles in the mesh
2513 # @return an integer value
2514 # @ingroup l1_meshinfo
2515 def NbBiQuadQuadrangles(self):
2516 return self.mesh.NbBiQuadQuadrangles()
2518 ## Return the number of polygons of given order in the mesh
2519 # @param elementOrder the order of elements:
2520 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2521 # @return an integer value
2522 # @ingroup l1_meshinfo
2523 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2524 return self.mesh.NbPolygonsOfOrder(elementOrder)
2526 ## Return the number of volumes in the mesh
2527 # @return an integer value
2528 # @ingroup l1_meshinfo
2529 def NbVolumes(self):
2530 return self.mesh.NbVolumes()
2532 ## Return the number of volumes with the given order in the mesh
2533 # @param elementOrder the order of elements:
2534 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2535 # @return an integer value
2536 # @ingroup l1_meshinfo
2537 def NbVolumesOfOrder(self, elementOrder):
2538 return self.mesh.NbVolumesOfOrder(elementOrder)
2540 ## Return the number of tetrahedrons in the mesh
2541 # @return an integer value
2542 # @ingroup l1_meshinfo
2544 return self.mesh.NbTetras()
2546 ## Return the number of tetrahedrons with the given order in the mesh
2547 # @param elementOrder the order of elements:
2548 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2549 # @return an integer value
2550 # @ingroup l1_meshinfo
2551 def NbTetrasOfOrder(self, elementOrder):
2552 return self.mesh.NbTetrasOfOrder(elementOrder)
2554 ## Return the number of hexahedrons in the mesh
2555 # @return an integer value
2556 # @ingroup l1_meshinfo
2558 return self.mesh.NbHexas()
2560 ## Return the number of hexahedrons with the given order in the mesh
2561 # @param elementOrder the order of elements:
2562 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2563 # @return an integer value
2564 # @ingroup l1_meshinfo
2565 def NbHexasOfOrder(self, elementOrder):
2566 return self.mesh.NbHexasOfOrder(elementOrder)
2568 ## Return the number of triquadratic hexahedrons in the mesh
2569 # @return an integer value
2570 # @ingroup l1_meshinfo
2571 def NbTriQuadraticHexas(self):
2572 return self.mesh.NbTriQuadraticHexas()
2574 ## Return the number of pyramids in the mesh
2575 # @return an integer value
2576 # @ingroup l1_meshinfo
2577 def NbPyramids(self):
2578 return self.mesh.NbPyramids()
2580 ## Return the number of pyramids with the given order in the mesh
2581 # @param elementOrder the order of elements:
2582 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2583 # @return an integer value
2584 # @ingroup l1_meshinfo
2585 def NbPyramidsOfOrder(self, elementOrder):
2586 return self.mesh.NbPyramidsOfOrder(elementOrder)
2588 ## Return the number of prisms in the mesh
2589 # @return an integer value
2590 # @ingroup l1_meshinfo
2592 return self.mesh.NbPrisms()
2594 ## Return the number of prisms with the given order in the mesh
2595 # @param elementOrder the order of elements:
2596 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2597 # @return an integer value
2598 # @ingroup l1_meshinfo
2599 def NbPrismsOfOrder(self, elementOrder):
2600 return self.mesh.NbPrismsOfOrder(elementOrder)
2602 ## Return the number of hexagonal prisms in the mesh
2603 # @return an integer value
2604 # @ingroup l1_meshinfo
2605 def NbHexagonalPrisms(self):
2606 return self.mesh.NbHexagonalPrisms()
2608 ## Return the number of polyhedrons in the mesh
2609 # @return an integer value
2610 # @ingroup l1_meshinfo
2611 def NbPolyhedrons(self):
2612 return self.mesh.NbPolyhedrons()
2614 ## Return the number of submeshes in the mesh
2615 # @return an integer value
2616 # @ingroup l1_meshinfo
2617 def NbSubMesh(self):
2618 return self.mesh.NbSubMesh()
2620 ## Return the list of mesh elements IDs
2621 # @return the list of integer values
2622 # @ingroup l1_meshinfo
2623 def GetElementsId(self):
2624 return self.mesh.GetElementsId()
2626 ## Return the list of IDs of mesh elements with the given type
2627 # @param elementType the required type of elements, either of
2628 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2629 # @return list of integer values
2630 # @ingroup l1_meshinfo
2631 def GetElementsByType(self, elementType):
2632 return self.mesh.GetElementsByType(elementType)
2634 ## Return the list of mesh nodes IDs
2635 # @return the list of integer values
2636 # @ingroup l1_meshinfo
2637 def GetNodesId(self):
2638 return self.mesh.GetNodesId()
2640 # Get the information about mesh elements:
2641 # ------------------------------------
2643 ## Return the type of mesh element
2644 # @return the value from SMESH::ElementType enumeration
2645 # Type SMESH.ElementType._items in the Python Console to see all possible values.
2646 # @ingroup l1_meshinfo
2647 def GetElementType(self, id, iselem=True):
2648 return self.mesh.GetElementType(id, iselem)
2650 ## Return the geometric type of mesh element
2651 # @return the value from SMESH::EntityType enumeration
2652 # Type SMESH.EntityType._items in the Python Console to see all possible values.
2653 # @ingroup l1_meshinfo
2654 def GetElementGeomType(self, id):
2655 return self.mesh.GetElementGeomType(id)
2657 ## Return the shape type of mesh element
2658 # @return the value from SMESH::GeometryType enumeration.
2659 # Type SMESH.GeometryType._items in the Python Console to see all possible values.
2660 # @ingroup l1_meshinfo
2661 def GetElementShape(self, id):
2662 return self.mesh.GetElementShape(id)
2664 ## Return the list of submesh elements IDs
2665 # @param Shape a geom object(sub-shape)
2666 # Shape must be the sub-shape of a ShapeToMesh()
2667 # @return the list of integer values
2668 # @ingroup l1_meshinfo
2669 def GetSubMeshElementsId(self, Shape):
2670 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2671 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2674 return self.mesh.GetSubMeshElementsId(ShapeID)
2676 ## Return the list of submesh nodes IDs
2677 # @param Shape a geom object(sub-shape)
2678 # Shape must be the sub-shape of a ShapeToMesh()
2679 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2680 # @return the list of integer values
2681 # @ingroup l1_meshinfo
2682 def GetSubMeshNodesId(self, Shape, all):
2683 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2684 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2687 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2689 ## Return type of elements on given shape
2690 # @param Shape a geom object(sub-shape)
2691 # Shape must be a sub-shape of a ShapeToMesh()
2692 # @return element type
2693 # @ingroup l1_meshinfo
2694 def GetSubMeshElementType(self, Shape):
2695 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2696 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2699 return self.mesh.GetSubMeshElementType(ShapeID)
2701 ## Get the mesh description
2702 # @return string value
2703 # @ingroup l1_meshinfo
2705 return self.mesh.Dump()
2708 # Get the information about nodes and elements of a mesh by its IDs:
2709 # -----------------------------------------------------------
2711 ## Get XYZ coordinates of a node
2712 # \n If there is no nodes for the given ID - return an empty list
2713 # @return a list of double precision values
2714 # @ingroup l1_meshinfo
2715 def GetNodeXYZ(self, id):
2716 return self.mesh.GetNodeXYZ(id)
2718 ## Return list of IDs of inverse elements for the given node
2719 # \n If there is no node for the given ID - return an empty list
2720 # @return a list of integer values
2721 # @ingroup l1_meshinfo
2722 def GetNodeInverseElements(self, id):
2723 return self.mesh.GetNodeInverseElements(id)
2725 ## Return the position of a node on the shape
2726 # @return SMESH::NodePosition
2727 # @ingroup l1_meshinfo
2728 def GetNodePosition(self,NodeID):
2729 return self.mesh.GetNodePosition(NodeID)
2731 ## Return the position of an element on the shape
2732 # @return SMESH::ElementPosition
2733 # @ingroup l1_meshinfo
2734 def GetElementPosition(self,ElemID):
2735 return self.mesh.GetElementPosition(ElemID)
2737 ## Return the ID of the shape, on which the given node was generated.
2738 # @return an integer value > 0 or -1 if there is no node for the given
2739 # ID or the node is not assigned to any geometry
2740 # @ingroup l1_meshinfo
2741 def GetShapeID(self, id):
2742 return self.mesh.GetShapeID(id)
2744 ## Return the ID of the shape, on which the given element was generated.
2745 # @return an integer value > 0 or -1 if there is no element for the given
2746 # ID or the element is not assigned to any geometry
2747 # @ingroup l1_meshinfo
2748 def GetShapeIDForElem(self,id):
2749 return self.mesh.GetShapeIDForElem(id)
2751 ## Return the number of nodes of the given element
2752 # @return an integer value > 0 or -1 if there is no element for the given ID
2753 # @ingroup l1_meshinfo
2754 def GetElemNbNodes(self, id):
2755 return self.mesh.GetElemNbNodes(id)
2757 ## Return the node ID the given (zero based) index for the given element
2758 # \n If there is no element for the given ID - return -1
2759 # \n If there is no node for the given index - return -2
2760 # @return an integer value
2761 # @ingroup l1_meshinfo
2762 def GetElemNode(self, id, index):
2763 return self.mesh.GetElemNode(id, index)
2765 ## Return the IDs of nodes of the given element
2766 # @return a list of integer values
2767 # @ingroup l1_meshinfo
2768 def GetElemNodes(self, id):
2769 return self.mesh.GetElemNodes(id)
2771 ## Return true if the given node is the medium node in the given quadratic element
2772 # @ingroup l1_meshinfo
2773 def IsMediumNode(self, elementID, nodeID):
2774 return self.mesh.IsMediumNode(elementID, nodeID)
2776 ## Return true if the given node is the medium node in one of quadratic elements
2777 # @param nodeID ID of the node
2778 # @param elementType the type of elements to check a state of the node, either of
2779 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2780 # @ingroup l1_meshinfo
2781 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2782 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2784 ## Return the number of edges for the given element
2785 # @ingroup l1_meshinfo
2786 def ElemNbEdges(self, id):
2787 return self.mesh.ElemNbEdges(id)
2789 ## Return the number of faces for the given element
2790 # @ingroup l1_meshinfo
2791 def ElemNbFaces(self, id):
2792 return self.mesh.ElemNbFaces(id)
2794 ## Return nodes of given face (counted from zero) for given volumic element.
2795 # @ingroup l1_meshinfo
2796 def GetElemFaceNodes(self,elemId, faceIndex):
2797 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2799 ## Return three components of normal of given mesh face
2800 # (or an empty array in KO case)
2801 # @ingroup l1_meshinfo
2802 def GetFaceNormal(self, faceId, normalized=False):
2803 return self.mesh.GetFaceNormal(faceId,normalized)
2805 ## Return an element based on all given nodes.
2806 # @ingroup l1_meshinfo
2807 def FindElementByNodes(self, nodes):
2808 return self.mesh.FindElementByNodes(nodes)
2810 ## Return elements including all given nodes.
2811 # @ingroup l1_meshinfo
2812 def GetElementsByNodes(self, nodes, elemType=SMESH.ALL):
2813 return self.mesh.GetElementsByNodes( nodes, elemType )
2815 ## Return true if the given element is a polygon
2816 # @ingroup l1_meshinfo
2817 def IsPoly(self, id):
2818 return self.mesh.IsPoly(id)
2820 ## Return true if the given element is quadratic
2821 # @ingroup l1_meshinfo
2822 def IsQuadratic(self, id):
2823 return self.mesh.IsQuadratic(id)
2825 ## Return diameter of a ball discrete element or zero in case of an invalid \a id
2826 # @ingroup l1_meshinfo
2827 def GetBallDiameter(self, id):
2828 return self.mesh.GetBallDiameter(id)
2830 ## Return XYZ coordinates of the barycenter of the given element
2831 # \n If there is no element for the given ID - return an empty list
2832 # @return a list of three double values
2833 # @ingroup l1_meshinfo
2834 def BaryCenter(self, id):
2835 return self.mesh.BaryCenter(id)
2837 ## Pass mesh elements through the given filter and return IDs of fitting elements
2838 # @param theFilter SMESH_Filter
2839 # @return a list of ids
2840 # @ingroup l1_controls
2841 def GetIdsFromFilter(self, theFilter):
2842 theFilter.SetMesh( self.mesh )
2843 return theFilter.GetIDs()
2845 # Get mesh measurements information:
2846 # ------------------------------------
2848 ## Verify whether a 2D mesh element has free edges (edges connected to one face only)\n
2849 # Return a list of special structures (borders).
2850 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2851 # @ingroup l1_measurements
2852 def GetFreeBorders(self):
2853 aFilterMgr = self.smeshpyD.CreateFilterManager()
2854 aPredicate = aFilterMgr.CreateFreeEdges()
2855 aPredicate.SetMesh(self.mesh)
2856 aBorders = aPredicate.GetBorders()
2857 aFilterMgr.UnRegister()
2860 ## Get minimum distance between two nodes, elements or distance to the origin
2861 # @param id1 first node/element id
2862 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2863 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2864 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2865 # @return minimum distance value
2866 # @sa GetMinDistance()
2867 # @ingroup l1_measurements
2868 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2869 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2870 return aMeasure.value
2872 ## Get measure structure specifying minimum distance data between two objects
2873 # @param id1 first node/element id
2874 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2875 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2876 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2877 # @return Measure structure
2879 # @ingroup l1_measurements
2880 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2882 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2884 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2887 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2889 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2894 aMeasurements = self.smeshpyD.CreateMeasurements()
2895 aMeasure = aMeasurements.MinDistance(id1, id2)
2896 genObjUnRegister([aMeasurements,id1, id2])
2899 ## Get bounding box of the specified object(s)
2900 # @param objects single source object or list of source objects or list of nodes/elements IDs
2901 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2902 # @c False specifies that @a objects are nodes
2903 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2904 # @sa GetBoundingBox()
2905 # @ingroup l1_measurements
2906 def BoundingBox(self, objects=None, isElem=False):
2907 result = self.GetBoundingBox(objects, isElem)
2911 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2914 ## Get measure structure specifying bounding box data of the specified object(s)
2915 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2916 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2917 # @c False specifies that @a objects are nodes
2918 # @return Measure structure
2920 # @ingroup l1_measurements
2921 def GetBoundingBox(self, IDs=None, isElem=False):
2924 elif isinstance(IDs, tuple):
2926 if not isinstance(IDs, list):
2928 if len(IDs) > 0 and isinstance(IDs[0], int):
2931 unRegister = genObjUnRegister()
2933 if isinstance(o, Mesh):
2934 srclist.append(o.mesh)
2935 elif hasattr(o, "_narrow"):
2936 src = o._narrow(SMESH.SMESH_IDSource)
2937 if src: srclist.append(src)
2939 elif isinstance(o, list):
2941 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2943 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2944 unRegister.set( srclist[-1] )
2947 aMeasurements = self.smeshpyD.CreateMeasurements()
2948 unRegister.set( aMeasurements )
2949 aMeasure = aMeasurements.BoundingBox(srclist)
2952 # Mesh edition (SMESH_MeshEditor functionality):
2953 # ---------------------------------------------
2955 ## Remove the elements from the mesh by ids
2956 # @param IDsOfElements is a list of ids of elements to remove
2957 # @return True or False
2958 # @ingroup l2_modif_del
2959 def RemoveElements(self, IDsOfElements):
2960 return self.editor.RemoveElements(IDsOfElements)
2962 ## Remove nodes from mesh by ids
2963 # @param IDsOfNodes is a list of ids of nodes to remove
2964 # @return True or False
2965 # @ingroup l2_modif_del
2966 def RemoveNodes(self, IDsOfNodes):
2967 return self.editor.RemoveNodes(IDsOfNodes)
2969 ## Remove all orphan (free) nodes from mesh
2970 # @return number of the removed nodes
2971 # @ingroup l2_modif_del
2972 def RemoveOrphanNodes(self):
2973 return self.editor.RemoveOrphanNodes()
2975 ## Add a node to the mesh by coordinates
2976 # @return Id of the new node
2977 # @ingroup l2_modif_add
2978 def AddNode(self, x, y, z):
2979 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2980 if hasVars: self.mesh.SetParameters(Parameters)
2981 return self.editor.AddNode( x, y, z)
2983 ## Create a 0D element on a node with given number.
2984 # @param IDOfNode the ID of node for creation of the element.
2985 # @param DuplicateElements to add one more 0D element to a node or not
2986 # @return the Id of the new 0D element
2987 # @ingroup l2_modif_add
2988 def Add0DElement( self, IDOfNode, DuplicateElements=True ):
2989 return self.editor.Add0DElement( IDOfNode, DuplicateElements )
2991 ## Create 0D elements on all nodes of the given elements except those
2992 # nodes on which a 0D element already exists.
2993 # @param theObject an object on whose nodes 0D elements will be created.
2994 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2995 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2996 # @param theGroupName optional name of a group to add 0D elements created
2997 # and/or found on nodes of \a theObject.
2998 # @param DuplicateElements to add one more 0D element to a node or not
2999 # @return an object (a new group or a temporary SMESH_IDSource) holding
3000 # IDs of new and/or found 0D elements. IDs of 0D elements
3001 # can be retrieved from the returned object by calling GetIDs()
3002 # @ingroup l2_modif_add
3003 def Add0DElementsToAllNodes(self, theObject, theGroupName="", DuplicateElements=False):
3004 unRegister = genObjUnRegister()
3005 if isinstance( theObject, Mesh ):
3006 theObject = theObject.GetMesh()
3007 elif isinstance( theObject, list ):
3008 theObject = self.GetIDSource( theObject, SMESH.ALL )
3009 unRegister.set( theObject )
3010 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName, DuplicateElements )
3012 ## Create a ball element on a node with given ID.
3013 # @param IDOfNode the ID of node for creation of the element.
3014 # @param diameter the bal diameter.
3015 # @return the Id of the new ball element
3016 # @ingroup l2_modif_add
3017 def AddBall(self, IDOfNode, diameter):
3018 return self.editor.AddBall( IDOfNode, diameter )
3020 ## Create a linear or quadratic edge (this is determined
3021 # by the number of given nodes).
3022 # @param IDsOfNodes the list of node IDs for creation of the element.
3023 # The order of nodes in this list should correspond to the description
3024 # of MED. \n This description is located by the following link:
3025 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3026 # @return the Id of the new edge
3027 # @ingroup l2_modif_add
3028 def AddEdge(self, IDsOfNodes):
3029 return self.editor.AddEdge(IDsOfNodes)
3031 ## Create a linear or quadratic face (this is determined
3032 # by the number of given nodes).
3033 # @param IDsOfNodes the list of node IDs for creation of the element.
3034 # The order of nodes in this list should correspond to the description
3035 # of MED. \n This description is located by the following link:
3036 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3037 # @return the Id of the new face
3038 # @ingroup l2_modif_add
3039 def AddFace(self, IDsOfNodes):
3040 return self.editor.AddFace(IDsOfNodes)
3042 ## Add a polygonal face to the mesh by the list of node IDs
3043 # @param IdsOfNodes the list of node IDs for creation of the element.
3044 # @return the Id of the new face
3045 # @ingroup l2_modif_add
3046 def AddPolygonalFace(self, IdsOfNodes):
3047 return self.editor.AddPolygonalFace(IdsOfNodes)
3049 ## Add a quadratic polygonal face to the mesh by the list of node IDs
3050 # @param IdsOfNodes the list of node IDs for creation of the element;
3051 # corner nodes follow first.
3052 # @return the Id of the new face
3053 # @ingroup l2_modif_add
3054 def AddQuadPolygonalFace(self, IdsOfNodes):
3055 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
3057 ## Create both simple and quadratic volume (this is determined
3058 # by the number of given nodes).
3059 # @param IDsOfNodes the list of node IDs for creation of the element.
3060 # The order of nodes in this list should correspond to the description
3061 # of MED. \n This description is located by the following link:
3062 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3063 # @return the Id of the new volumic element
3064 # @ingroup l2_modif_add
3065 def AddVolume(self, IDsOfNodes):
3066 return self.editor.AddVolume(IDsOfNodes)
3068 ## Create a volume of many faces, giving nodes for each face.
3069 # @param IdsOfNodes the list of node IDs for volume creation face by face.
3070 # @param Quantities the list of integer values, Quantities[i]
3071 # gives the quantity of nodes in face number i.
3072 # @return the Id of the new volumic element
3073 # @ingroup l2_modif_add
3074 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
3075 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
3077 ## Create a volume of many faces, giving the IDs of the existing faces.
3078 # @param IdsOfFaces the list of face IDs for volume creation.
3080 # Note: The created volume will refer only to the nodes
3081 # of the given faces, not to the faces themselves.
3082 # @return the Id of the new volumic element
3083 # @ingroup l2_modif_add
3084 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
3085 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
3088 ## @brief Binds a node to a vertex
3089 # @param NodeID a node ID
3090 # @param Vertex a vertex or vertex ID
3091 # @return True if succeed else raises an exception
3092 # @ingroup l2_modif_add
3093 def SetNodeOnVertex(self, NodeID, Vertex):
3094 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
3095 VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
3099 self.editor.SetNodeOnVertex(NodeID, VertexID)
3100 except SALOME.SALOME_Exception as inst:
3101 raise ValueError(inst.details.text)
3105 ## @brief Stores the node position on an edge
3106 # @param NodeID a node ID
3107 # @param Edge an edge or edge ID
3108 # @param paramOnEdge a parameter on the edge where the node is located
3109 # @return True if succeed else raises an exception
3110 # @ingroup l2_modif_add
3111 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
3112 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
3113 EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
3117 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
3118 except SALOME.SALOME_Exception as inst:
3119 raise ValueError(inst.details.text)
3122 ## @brief Stores node position on a face
3123 # @param NodeID a node ID
3124 # @param Face a face or face ID
3125 # @param u U parameter on the face where the node is located
3126 # @param v V parameter on the face where the node is located
3127 # @return True if succeed else raises an exception
3128 # @ingroup l2_modif_add
3129 def SetNodeOnFace(self, NodeID, Face, u, v):
3130 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
3131 FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
3135 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
3136 except SALOME.SALOME_Exception as inst:
3137 raise ValueError(inst.details.text)
3140 ## @brief Binds a node to a solid
3141 # @param NodeID a node ID
3142 # @param Solid a solid or solid ID
3143 # @return True if succeed else raises an exception
3144 # @ingroup l2_modif_add
3145 def SetNodeInVolume(self, NodeID, Solid):
3146 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
3147 SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
3151 self.editor.SetNodeInVolume(NodeID, SolidID)
3152 except SALOME.SALOME_Exception as inst:
3153 raise ValueError(inst.details.text)
3156 ## @brief Bind an element to a shape
3157 # @param ElementID an element ID
3158 # @param Shape a shape or shape ID
3159 # @return True if succeed else raises an exception
3160 # @ingroup l2_modif_add
3161 def SetMeshElementOnShape(self, ElementID, Shape):
3162 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
3163 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3167 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
3168 except SALOME.SALOME_Exception as inst:
3169 raise ValueError(inst.details.text)
3173 ## Move the node with the given id
3174 # @param NodeID the id of the node
3175 # @param x a new X coordinate
3176 # @param y a new Y coordinate
3177 # @param z a new Z coordinate
3178 # @return True if succeed else False
3179 # @ingroup l2_modif_edit
3180 def MoveNode(self, NodeID, x, y, z):
3181 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3182 if hasVars: self.mesh.SetParameters(Parameters)
3183 return self.editor.MoveNode(NodeID, x, y, z)
3185 ## Find the node closest to a point and moves it to a point location
3186 # @param x the X coordinate of a point
3187 # @param y the Y coordinate of a point
3188 # @param z the Z coordinate of a point
3189 # @param NodeID if specified (>0), the node with this ID is moved,
3190 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
3191 # @return the ID of a node
3192 # @ingroup l2_modif_edit
3193 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3194 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3195 if hasVars: self.mesh.SetParameters(Parameters)
3196 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3198 ## Find the node closest to a point
3199 # @param x the X coordinate of a point
3200 # @param y the Y coordinate of a point
3201 # @param z the Z coordinate of a point
3202 # @return the ID of a node
3203 # @ingroup l1_meshinfo
3204 def FindNodeClosestTo(self, x, y, z):
3205 #preview = self.mesh.GetMeshEditPreviewer()
3206 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3207 return self.editor.FindNodeClosestTo(x, y, z)
3209 ## Find the elements where a point lays IN or ON
3210 # @param x the X coordinate of a point
3211 # @param y the Y coordinate of a point
3212 # @param z the Z coordinate of a point
3213 # @param elementType type of elements to find; either of
3214 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3215 # means elements of any type excluding nodes, discrete and 0D elements.
3216 # @param meshPart a part of mesh (group, sub-mesh) to search within
3217 # @return list of IDs of found elements
3218 # @ingroup l1_meshinfo
3219 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3221 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
3223 return self.editor.FindElementsByPoint(x, y, z, elementType)
3225 ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
3226 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
3227 # UNKNOWN state means that either mesh is wrong or the analysis fails.
3228 # @ingroup l1_meshinfo
3229 def GetPointState(self, x, y, z):
3230 return self.editor.GetPointState(x, y, z)
3232 ## Check if a 2D mesh is manifold
3233 # @ingroup l1_controls
3234 def IsManifold(self):
3235 return self.editor.IsManifold()
3237 ## Check if orientation of 2D elements is coherent
3238 # @ingroup l1_controls
3239 def IsCoherentOrientation2D(self):
3240 return self.editor.IsCoherentOrientation2D()
3242 ## Find the node closest to a point and moves it to a point location
3243 # @param x the X coordinate of a point
3244 # @param y the Y coordinate of a point
3245 # @param z the Z coordinate of a point
3246 # @return the ID of a moved node
3247 # @ingroup l2_modif_edit
3248 def MeshToPassThroughAPoint(self, x, y, z):
3249 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3251 ## Replace two neighbour triangles sharing Node1-Node2 link
3252 # with the triangles built on the same 4 nodes but having other common link.
3253 # @param NodeID1 the ID of the first node
3254 # @param NodeID2 the ID of the second node
3255 # @return false if proper faces were not found
3256 # @ingroup l2_modif_cutquadr
3257 def InverseDiag(self, NodeID1, NodeID2):
3258 return self.editor.InverseDiag(NodeID1, NodeID2)
3260 ## Replace two neighbour triangles sharing Node1-Node2 link
3261 # with a quadrangle built on the same 4 nodes.
3262 # @param NodeID1 the ID of the first node
3263 # @param NodeID2 the ID of the second node
3264 # @return false if proper faces were not found
3265 # @ingroup l2_modif_unitetri
3266 def DeleteDiag(self, NodeID1, NodeID2):
3267 return self.editor.DeleteDiag(NodeID1, NodeID2)
3269 ## Reorient elements by ids
3270 # @param IDsOfElements if undefined reorients all mesh elements
3271 # @return True if succeed else False
3272 # @ingroup l2_modif_changori
3273 def Reorient(self, IDsOfElements=None):
3274 if IDsOfElements == None:
3275 IDsOfElements = self.GetElementsId()
3276 return self.editor.Reorient(IDsOfElements)
3278 ## Reorient all elements of the object
3279 # @param theObject mesh, submesh or group
3280 # @return True if succeed else False
3281 # @ingroup l2_modif_changori
3282 def ReorientObject(self, theObject):
3283 if ( isinstance( theObject, Mesh )):
3284 theObject = theObject.GetMesh()
3285 return self.editor.ReorientObject(theObject)
3287 ## Reorient faces contained in \a the2DObject.
3288 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3289 # @param theDirection is a desired direction of normal of \a theFace.
3290 # It can be either a GEOM vector or a list of coordinates [x,y,z].
3291 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3292 # compared with theDirection. It can be either ID of face or a point
3293 # by which the face will be found. The point can be given as either
3294 # a GEOM vertex or a list of point coordinates.
3295 # @return number of reoriented faces
3296 # @ingroup l2_modif_changori
3297 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3298 unRegister = genObjUnRegister()
3300 if isinstance( the2DObject, Mesh ):
3301 the2DObject = the2DObject.GetMesh()
3302 if isinstance( the2DObject, list ):
3303 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3304 unRegister.set( the2DObject )
3305 # check theDirection
3306 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3307 theDirection = self.smeshpyD.GetDirStruct( theDirection )
3308 if isinstance( theDirection, list ):
3309 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
3310 # prepare theFace and thePoint
3311 theFace = theFaceOrPoint
3312 thePoint = PointStruct(0,0,0)
3313 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3314 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3316 if isinstance( theFaceOrPoint, list ):
3317 thePoint = PointStruct( *theFaceOrPoint )
3319 if isinstance( theFaceOrPoint, PointStruct ):
3320 thePoint = theFaceOrPoint
3322 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3324 ## Reorient faces according to adjacent volumes.
3325 # @param the2DObject is a mesh, sub-mesh, group or list of
3326 # either IDs of faces or face groups.
3327 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3328 # @param theOutsideNormal to orient faces to have their normals
3329 # pointing either \a outside or \a inside the adjacent volumes.
3330 # @return number of reoriented faces.
3331 # @ingroup l2_modif_changori
3332 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3333 unRegister = genObjUnRegister()
3335 if not isinstance( the2DObject, list ):
3336 the2DObject = [ the2DObject ]
3337 elif the2DObject and isinstance( the2DObject[0], int ):
3338 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3339 unRegister.set( the2DObject )
3340 the2DObject = [ the2DObject ]
3341 for i,obj2D in enumerate( the2DObject ):
3342 if isinstance( obj2D, Mesh ):
3343 the2DObject[i] = obj2D.GetMesh()
3344 if isinstance( obj2D, list ):
3345 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3346 unRegister.set( the2DObject[i] )
3348 if isinstance( the3DObject, Mesh ):
3349 the3DObject = the3DObject.GetMesh()
3350 if isinstance( the3DObject, list ):
3351 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3352 unRegister.set( the3DObject )
3353 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3355 ## Fuse the neighbouring triangles into quadrangles.
3356 # @param IDsOfElements The triangles to be fused.
3357 # @param theCriterion a numerical functor, in terms of enum SMESH.FunctorType, used to
3358 # applied to possible quadrangles to choose a neighbour to fuse with.
3359 # Type SMESH.FunctorType._items in the Python Console to see all items.
3360 # Note that not all items correspond to numerical functors.
3361 # @param MaxAngle is the maximum angle between element normals at which the fusion
3362 # is still performed; theMaxAngle is measured in radians.
3363 # Also it could be a name of variable which defines angle in degrees.
3364 # @return TRUE in case of success, FALSE otherwise.
3365 # @ingroup l2_modif_unitetri
3366 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3367 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3368 self.mesh.SetParameters(Parameters)
3369 if not IDsOfElements:
3370 IDsOfElements = self.GetElementsId()
3371 Functor = self.smeshpyD.GetFunctor(theCriterion)
3372 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3374 ## Fuse the neighbouring triangles of the object into quadrangles
3375 # @param theObject is mesh, submesh or group
3376 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType,
3377 # applied to possible quadrangles to choose a neighbour to fuse with.
3378 # Type SMESH.FunctorType._items in the Python Console to see all items.
3379 # Note that not all items correspond to numerical functors.
3380 # @param MaxAngle a max angle between element normals at which the fusion
3381 # is still performed; theMaxAngle is measured in radians.
3382 # @return TRUE in case of success, FALSE otherwise.
3383 # @ingroup l2_modif_unitetri
3384 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3385 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3386 self.mesh.SetParameters(Parameters)
3387 if isinstance( theObject, Mesh ):
3388 theObject = theObject.GetMesh()
3389 Functor = self.smeshpyD.GetFunctor(theCriterion)
3390 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3392 ## Split quadrangles into triangles.
3393 # @param IDsOfElements the faces to be split.
3394 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3395 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3396 # value, then quadrangles will be split by the smallest diagonal.
3397 # Type SMESH.FunctorType._items in the Python Console to see all items.
3398 # Note that not all items correspond to numerical functors.
3399 # @return TRUE in case of success, FALSE otherwise.
3400 # @ingroup l2_modif_cutquadr
3401 def QuadToTri (self, IDsOfElements, theCriterion = None):
3402 if IDsOfElements == []:
3403 IDsOfElements = self.GetElementsId()
3404 if theCriterion is None:
3405 theCriterion = FT_MaxElementLength2D
3406 Functor = self.smeshpyD.GetFunctor(theCriterion)
3407 return self.editor.QuadToTri(IDsOfElements, Functor)
3409 ## Split quadrangles into triangles.
3410 # @param theObject the object from which the list of elements is taken,
3411 # this is mesh, submesh or group
3412 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3413 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3414 # value, then quadrangles will be split by the smallest diagonal.
3415 # Type SMESH.FunctorType._items in the Python Console to see all items.
3416 # Note that not all items correspond to numerical functors.
3417 # @return TRUE in case of success, FALSE otherwise.
3418 # @ingroup l2_modif_cutquadr
3419 def QuadToTriObject (self, theObject, theCriterion = None):
3420 if ( isinstance( theObject, Mesh )):
3421 theObject = theObject.GetMesh()
3422 if theCriterion is None:
3423 theCriterion = FT_MaxElementLength2D
3424 Functor = self.smeshpyD.GetFunctor(theCriterion)
3425 return self.editor.QuadToTriObject(theObject, Functor)
3427 ## Split each of given quadrangles into 4 triangles. A node is added at the center of
3429 # @param theElements the faces to be split. This can be either mesh, sub-mesh,
3430 # group or a list of face IDs. By default all quadrangles are split
3431 # @ingroup l2_modif_cutquadr
3432 def QuadTo4Tri (self, theElements=[]):
3433 unRegister = genObjUnRegister()
3434 if isinstance( theElements, Mesh ):
3435 theElements = theElements.mesh
3436 elif not theElements:
3437 theElements = self.mesh
3438 elif isinstance( theElements, list ):
3439 theElements = self.GetIDSource( theElements, SMESH.FACE )
3440 unRegister.set( theElements )
3441 return self.editor.QuadTo4Tri( theElements )
3443 ## Split quadrangles into triangles.
3444 # @param IDsOfElements the faces to be split
3445 # @param Diag13 is used to choose a diagonal for splitting.
3446 # @return TRUE in case of success, FALSE otherwise.
3447 # @ingroup l2_modif_cutquadr
3448 def SplitQuad (self, IDsOfElements, Diag13):
3449 if IDsOfElements == []:
3450 IDsOfElements = self.GetElementsId()
3451 return self.editor.SplitQuad(IDsOfElements, Diag13)
3453 ## Split quadrangles into triangles.
3454 # @param theObject the object from which the list of elements is taken,
3455 # this is mesh, submesh or group
3456 # @param Diag13 is used to choose a diagonal for splitting.
3457 # @return TRUE in case of success, FALSE otherwise.
3458 # @ingroup l2_modif_cutquadr
3459 def SplitQuadObject (self, theObject, Diag13):
3460 if ( isinstance( theObject, Mesh )):
3461 theObject = theObject.GetMesh()
3462 return self.editor.SplitQuadObject(theObject, Diag13)
3464 ## Find a better splitting of the given quadrangle.
3465 # @param IDOfQuad the ID of the quadrangle to be split.
3466 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3467 # choose a diagonal for splitting.
3468 # Type SMESH.FunctorType._items in the Python Console to see all items.
3469 # Note that not all items correspond to numerical functors.
3470 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3471 # diagonal is better, 0 if error occurs.
3472 # @ingroup l2_modif_cutquadr
3473 def BestSplit (self, IDOfQuad, theCriterion):
3474 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3476 ## Split volumic elements into tetrahedrons
3477 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3478 # @param method flags passing splitting method:
3479 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3480 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3481 # @ingroup l2_modif_cutquadr
3482 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3483 unRegister = genObjUnRegister()
3484 if isinstance( elems, Mesh ):
3485 elems = elems.GetMesh()
3486 if ( isinstance( elems, list )):
3487 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3488 unRegister.set( elems )
3489 self.editor.SplitVolumesIntoTetra(elems, method)
3492 ## Split bi-quadratic elements into linear ones without creation of additional nodes:
3493 # - bi-quadratic triangle will be split into 3 linear quadrangles;
3494 # - bi-quadratic quadrangle will be split into 4 linear quadrangles;
3495 # - tri-quadratic hexahedron will be split into 8 linear hexahedra.
3496 # Quadratic elements of lower dimension adjacent to the split bi-quadratic element
3497 # will be split in order to keep the mesh conformal.
3498 # @param elems - elements to split: sub-meshes, groups, filters or element IDs;
3499 # if None (default), all bi-quadratic elements will be split
3500 # @ingroup l2_modif_cutquadr
3501 def SplitBiQuadraticIntoLinear(self, elems=None):
3502 unRegister = genObjUnRegister()
3503 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
3504 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
3505 unRegister.set( elems )
3507 elems = [ self.GetMesh() ]
3508 if isinstance( elems, Mesh ):
3509 elems = [ elems.GetMesh() ]
3510 if not isinstance( elems, list ):
3512 self.editor.SplitBiQuadraticIntoLinear( elems )
3514 ## Split hexahedra into prisms
3515 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3516 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3517 # gives a normal vector defining facets to split into triangles.
3518 # @a startHexPoint can be either a triple of coordinates or a vertex.
3519 # @param facetNormal a normal to a facet to split into triangles of a
3520 # hexahedron found by @a startHexPoint.
3521 # @a facetNormal can be either a triple of coordinates or an edge.
3522 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3523 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3524 # @param allDomains if @c False, only hexahedra adjacent to one closest
3525 # to @a startHexPoint are split, else @a startHexPoint
3526 # is used to find the facet to split in all domains present in @a elems.
3527 # @ingroup l2_modif_cutquadr
3528 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3529 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3531 unRegister = genObjUnRegister()
3532 if isinstance( elems, Mesh ):
3533 elems = elems.GetMesh()
3534 if ( isinstance( elems, list )):
3535 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3536 unRegister.set( elems )
3539 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3540 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3541 elif isinstance( startHexPoint, list ):
3542 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3545 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3546 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3547 elif isinstance( facetNormal, list ):
3548 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3551 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3553 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3555 ## Split quadrangle faces near triangular facets of volumes
3557 # @ingroup l2_modif_cutquadr
3558 def SplitQuadsNearTriangularFacets(self):
3559 faces_array = self.GetElementsByType(SMESH.FACE)
3560 for face_id in faces_array:
3561 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3562 quad_nodes = self.mesh.GetElemNodes(face_id)
3563 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3564 isVolumeFound = False
3565 for node1_elem in node1_elems:
3566 if not isVolumeFound:
3567 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3568 nb_nodes = self.GetElemNbNodes(node1_elem)
3569 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3570 volume_elem = node1_elem
3571 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3572 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3573 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3574 isVolumeFound = True
3575 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3576 self.SplitQuad([face_id], False) # diagonal 2-4
3577 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3578 isVolumeFound = True
3579 self.SplitQuad([face_id], True) # diagonal 1-3
3580 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3581 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3582 isVolumeFound = True
3583 self.SplitQuad([face_id], True) # diagonal 1-3
3585 ## @brief Splits hexahedrons into tetrahedrons.
3587 # This operation uses pattern mapping functionality for splitting.
3588 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3589 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3590 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3591 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3592 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3593 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3594 # @return TRUE in case of success, FALSE otherwise.
3595 # @ingroup l2_modif_cutquadr
3596 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3597 # Pattern: 5.---------.6
3602 # (0,0,1) 4.---------.7 * |
3609 # (0,0,0) 0.---------.3
3610 pattern_tetra = "!!! Nb of points: \n 8 \n\
3620 !!! Indices of points of 6 tetras: \n\
3628 pattern = self.smeshpyD.GetPattern()
3629 isDone = pattern.LoadFromFile(pattern_tetra)
3631 print('Pattern.LoadFromFile :', pattern.GetErrorCode())
3634 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3635 isDone = pattern.MakeMesh(self.mesh, False, False)
3636 if not isDone: print('Pattern.MakeMesh :', pattern.GetErrorCode())
3638 # split quafrangle faces near triangular facets of volumes
3639 self.SplitQuadsNearTriangularFacets()
3643 ## @brief Split hexahedrons into prisms.
3645 # Uses the pattern mapping functionality for splitting.
3646 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3647 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3648 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3649 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3650 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3651 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3652 # @return TRUE in case of success, FALSE otherwise.
3653 # @ingroup l2_modif_cutquadr
3654 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3655 # Pattern: 5.---------.6
3660 # (0,0,1) 4.---------.7 |
3667 # (0,0,0) 0.---------.3
3668 pattern_prism = "!!! Nb of points: \n 8 \n\
3678 !!! Indices of points of 2 prisms: \n\
3682 pattern = self.smeshpyD.GetPattern()
3683 isDone = pattern.LoadFromFile(pattern_prism)
3685 print('Pattern.LoadFromFile :', pattern.GetErrorCode())
3688 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3689 isDone = pattern.MakeMesh(self.mesh, False, False)
3690 if not isDone: print('Pattern.MakeMesh :', pattern.GetErrorCode())
3692 # Split quafrangle faces near triangular facets of volumes
3693 self.SplitQuadsNearTriangularFacets()
3698 # @param IDsOfElements the list if ids of elements to smooth
3699 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3700 # Note that nodes built on edges and boundary nodes are always fixed.
3701 # @param MaxNbOfIterations the maximum number of iterations
3702 # @param MaxAspectRatio varies in range [1.0, inf]
3703 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3704 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3705 # @return TRUE in case of success, FALSE otherwise.
3706 # @ingroup l2_modif_smooth
3707 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3708 MaxNbOfIterations, MaxAspectRatio, Method):
3709 if IDsOfElements == []:
3710 IDsOfElements = self.GetElementsId()
3711 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3712 self.mesh.SetParameters(Parameters)
3713 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3714 MaxNbOfIterations, MaxAspectRatio, Method)
3716 ## Smooth elements which belong to the given object
3717 # @param theObject the object to smooth
3718 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3719 # Note that nodes built on edges and boundary nodes are always fixed.
3720 # @param MaxNbOfIterations the maximum number of iterations
3721 # @param MaxAspectRatio varies in range [1.0, inf]
3722 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3723 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3724 # @return TRUE in case of success, FALSE otherwise.
3725 # @ingroup l2_modif_smooth
3726 def SmoothObject(self, theObject, IDsOfFixedNodes,
3727 MaxNbOfIterations, MaxAspectRatio, Method):
3728 if ( isinstance( theObject, Mesh )):
3729 theObject = theObject.GetMesh()
3730 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3731 MaxNbOfIterations, MaxAspectRatio, Method)
3733 ## Parametrically smooth the given elements
3734 # @param IDsOfElements the list if ids of elements to smooth
3735 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3736 # Note that nodes built on edges and boundary nodes are always fixed.
3737 # @param MaxNbOfIterations the maximum number of iterations
3738 # @param MaxAspectRatio varies in range [1.0, inf]
3739 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3740 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3741 # @return TRUE in case of success, FALSE otherwise.
3742 # @ingroup l2_modif_smooth
3743 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3744 MaxNbOfIterations, MaxAspectRatio, Method):
3745 if IDsOfElements == []:
3746 IDsOfElements = self.GetElementsId()
3747 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3748 self.mesh.SetParameters(Parameters)
3749 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3750 MaxNbOfIterations, MaxAspectRatio, Method)
3752 ## Parametrically smooth the elements which belong to the given object
3753 # @param theObject the object to smooth
3754 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3755 # Note that nodes built on edges and boundary nodes are always fixed.
3756 # @param MaxNbOfIterations the maximum number of iterations
3757 # @param MaxAspectRatio varies in range [1.0, inf]
3758 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3759 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3760 # @return TRUE in case of success, FALSE otherwise.
3761 # @ingroup l2_modif_smooth
3762 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3763 MaxNbOfIterations, MaxAspectRatio, Method):
3764 if ( isinstance( theObject, Mesh )):
3765 theObject = theObject.GetMesh()
3766 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3767 MaxNbOfIterations, MaxAspectRatio, Method)
3769 ## Convert the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3770 # them with quadratic with the same id.
3771 # @param theForce3d new node creation method:
3772 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3773 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3774 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3775 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3776 # @return SMESH.ComputeError which can hold a warning
3777 # @ingroup l2_modif_tofromqu
3778 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3779 if isinstance( theSubMesh, Mesh ):
3780 theSubMesh = theSubMesh.mesh
3782 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3785 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3787 self.editor.ConvertToQuadratic(theForce3d)
3788 error = self.editor.GetLastError()
3789 if error and error.comment:
3790 print(error.comment)
3793 ## Convert the mesh from quadratic to ordinary,
3794 # deletes old quadratic elements, \n replacing
3795 # them with ordinary mesh elements with the same id.
3796 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3797 # @ingroup l2_modif_tofromqu
3798 def ConvertFromQuadratic(self, theSubMesh=None):
3800 self.editor.ConvertFromQuadraticObject(theSubMesh)
3802 return self.editor.ConvertFromQuadratic()
3804 ## Create 2D mesh as skin on boundary faces of a 3D mesh
3805 # @return TRUE if operation has been completed successfully, FALSE otherwise
3806 # @ingroup l2_modif_add
3807 def Make2DMeshFrom3D(self):
3808 return self.editor.Make2DMeshFrom3D()
3810 ## Create missing boundary elements
3811 # @param elements - elements whose boundary is to be checked:
3812 # mesh, group, sub-mesh or list of elements
3813 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3814 # @param dimension - defines type of boundary elements to create, either of
3815 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3816 # SMESH.BND_1DFROM3D create mesh edges on all borders of free facets of 3D cells
3817 # @param groupName - a name of group to store created boundary elements in,
3818 # "" means not to create the group
3819 # @param meshName - a name of new mesh to store created boundary elements in,
3820 # "" means not to create the new mesh
3821 # @param toCopyElements - if true, the checked elements will be copied into
3822 # the new mesh else only boundary elements will be copied into the new mesh
3823 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3824 # boundary elements will be copied into the new mesh
3825 # @return tuple (mesh, group) where boundary elements were added to
3826 # @ingroup l2_modif_add
3827 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3828 toCopyElements=False, toCopyExistingBondary=False):
3829 unRegister = genObjUnRegister()
3830 if isinstance( elements, Mesh ):
3831 elements = elements.GetMesh()
3832 if ( isinstance( elements, list )):
3833 elemType = SMESH.ALL
3834 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3835 elements = self.editor.MakeIDSource(elements, elemType)
3836 unRegister.set( elements )
3837 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3838 toCopyElements,toCopyExistingBondary)
3839 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3843 # @brief Create missing boundary elements around either the whole mesh or
3844 # groups of elements
3845 # @param dimension - defines type of boundary elements to create, either of
3846 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3847 # @param groupName - a name of group to store all boundary elements in,
3848 # "" means not to create the group
3849 # @param meshName - a name of a new mesh, which is a copy of the initial
3850 # mesh + created boundary elements; "" means not to create the new mesh
3851 # @param toCopyAll - if true, the whole initial mesh will be copied into
3852 # the new mesh else only boundary elements will be copied into the new mesh
3853 # @param groups - groups of elements to make boundary around
3854 # @retval tuple( long, mesh, groups )
3855 # long - number of added boundary elements
3856 # mesh - the mesh where elements were added to
3857 # group - the group of boundary elements or None
3859 # @ingroup l2_modif_add
3860 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3861 toCopyAll=False, groups=[]):
3862 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3864 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3865 return nb, mesh, group
3867 ## Renumber mesh nodes (Obsolete, does nothing)
3868 # @ingroup l2_modif_renumber
3869 def RenumberNodes(self):
3870 self.editor.RenumberNodes()
3872 ## Renumber mesh elements (Obsole, does nothing)
3873 # @ingroup l2_modif_renumber
3874 def RenumberElements(self):
3875 self.editor.RenumberElements()
3877 ## Private method converting \a arg into a list of SMESH_IdSource's
3878 def _getIdSourceList(self, arg, idType, unRegister):
3879 if arg and isinstance( arg, list ):
3880 if isinstance( arg[0], int ):
3881 arg = self.GetIDSource( arg, idType )
3882 unRegister.set( arg )
3883 elif isinstance( arg[0], Mesh ):
3884 arg[0] = arg[0].GetMesh()
3885 elif isinstance( arg, Mesh ):
3887 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3891 ## Generate new elements by rotation of the given elements and nodes around the axis
3892 # @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3893 # @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3894 # @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3895 # @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3896 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3897 # which defines angle in degrees
3898 # @param NbOfSteps the number of steps
3899 # @param Tolerance tolerance
3900 # @param MakeGroups forces the generation of new groups from existing ones
3901 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3902 # of all steps, else - size of each step
3903 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3904 # @ingroup l2_modif_extrurev
3905 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3906 MakeGroups=False, TotalAngle=False):
3907 unRegister = genObjUnRegister()
3908 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3909 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3910 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3912 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3913 Axis = self.smeshpyD.GetAxisStruct( Axis )
3914 if isinstance( Axis, list ):
3915 Axis = SMESH.AxisStruct( *Axis )
3917 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3918 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3919 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3920 self.mesh.SetParameters(Parameters)
3921 if TotalAngle and NbOfSteps:
3922 AngleInRadians /= NbOfSteps
3923 return self.editor.RotationSweepObjects( nodes, edges, faces,
3924 Axis, AngleInRadians,
3925 NbOfSteps, Tolerance, MakeGroups)
3927 ## Generate new elements by rotation of the elements around the axis
3928 # @param IDsOfElements the list of ids of elements to sweep
3929 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3930 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3931 # @param NbOfSteps the number of steps
3932 # @param Tolerance tolerance
3933 # @param MakeGroups forces the generation of new groups from existing ones
3934 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3935 # of all steps, else - size of each step
3936 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3937 # @ingroup l2_modif_extrurev
3938 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3939 MakeGroups=False, TotalAngle=False):
3940 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3941 AngleInRadians, NbOfSteps, Tolerance,
3942 MakeGroups, TotalAngle)
3944 ## Generate new elements by rotation of the elements of object around the axis
3945 # @param theObject object which elements should be sweeped.
3946 # It can be a mesh, a sub mesh or a group.
3947 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3948 # @param AngleInRadians the angle of Rotation
3949 # @param NbOfSteps number of steps
3950 # @param Tolerance tolerance
3951 # @param MakeGroups forces the generation of new groups from existing ones
3952 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3953 # of all steps, else - size of each step
3954 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3955 # @ingroup l2_modif_extrurev
3956 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3957 MakeGroups=False, TotalAngle=False):
3958 return self.RotationSweepObjects( [], theObject, theObject, Axis,
3959 AngleInRadians, NbOfSteps, Tolerance,
3960 MakeGroups, TotalAngle )
3962 ## Generate new elements by rotation of the elements of object around the axis
3963 # @param theObject object which elements should be sweeped.
3964 # It can be a mesh, a sub mesh or a group.
3965 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3966 # @param AngleInRadians the angle of Rotation
3967 # @param NbOfSteps number of steps
3968 # @param Tolerance tolerance
3969 # @param MakeGroups forces the generation of new groups from existing ones
3970 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3971 # of all steps, else - size of each step
3972 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3973 # @ingroup l2_modif_extrurev
3974 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3975 MakeGroups=False, TotalAngle=False):
3976 return self.RotationSweepObjects([],theObject,[], Axis,
3977 AngleInRadians, NbOfSteps, Tolerance,
3978 MakeGroups, TotalAngle)
3980 ## Generate new elements by rotation of the elements of object around the axis
3981 # @param theObject object which elements should be sweeped.
3982 # It can be a mesh, a sub mesh or a group.
3983 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3984 # @param AngleInRadians the angle of Rotation
3985 # @param NbOfSteps number of steps
3986 # @param Tolerance tolerance
3987 # @param MakeGroups forces the generation of new groups from existing ones
3988 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3989 # of all steps, else - size of each step
3990 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3991 # @ingroup l2_modif_extrurev
3992 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3993 MakeGroups=False, TotalAngle=False):
3994 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3995 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3997 ## Generate new elements by extrusion of the given elements and nodes
3998 # @param nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3999 # @param edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
4000 # @param faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
4001 # @param StepVector vector or DirStruct or 3 vector components, defining
4002 # the direction and value of extrusion for one step (the total extrusion
4003 # length will be NbOfSteps * ||StepVector||)
4004 # @param NbOfSteps the number of steps
4005 # @param MakeGroups forces the generation of new groups from existing ones
4006 # @param scaleFactors optional scale factors to apply during extrusion
4007 # @param linearVariation if @c True, scaleFactors are spread over all @a scaleFactors,
4008 # else scaleFactors[i] is applied to nodes at the i-th extrusion step
4009 # @param basePoint optional scaling center; if not provided, a gravity center of
4010 # nodes and elements being extruded is used as the scaling center.
4012 # - a list of tree components of the point or
4015 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4016 # @ingroup l2_modif_extrurev
4017 # @ref tui_extrusion example
4018 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False,
4019 scaleFactors=[], linearVariation=False, basePoint=[] ):
4020 unRegister = genObjUnRegister()
4021 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
4022 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
4023 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
4025 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
4026 StepVector = self.smeshpyD.GetDirStruct(StepVector)
4027 if isinstance( StepVector, list ):
4028 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
4030 if isinstance( basePoint, int):
4031 xyz = self.GetNodeXYZ( basePoint )
4033 raise RuntimeError("Invalid node ID: %s" % basePoint)
4035 if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
4036 basePoint = self.geompyD.PointCoordinates( basePoint )
4038 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
4039 Parameters = StepVector.PS.parameters + var_separator + Parameters
4040 self.mesh.SetParameters(Parameters)
4042 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
4043 StepVector, NbOfSteps,
4044 scaleFactors, linearVariation, basePoint,
4048 ## Generate new elements by extrusion of the elements with given ids
4049 # @param IDsOfElements the list of ids of elements or nodes for extrusion
4050 # @param StepVector vector or DirStruct or 3 vector components, defining
4051 # the direction and value of extrusion for one step (the total extrusion
4052 # length will be NbOfSteps * ||StepVector||)
4053 # @param NbOfSteps the number of steps
4054 # @param MakeGroups forces the generation of new groups from existing ones
4055 # @param IsNodes is True if elements with given ids are nodes
4056 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4057 # @ingroup l2_modif_extrurev
4058 # @ref tui_extrusion example
4059 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
4061 if IsNodes: n = IDsOfElements
4062 else : e,f, = IDsOfElements,IDsOfElements
4063 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
4065 ## Generate new elements by extrusion along the normal to a discretized surface or wire
4066 # @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh.
4067 # Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
4068 # @param StepSize length of one extrusion step (the total extrusion
4069 # length will be \a NbOfSteps * \a StepSize ).
4070 # @param NbOfSteps number of extrusion steps.
4071 # @param ByAverageNormal if True each node is translated by \a StepSize
4072 # along the average of the normal vectors to the faces sharing the node;
4073 # else each node is translated along the same average normal till
4074 # intersection with the plane got by translation of the face sharing
4075 # the node along its own normal by \a StepSize.
4076 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
4077 # for every node of \a Elements.
4078 # @param MakeGroups forces generation of new groups from existing ones.
4079 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
4080 # is not yet implemented. This parameter is used if \a Elements contains
4081 # both faces and edges, i.e. \a Elements is a Mesh.
4082 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
4083 # empty list otherwise.
4084 # @ingroup l2_modif_extrurev
4085 # @ref tui_extrusion example
4086 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
4087 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
4088 unRegister = genObjUnRegister()
4089 if isinstance( Elements, Mesh ):
4090 Elements = [ Elements.GetMesh() ]
4091 if isinstance( Elements, list ):
4093 raise RuntimeError("Elements empty!")
4094 if isinstance( Elements[0], int ):
4095 Elements = self.GetIDSource( Elements, SMESH.ALL )
4096 unRegister.set( Elements )
4097 if not isinstance( Elements, list ):
4098 Elements = [ Elements ]
4099 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
4100 self.mesh.SetParameters(Parameters)
4101 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
4102 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
4104 ## Generate new elements by extrusion of the elements or nodes which belong to the object
4105 # @param theObject the object whose elements or nodes should be processed.
4106 # It can be a mesh, a sub-mesh or a group.
4107 # @param StepVector vector or DirStruct or 3 vector components, defining
4108 # the direction and value of extrusion for one step (the total extrusion
4109 # length will be NbOfSteps * ||StepVector||)
4110 # @param NbOfSteps the number of steps
4111 # @param MakeGroups forces the generation of new groups from existing ones
4112 # @param IsNodes is True if elements to extrude are nodes
4113 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4114 # @ingroup l2_modif_extrurev
4115 # @ref tui_extrusion example
4116 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
4118 if IsNodes: n = theObject
4119 else : e,f, = theObject,theObject
4120 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
4122 ## Generate new elements by extrusion of edges which belong to the object
4123 # @param theObject object whose 1D elements should be processed.
4124 # It can be a mesh, a sub-mesh or a group.
4125 # @param StepVector vector or DirStruct or 3 vector components, defining
4126 # the direction and value of extrusion for one step (the total extrusion
4127 # length will be NbOfSteps * ||StepVector||)
4128 # @param NbOfSteps the number of steps
4129 # @param MakeGroups to generate new groups from existing ones
4130 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4131 # @ingroup l2_modif_extrurev
4132 # @ref tui_extrusion example
4133 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
4134 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
4136 ## Generate new elements by extrusion of faces which belong to the object
4137 # @param theObject object whose 2D elements should be processed.
4138 # It can be a mesh, a sub-mesh or a group.
4139 # @param StepVector vector or DirStruct or 3 vector components, defining
4140 # the direction and value of extrusion for one step (the total extrusion
4141 # length will be NbOfSteps * ||StepVector||)
4142 # @param NbOfSteps the number of steps
4143 # @param MakeGroups forces the generation of new groups from existing ones
4144 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4145 # @ingroup l2_modif_extrurev
4146 # @ref tui_extrusion example
4147 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
4148 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
4150 ## Generate new elements by extrusion of the elements with given ids
4151 # @param IDsOfElements is ids of elements
4152 # @param StepVector vector or DirStruct or 3 vector components, defining
4153 # the direction and value of extrusion for one step (the total extrusion
4154 # length will be NbOfSteps * ||StepVector||)
4155 # @param NbOfSteps the number of steps
4156 # @param ExtrFlags sets flags for extrusion
4157 # @param SewTolerance uses for comparing locations of nodes if flag
4158 # EXTRUSION_FLAG_SEW is set
4159 # @param MakeGroups forces the generation of new groups from existing ones
4160 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4161 # @ingroup l2_modif_extrurev
4162 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
4163 ExtrFlags, SewTolerance, MakeGroups=False):
4164 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
4165 StepVector = self.smeshpyD.GetDirStruct(StepVector)
4166 if isinstance( StepVector, list ):
4167 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
4168 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
4169 ExtrFlags, SewTolerance, MakeGroups)
4171 ## Generate new elements by extrusion of the given elements and nodes along the path.
4172 # The path of extrusion must be a meshed edge.
4173 # @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
4174 # @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
4175 # @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
4176 # @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4177 # @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
4178 # contains not only path segments, else it can be None
4179 # @param NodeStart the first or the last node on the path. Defines the direction of extrusion
4180 # @param HasAngles allows the shape to be rotated around the path
4181 # to get the resulting mesh in a helical fashion
4182 # @param Angles list of angles
4183 # @param LinearVariation forces the computation of rotation angles as linear
4184 # variation of the given Angles along path steps
4185 # @param HasRefPoint allows using the reference point
4186 # @param RefPoint the point around which the shape is rotated (the mass center of the
4187 # shape by default). The User can specify any point as the Reference Point.
4188 # @param MakeGroups forces the generation of new groups from existing ones
4189 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
4190 # @ingroup l2_modif_extrurev
4191 # @ref tui_extrusion_along_path example
4192 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
4193 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
4194 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
4195 unRegister = genObjUnRegister()
4196 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
4197 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
4198 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
4200 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
4201 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4202 if isinstance( RefPoint, list ):
4203 if not RefPoint: RefPoint = [0,0,0]
4204 RefPoint = SMESH.PointStruct( *RefPoint )
4205 if isinstance( PathMesh, Mesh ):
4206 PathMesh = PathMesh.GetMesh()
4207 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4208 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4209 self.mesh.SetParameters(Parameters)
4210 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
4211 PathMesh, PathShape, NodeStart,
4212 HasAngles, Angles, LinearVariation,
4213 HasRefPoint, RefPoint, MakeGroups)
4215 ## Generate new elements by extrusion of the given elements
4216 # The path of extrusion must be a meshed edge.
4217 # @param Base mesh or group, or sub-mesh, or list of ids of elements for extrusion
4218 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4219 # @param NodeStart the start node from Path. Defines the direction of extrusion
4220 # @param HasAngles allows the shape to be rotated around the path
4221 # to get the resulting mesh in a helical fashion
4222 # @param Angles list of angles in radians
4223 # @param LinearVariation forces the computation of rotation angles as linear
4224 # variation of the given Angles along path steps
4225 # @param HasRefPoint allows using the reference point
4226 # @param RefPoint the point around which the elements are rotated (the mass
4227 # center of the elements by default).
4228 # The User can specify any point as the Reference Point.
4229 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
4230 # @param MakeGroups forces the generation of new groups from existing ones
4231 # @param ElemType type of elements for extrusion (if param Base is a mesh)
4232 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4233 # only SMESH::Extrusion_Error otherwise
4234 # @ingroup l2_modif_extrurev
4235 # @ref tui_extrusion_along_path example
4236 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
4237 HasAngles=False, Angles=[], LinearVariation=False,
4238 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
4239 ElemType=SMESH.FACE):
4241 if ElemType == SMESH.NODE: n = Base
4242 if ElemType == SMESH.EDGE: e = Base
4243 if ElemType == SMESH.FACE: f = Base
4244 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
4245 HasAngles, Angles, LinearVariation,
4246 HasRefPoint, RefPoint, MakeGroups)
4247 if MakeGroups: return gr,er
4250 ## Generate new elements by extrusion of the given elements
4251 # The path of extrusion must be a meshed edge.
4252 # @param IDsOfElements ids of elements
4253 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
4254 # @param PathShape shape(edge) defines the sub-mesh for the path
4255 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4256 # @param HasAngles allows the shape to be rotated around the path
4257 # to get the resulting mesh in a helical fashion
4258 # @param Angles list of angles in radians
4259 # @param HasRefPoint allows using the reference point
4260 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4261 # The User can specify any point as the Reference Point.
4262 # @param MakeGroups forces the generation of new groups from existing ones
4263 # @param LinearVariation forces the computation of rotation angles as linear
4264 # variation of the given Angles along path steps
4265 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4266 # only SMESH::Extrusion_Error otherwise
4267 # @ingroup l2_modif_extrurev
4268 # @ref tui_extrusion_along_path example
4269 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
4270 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4271 MakeGroups=False, LinearVariation=False):
4272 n,e,f = [],IDsOfElements,IDsOfElements
4273 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
4274 NodeStart, HasAngles, Angles,
4276 HasRefPoint, RefPoint, MakeGroups)
4277 if MakeGroups: return gr,er
4280 ## Generate new elements by extrusion of the elements which belong to the object
4281 # The path of extrusion must be a meshed edge.
4282 # @param theObject the object whose elements should be processed.
4283 # It can be a mesh, a sub-mesh or a group.
4284 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4285 # @param PathShape shape(edge) defines the sub-mesh for the path
4286 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4287 # @param HasAngles allows the shape to be rotated around the path
4288 # to get the resulting mesh in a helical fashion
4289 # @param Angles list of angles
4290 # @param HasRefPoint allows using the reference point
4291 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4292 # The User can specify any point as the Reference Point.
4293 # @param MakeGroups forces the generation of new groups from existing ones
4294 # @param LinearVariation forces the computation of rotation angles as linear
4295 # variation of the given Angles along path steps
4296 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4297 # only SMESH::Extrusion_Error otherwise
4298 # @ingroup l2_modif_extrurev
4299 # @ref tui_extrusion_along_path example
4300 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4301 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4302 MakeGroups=False, LinearVariation=False):
4303 n,e,f = [],theObject,theObject
4304 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4305 HasAngles, Angles, LinearVariation,
4306 HasRefPoint, RefPoint, MakeGroups)
4307 if MakeGroups: return gr,er
4310 ## Generate new elements by extrusion of mesh segments which belong to the object
4311 # The path of extrusion must be a meshed edge.
4312 # @param theObject the object whose 1D elements should be processed.
4313 # It can be a mesh, a sub-mesh or a group.
4314 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4315 # @param PathShape shape(edge) defines the sub-mesh for the path
4316 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4317 # @param HasAngles allows the shape to be rotated around the path
4318 # to get the resulting mesh in a helical fashion
4319 # @param Angles list of angles
4320 # @param HasRefPoint allows using the reference point
4321 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4322 # The User can specify any point as the Reference Point.
4323 # @param MakeGroups forces the generation of new groups from existing ones
4324 # @param LinearVariation forces the computation of rotation angles as linear
4325 # variation of the given Angles along path steps
4326 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4327 # only SMESH::Extrusion_Error otherwise
4328 # @ingroup l2_modif_extrurev
4329 # @ref tui_extrusion_along_path example
4330 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4331 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4332 MakeGroups=False, LinearVariation=False):
4333 n,e,f = [],theObject,[]
4334 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4335 HasAngles, Angles, LinearVariation,
4336 HasRefPoint, RefPoint, MakeGroups)
4337 if MakeGroups: return gr,er
4340 ## Generate new elements by extrusion of faces which belong to the object
4341 # The path of extrusion must be a meshed edge.
4342 # @param theObject the object whose 2D elements should be processed.
4343 # It can be a mesh, a sub-mesh or a group.
4344 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4345 # @param PathShape shape(edge) defines the sub-mesh for the path
4346 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4347 # @param HasAngles allows the shape to be rotated around the path
4348 # to get the resulting mesh in a helical fashion
4349 # @param Angles list of angles
4350 # @param HasRefPoint allows using the reference point
4351 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4352 # The User can specify any point as the Reference Point.
4353 # @param MakeGroups forces the generation of new groups from existing ones
4354 # @param LinearVariation forces the computation of rotation angles as linear
4355 # variation of the given Angles along path steps
4356 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4357 # only SMESH::Extrusion_Error otherwise
4358 # @ingroup l2_modif_extrurev
4359 # @ref tui_extrusion_along_path example
4360 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4361 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4362 MakeGroups=False, LinearVariation=False):
4363 n,e,f = [],[],theObject
4364 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4365 HasAngles, Angles, LinearVariation,
4366 HasRefPoint, RefPoint, MakeGroups)
4367 if MakeGroups: return gr,er
4370 ## Create a symmetrical copy of mesh elements
4371 # @param IDsOfElements list of elements ids
4372 # @param Mirror is AxisStruct or geom object(point, line, plane)
4373 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4374 # If the Mirror is a geom object this parameter is unnecessary
4375 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4376 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4377 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4378 # @ingroup l2_modif_trsf
4379 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4380 if IDsOfElements == []:
4381 IDsOfElements = self.GetElementsId()
4382 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4383 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4384 theMirrorType = Mirror._mirrorType
4386 self.mesh.SetParameters(Mirror.parameters)
4387 if Copy and MakeGroups:
4388 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4389 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4392 ## Create a new mesh by a symmetrical copy of mesh elements
4393 # @param IDsOfElements the list of elements ids
4394 # @param Mirror is AxisStruct or geom object (point, line, plane)
4395 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4396 # If the Mirror is a geom object this parameter is unnecessary
4397 # @param MakeGroups to generate new groups from existing ones
4398 # @param NewMeshName a name of the new mesh to create
4399 # @return instance of Mesh class
4400 # @ingroup l2_modif_trsf
4401 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4402 if IDsOfElements == []:
4403 IDsOfElements = self.GetElementsId()
4404 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4405 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4406 theMirrorType = Mirror._mirrorType
4408 self.mesh.SetParameters(Mirror.parameters)
4409 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4410 MakeGroups, NewMeshName)
4411 return Mesh(self.smeshpyD,self.geompyD,mesh)
4413 ## Create a symmetrical copy of the object
4414 # @param theObject mesh, submesh or group
4415 # @param Mirror AxisStruct or geom object (point, line, plane)
4416 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4417 # If the Mirror is a geom object this parameter is unnecessary
4418 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4419 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4420 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4421 # @ingroup l2_modif_trsf
4422 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4423 if ( isinstance( theObject, Mesh )):
4424 theObject = theObject.GetMesh()
4425 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4426 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4427 theMirrorType = Mirror._mirrorType
4429 self.mesh.SetParameters(Mirror.parameters)
4430 if Copy and MakeGroups:
4431 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4432 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4435 ## Create a new mesh by a symmetrical copy of the object
4436 # @param theObject mesh, submesh or group
4437 # @param Mirror AxisStruct or geom object (point, line, plane)
4438 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4439 # If the Mirror is a geom object this parameter is unnecessary
4440 # @param MakeGroups forces the generation of new groups from existing ones
4441 # @param NewMeshName the name of the new mesh to create
4442 # @return instance of Mesh class
4443 # @ingroup l2_modif_trsf
4444 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4445 if ( isinstance( theObject, Mesh )):
4446 theObject = theObject.GetMesh()
4447 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4448 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4449 theMirrorType = Mirror._mirrorType
4451 self.mesh.SetParameters(Mirror.parameters)
4452 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4453 MakeGroups, NewMeshName)
4454 return Mesh( self.smeshpyD,self.geompyD,mesh )
4456 ## Translate the elements
4457 # @param IDsOfElements list of elements ids
4458 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4459 # @param Copy allows copying the translated elements
4460 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4461 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4462 # @ingroup l2_modif_trsf
4463 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4464 if IDsOfElements == []:
4465 IDsOfElements = self.GetElementsId()
4466 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4467 Vector = self.smeshpyD.GetDirStruct(Vector)
4468 if isinstance( Vector, list ):
4469 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4470 self.mesh.SetParameters(Vector.PS.parameters)
4471 if Copy and MakeGroups:
4472 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4473 self.editor.Translate(IDsOfElements, Vector, Copy)
4476 ## Create a new mesh of translated elements
4477 # @param IDsOfElements list of elements ids
4478 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4479 # @param MakeGroups forces the generation of new groups from existing ones
4480 # @param NewMeshName the name of the newly created mesh
4481 # @return instance of Mesh class
4482 # @ingroup l2_modif_trsf
4483 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4484 if IDsOfElements == []:
4485 IDsOfElements = self.GetElementsId()
4486 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4487 Vector = self.smeshpyD.GetDirStruct(Vector)
4488 if isinstance( Vector, list ):
4489 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4490 self.mesh.SetParameters(Vector.PS.parameters)
4491 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4492 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4494 ## Translate the object
4495 # @param theObject the object to translate (mesh, submesh, or group)
4496 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4497 # @param Copy allows copying the translated elements
4498 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4499 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4500 # @ingroup l2_modif_trsf
4501 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4502 if ( isinstance( theObject, Mesh )):
4503 theObject = theObject.GetMesh()
4504 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4505 Vector = self.smeshpyD.GetDirStruct(Vector)
4506 if isinstance( Vector, list ):
4507 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4508 self.mesh.SetParameters(Vector.PS.parameters)
4509 if Copy and MakeGroups:
4510 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4511 self.editor.TranslateObject(theObject, Vector, Copy)
4514 ## Create a new mesh from the translated object
4515 # @param theObject the object to translate (mesh, submesh, or group)
4516 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4517 # @param MakeGroups forces the generation of new groups from existing ones
4518 # @param NewMeshName the name of the newly created mesh
4519 # @return instance of Mesh class
4520 # @ingroup l2_modif_trsf
4521 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4522 if isinstance( theObject, Mesh ):
4523 theObject = theObject.GetMesh()
4524 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4525 Vector = self.smeshpyD.GetDirStruct(Vector)
4526 if isinstance( Vector, list ):
4527 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4528 self.mesh.SetParameters(Vector.PS.parameters)
4529 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4530 return Mesh( self.smeshpyD, self.geompyD, mesh )
4535 # @param theObject - the object to translate (mesh, submesh, or group)
4536 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4537 # @param theScaleFact - list of 1-3 scale factors for axises
4538 # @param Copy - allows copying the translated elements
4539 # @param MakeGroups - forces the generation of new groups from existing
4541 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4542 # empty list otherwise
4543 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4544 unRegister = genObjUnRegister()
4545 if ( isinstance( theObject, Mesh )):
4546 theObject = theObject.GetMesh()
4547 if ( isinstance( theObject, list )):
4548 theObject = self.GetIDSource(theObject, SMESH.ALL)
4549 unRegister.set( theObject )
4550 if ( isinstance( thePoint, list )):
4551 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4552 if ( isinstance( theScaleFact, float )):
4553 theScaleFact = [theScaleFact]
4554 if ( isinstance( theScaleFact, int )):
4555 theScaleFact = [ float(theScaleFact)]
4557 self.mesh.SetParameters(thePoint.parameters)
4559 if Copy and MakeGroups:
4560 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4561 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4564 ## Create a new mesh from the translated object
4565 # @param theObject - the object to translate (mesh, submesh, or group)
4566 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4567 # @param theScaleFact - list of 1-3 scale factors for axises
4568 # @param MakeGroups - forces the generation of new groups from existing ones
4569 # @param NewMeshName - the name of the newly created mesh
4570 # @return instance of Mesh class
4571 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4572 unRegister = genObjUnRegister()
4573 if (isinstance(theObject, Mesh)):
4574 theObject = theObject.GetMesh()
4575 if ( isinstance( theObject, list )):
4576 theObject = self.GetIDSource(theObject,SMESH.ALL)
4577 unRegister.set( theObject )
4578 if ( isinstance( thePoint, list )):
4579 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4580 if ( isinstance( theScaleFact, float )):
4581 theScaleFact = [theScaleFact]
4582 if ( isinstance( theScaleFact, int )):
4583 theScaleFact = [ float(theScaleFact)]
4585 self.mesh.SetParameters(thePoint.parameters)
4586 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4587 MakeGroups, NewMeshName)
4588 return Mesh( self.smeshpyD, self.geompyD, mesh )
4592 ## Rotate the elements
4593 # @param IDsOfElements list of elements ids
4594 # @param Axis the axis of rotation (AxisStruct or geom line)
4595 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4596 # @param Copy allows copying the rotated elements
4597 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4598 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4599 # @ingroup l2_modif_trsf
4600 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4601 if IDsOfElements == []:
4602 IDsOfElements = self.GetElementsId()
4603 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4604 Axis = self.smeshpyD.GetAxisStruct(Axis)
4605 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4606 Parameters = Axis.parameters + var_separator + Parameters
4607 self.mesh.SetParameters(Parameters)
4608 if Copy and MakeGroups:
4609 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4610 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4613 ## Create a new mesh of rotated elements
4614 # @param IDsOfElements list of element ids
4615 # @param Axis the axis of rotation (AxisStruct or geom line)
4616 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4617 # @param MakeGroups forces the generation of new groups from existing ones
4618 # @param NewMeshName the name of the newly created mesh
4619 # @return instance of Mesh class
4620 # @ingroup l2_modif_trsf
4621 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4622 if IDsOfElements == []:
4623 IDsOfElements = self.GetElementsId()
4624 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4625 Axis = self.smeshpyD.GetAxisStruct(Axis)
4626 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4627 Parameters = Axis.parameters + var_separator + Parameters
4628 self.mesh.SetParameters(Parameters)
4629 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4630 MakeGroups, NewMeshName)
4631 return Mesh( self.smeshpyD, self.geompyD, mesh )
4633 ## Rotate the object
4634 # @param theObject the object to rotate( mesh, submesh, or group)
4635 # @param Axis the axis of rotation (AxisStruct or geom line)
4636 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4637 # @param Copy allows copying the rotated elements
4638 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4639 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4640 # @ingroup l2_modif_trsf
4641 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4642 if (isinstance(theObject, Mesh)):
4643 theObject = theObject.GetMesh()
4644 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4645 Axis = self.smeshpyD.GetAxisStruct(Axis)
4646 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4647 Parameters = Axis.parameters + ":" + Parameters
4648 self.mesh.SetParameters(Parameters)
4649 if Copy and MakeGroups:
4650 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4651 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4654 ## Create a new mesh from the rotated object
4655 # @param theObject the object to rotate (mesh, submesh, or group)
4656 # @param Axis the axis of rotation (AxisStruct or geom line)
4657 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4658 # @param MakeGroups forces the generation of new groups from existing ones
4659 # @param NewMeshName the name of the newly created mesh
4660 # @return instance of Mesh class
4661 # @ingroup l2_modif_trsf
4662 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4663 if (isinstance( theObject, Mesh )):
4664 theObject = theObject.GetMesh()
4665 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4666 Axis = self.smeshpyD.GetAxisStruct(Axis)
4667 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4668 Parameters = Axis.parameters + ":" + Parameters
4669 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4670 MakeGroups, NewMeshName)
4671 self.mesh.SetParameters(Parameters)
4672 return Mesh( self.smeshpyD, self.geompyD, mesh )
4674 ## Find groups of adjacent nodes within Tolerance.
4675 # @param Tolerance the value of tolerance
4676 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4677 # corner and medium nodes in separate groups thus preventing
4678 # their further merge.
4679 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4680 # @ingroup l2_modif_trsf
4681 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
4682 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
4684 ## Find groups of ajacent nodes within Tolerance.
4685 # @param Tolerance the value of tolerance
4686 # @param SubMeshOrGroup SubMesh, Group or Filter
4687 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4688 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4689 # corner and medium nodes in separate groups thus preventing
4690 # their further merge.
4691 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4692 # @ingroup l2_modif_trsf
4693 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
4694 exceptNodes=[], SeparateCornerAndMediumNodes=False):
4695 unRegister = genObjUnRegister()
4696 if (isinstance( SubMeshOrGroup, Mesh )):
4697 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4698 if not isinstance( exceptNodes, list ):
4699 exceptNodes = [ exceptNodes ]
4700 if exceptNodes and isinstance( exceptNodes[0], int ):
4701 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
4702 unRegister.set( exceptNodes )
4703 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
4704 exceptNodes, SeparateCornerAndMediumNodes)
4707 # @param GroupsOfNodes a list of groups of nodes IDs for merging
4708 # (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
4709 # by nodes 1 and 25 correspondingly in all elements and groups
4710 # @param NodesToKeep nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
4711 # If @a NodesToKeep does not include a node to keep for some group to merge,
4712 # then the first node in the group is kept.
4713 # @param AvoidMakingHoles prevent merging nodes which cause removal of elements becoming
4715 # @ingroup l2_modif_trsf
4716 def MergeNodes (self, GroupsOfNodes, NodesToKeep=[], AvoidMakingHoles=False):
4717 # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
4718 self.editor.MergeNodes( GroupsOfNodes, NodesToKeep, AvoidMakingHoles )
4720 ## Find the elements built on the same nodes.
4721 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4722 # @return the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
4723 # @ingroup l2_modif_trsf
4724 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4725 if not MeshOrSubMeshOrGroup:
4726 MeshOrSubMeshOrGroup=self.mesh
4727 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4728 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4729 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4731 ## Merge elements in each given group.
4732 # @param GroupsOfElementsID a list of groups of elements IDs for merging
4733 # (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
4734 # replaced by elements 1 and 25 in all groups)
4735 # @ingroup l2_modif_trsf
4736 def MergeElements(self, GroupsOfElementsID):
4737 self.editor.MergeElements(GroupsOfElementsID)
4739 ## Leave one element and remove all other elements built on the same nodes.
4740 # @ingroup l2_modif_trsf
4741 def MergeEqualElements(self):
4742 self.editor.MergeEqualElements()
4744 ## Returns all or only closed free borders
4745 # @return list of SMESH.FreeBorder's
4746 # @ingroup l2_modif_trsf
4747 def FindFreeBorders(self, ClosedOnly=True):
4748 return self.editor.FindFreeBorders( ClosedOnly )
4750 ## Fill with 2D elements a hole defined by a SMESH.FreeBorder.
4751 # @param FreeBorder either a SMESH.FreeBorder or a list on node IDs. These nodes
4752 # must describe all sequential nodes of the hole border. The first and the last
4753 # nodes must be the same. Use FindFreeBorders() to get nodes of holes.
4754 # @ingroup l2_modif_trsf
4755 def FillHole(self, holeNodes):
4756 if holeNodes and isinstance( holeNodes, list ) and isinstance( holeNodes[0], int ):
4757 holeNodes = SMESH.FreeBorder(nodeIDs=holeNodes)
4758 if not isinstance( holeNodes, SMESH.FreeBorder ):
4759 raise TypeError("holeNodes must be either SMESH.FreeBorder or list of integer and not %s" % holeNodes)
4760 self.editor.FillHole( holeNodes )
4762 ## Return groups of FreeBorder's coincident within the given tolerance.
4763 # @param tolerance the tolerance. If the tolerance <= 0.0 then one tenth of an average
4764 # size of elements adjacent to free borders being compared is used.
4765 # @return SMESH.CoincidentFreeBorders structure
4766 # @ingroup l2_modif_trsf
4767 def FindCoincidentFreeBorders (self, tolerance=0.):
4768 return self.editor.FindCoincidentFreeBorders( tolerance )
4770 ## Sew FreeBorder's of each group
4771 # @param freeBorders either a SMESH.CoincidentFreeBorders structure or a list of lists
4772 # where each enclosed list contains node IDs of a group of coincident free
4773 # borders such that each consequent triple of IDs within a group describes
4774 # a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
4775 # last node of a border.
4776 # For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
4777 # groups of coincident free borders, each group including two borders.
4778 # @param createPolygons if @c True faces adjacent to free borders are converted to
4779 # polygons if a node of opposite border falls on a face edge, else such
4780 # faces are split into several ones.
4781 # @param createPolyhedra if @c True volumes adjacent to free borders are converted to
4782 # polyhedra if a node of opposite border falls on a volume edge, else such
4783 # volumes, if any, remain intact and the mesh becomes non-conformal.
4784 # @return a number of successfully sewed groups
4785 # @ingroup l2_modif_trsf
4786 def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
4787 if freeBorders and isinstance( freeBorders, list ):
4788 # construct SMESH.CoincidentFreeBorders
4789 if isinstance( freeBorders[0], int ):
4790 freeBorders = [freeBorders]
4792 coincidentGroups = []
4793 for nodeList in freeBorders:
4794 if not nodeList or len( nodeList ) % 3:
4795 raise ValueError("Wrong number of nodes in this group: %s" % nodeList)
4798 group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
4799 borders.append( SMESH.FreeBorder( nodeList[:3] ))
4800 nodeList = nodeList[3:]
4802 coincidentGroups.append( group )
4804 freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
4806 return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
4809 # @return SMESH::Sew_Error
4810 # @ingroup l2_modif_trsf
4811 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4812 FirstNodeID2, SecondNodeID2, LastNodeID2,
4813 CreatePolygons, CreatePolyedrs):
4814 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4815 FirstNodeID2, SecondNodeID2, LastNodeID2,
4816 CreatePolygons, CreatePolyedrs)
4818 ## Sew conform free borders
4819 # @return SMESH::Sew_Error
4820 # @ingroup l2_modif_trsf
4821 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4822 FirstNodeID2, SecondNodeID2):
4823 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4824 FirstNodeID2, SecondNodeID2)
4826 ## Sew border to side
4827 # @return SMESH::Sew_Error
4828 # @ingroup l2_modif_trsf
4829 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4830 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4831 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4832 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4834 ## Sew two sides of a mesh. The nodes belonging to Side1 are
4835 # merged with the nodes of elements of Side2.
4836 # The number of elements in theSide1 and in theSide2 must be
4837 # equal and they should have similar nodal connectivity.
4838 # The nodes to merge should belong to side borders and
4839 # the first node should be linked to the second.
4840 # @return SMESH::Sew_Error
4841 # @ingroup l2_modif_trsf
4842 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4843 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4844 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4845 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4846 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4847 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4849 ## Set new nodes for the given element.
4850 # @param ide the element id
4851 # @param newIDs nodes ids
4852 # @return If the number of nodes does not correspond to the type of element - return false
4853 # @ingroup l2_modif_edit
4854 def ChangeElemNodes(self, ide, newIDs):
4855 return self.editor.ChangeElemNodes(ide, newIDs)
4857 ## If during the last operation of MeshEditor some nodes were
4858 # created, this method return the list of their IDs, \n
4859 # if new nodes were not created - return empty list
4860 # @return the list of integer values (can be empty)
4861 # @ingroup l2_modif_add
4862 def GetLastCreatedNodes(self):
4863 return self.editor.GetLastCreatedNodes()
4865 ## If during the last operation of MeshEditor some elements were
4866 # created this method return the list of their IDs, \n
4867 # if new elements were not created - return empty list
4868 # @return the list of integer values (can be empty)
4869 # @ingroup l2_modif_add
4870 def GetLastCreatedElems(self):
4871 return self.editor.GetLastCreatedElems()
4873 ## Forget what nodes and elements were created by the last mesh edition operation
4874 # @ingroup l2_modif_add
4875 def ClearLastCreated(self):
4876 self.editor.ClearLastCreated()
4878 ## Create duplicates of given elements, i.e. create new elements based on the
4879 # same nodes as the given ones.
4880 # @param theElements - container of elements to duplicate. It can be a Mesh,
4881 # sub-mesh, group, filter or a list of element IDs. If \a theElements is
4882 # a Mesh, elements of highest dimension are duplicated
4883 # @param theGroupName - a name of group to contain the generated elements.
4884 # If a group with such a name already exists, the new elements
4885 # are added to the existng group, else a new group is created.
4886 # If \a theGroupName is empty, new elements are not added
4888 # @return a group where the new elements are added. None if theGroupName == "".
4889 # @ingroup l2_modif_duplicat
4890 def DoubleElements(self, theElements, theGroupName=""):
4891 unRegister = genObjUnRegister()
4892 if isinstance( theElements, Mesh ):
4893 theElements = theElements.mesh
4894 elif isinstance( theElements, list ):
4895 theElements = self.GetIDSource( theElements, SMESH.ALL )
4896 unRegister.set( theElements )
4897 return self.editor.DoubleElements(theElements, theGroupName)
4899 ## Create a hole in a mesh by doubling the nodes of some particular elements
4900 # @param theNodes identifiers of nodes to be doubled
4901 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4902 # nodes. If list of element identifiers is empty then nodes are doubled but
4903 # they not assigned to elements
4904 # @return TRUE if operation has been completed successfully, FALSE otherwise
4905 # @ingroup l2_modif_duplicat
4906 def DoubleNodes(self, theNodes, theModifiedElems):
4907 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4909 ## Create a hole in a mesh by doubling the nodes of some particular elements
4910 # This method provided for convenience works as DoubleNodes() described above.
4911 # @param theNodeId identifiers of node to be doubled
4912 # @param theModifiedElems identifiers of elements to be updated
4913 # @return TRUE if operation has been completed successfully, FALSE otherwise
4914 # @ingroup l2_modif_duplicat
4915 def DoubleNode(self, theNodeId, theModifiedElems):
4916 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4918 ## Create a hole in a mesh by doubling the nodes of some particular elements
4919 # This method provided for convenience works as DoubleNodes() described above.
4920 # @param theNodes group of nodes to be doubled
4921 # @param theModifiedElems group of elements to be updated.
4922 # @param theMakeGroup forces the generation of a group containing new nodes.
4923 # @return TRUE or a created group if operation has been completed successfully,
4924 # FALSE or None otherwise
4925 # @ingroup l2_modif_duplicat
4926 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4928 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4929 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4931 ## Create a hole in a mesh by doubling the nodes of some particular elements
4932 # This method provided for convenience works as DoubleNodes() described above.
4933 # @param theNodes list of groups of nodes to be doubled
4934 # @param theModifiedElems list of groups of elements to be updated.
4935 # @param theMakeGroup forces the generation of a group containing new nodes.
4936 # @return TRUE if operation has been completed successfully, FALSE otherwise
4937 # @ingroup l2_modif_duplicat
4938 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4940 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4941 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4943 ## Create a hole in a mesh by doubling the nodes of some particular elements
4944 # @param theElems - the list of elements (edges or faces) to be replicated
4945 # The nodes for duplication could be found from these elements
4946 # @param theNodesNot - list of nodes to NOT replicate
4947 # @param theAffectedElems - the list of elements (cells and edges) to which the
4948 # replicated nodes should be associated to.
4949 # @return TRUE if operation has been completed successfully, FALSE otherwise
4950 # @ingroup l2_modif_duplicat
4951 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4952 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4954 ## Create a hole in a mesh by doubling the nodes of some particular elements
4955 # @param theElems - the list of elements (edges or faces) to be replicated
4956 # The nodes for duplication could be found from these elements
4957 # @param theNodesNot - list of nodes to NOT replicate
4958 # @param theShape - shape to detect affected elements (element which geometric center
4959 # located on or inside shape).
4960 # The replicated nodes should be associated to affected elements.
4961 # @return TRUE if operation has been completed successfully, FALSE otherwise
4962 # @ingroup l2_modif_duplicat
4963 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4964 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4966 ## Create a hole in a mesh by doubling the nodes of some particular elements
4967 # This method provided for convenience works as DoubleNodes() described above.
4968 # @param theElems - group of of elements (edges or faces) to be replicated
4969 # @param theNodesNot - group of nodes not to replicated
4970 # @param theAffectedElems - group of elements to which the replicated nodes
4971 # should be associated to.
4972 # @param theMakeGroup forces the generation of a group containing new elements.
4973 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4974 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4975 # FALSE or None otherwise
4976 # @ingroup l2_modif_duplicat
4977 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4978 theMakeGroup=False, theMakeNodeGroup=False):
4979 if theMakeGroup or theMakeNodeGroup:
4980 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4982 theMakeGroup, theMakeNodeGroup)
4983 if theMakeGroup and theMakeNodeGroup:
4986 return twoGroups[ int(theMakeNodeGroup) ]
4987 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4989 ## Create a hole in a mesh by doubling the nodes of some particular elements
4990 # This method provided for convenience works as DoubleNodes() described above.
4991 # @param theElems - group of of elements (edges or faces) to be replicated
4992 # @param theNodesNot - group of nodes not to replicated
4993 # @param theShape - shape to detect affected elements (element which geometric center
4994 # located on or inside shape).
4995 # The replicated nodes should be associated to affected elements.
4996 # @ingroup l2_modif_duplicat
4997 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4998 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
5000 ## Create a hole in a mesh by doubling the nodes of some particular elements
5001 # This method provided for convenience works as DoubleNodes() described above.
5002 # @param theElems - list of groups of elements (edges or faces) to be replicated
5003 # @param theNodesNot - list of groups of nodes not to replicated
5004 # @param theAffectedElems - group of elements to which the replicated nodes
5005 # should be associated to.
5006 # @param theMakeGroup forces the generation of a group containing new elements.
5007 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
5008 # @return TRUE or created groups (one or two) if operation has been completed successfully,
5009 # FALSE or None otherwise
5010 # @ingroup l2_modif_duplicat
5011 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
5012 theMakeGroup=False, theMakeNodeGroup=False):
5013 if theMakeGroup or theMakeNodeGroup:
5014 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
5016 theMakeGroup, theMakeNodeGroup)
5017 if theMakeGroup and theMakeNodeGroup:
5020 return twoGroups[ int(theMakeNodeGroup) ]
5021 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
5023 ## Create a hole in a mesh by doubling the nodes of some particular elements
5024 # This method provided for convenience works as DoubleNodes() described above.
5025 # @param theElems - list of groups of elements (edges or faces) to be replicated
5026 # @param theNodesNot - list of groups of nodes not to replicated
5027 # @param theShape - shape to detect affected elements (element which geometric center
5028 # located on or inside shape).
5029 # The replicated nodes should be associated to affected elements.
5030 # @return TRUE if operation has been completed successfully, FALSE otherwise
5031 # @ingroup l2_modif_duplicat
5032 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
5033 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
5035 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
5036 # This method is the first step of DoubleNodeElemGroupsInRegion.
5037 # @param theElems - list of groups of nodes or elements (edges or faces) to be replicated
5038 # @param theNodesNot - list of groups of nodes not to replicated
5039 # @param theShape - shape to detect affected elements (element which geometric center
5040 # located on or inside shape).
5041 # The replicated nodes should be associated to affected elements.
5042 # @return groups of affected elements in order: volumes, faces, edges
5043 # @ingroup l2_modif_duplicat
5044 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
5045 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
5047 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
5048 # The list of groups must describe a partition of the mesh volumes.
5049 # The nodes of the internal faces at the boundaries of the groups are doubled.
5050 # In option, the internal faces are replaced by flat elements.
5051 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
5052 # @param theDomains - list of groups of volumes
5053 # @param createJointElems - if TRUE, create the elements
5054 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
5055 # the boundary between \a theDomains and the rest mesh
5056 # @return TRUE if operation has been completed successfully, FALSE otherwise
5057 # @ingroup l2_modif_duplicat
5058 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
5059 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
5061 ## Double nodes on some external faces and create flat elements.
5062 # Flat elements are mainly used by some types of mechanic calculations.
5064 # Each group of the list must be constituted of faces.
5065 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
5066 # @param theGroupsOfFaces - list of groups of faces
5067 # @return TRUE if operation has been completed successfully, FALSE otherwise
5068 # @ingroup l2_modif_duplicat
5069 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
5070 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
5072 ## identify all the elements around a geom shape, get the faces delimiting the hole
5074 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
5075 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
5077 ## Create a polyline consisting of 1D mesh elements each lying on a 2D element of
5078 # the initial mesh. Positions of new nodes are found by cutting the mesh by the
5079 # plane passing through pairs of points specified by each PolySegment structure.
5080 # If there are several paths connecting a pair of points, the shortest path is
5081 # selected by the module. Position of the cutting plane is defined by the two
5082 # points and an optional vector lying on the plane specified by a PolySegment.
5083 # By default the vector is defined by Mesh module as following. A middle point
5084 # of the two given points is computed. The middle point is projected to the mesh.
5085 # The vector goes from the middle point to the projection point. In case of planar
5086 # mesh, the vector is normal to the mesh.
5087 # @param segments - PolySegment's defining positions of cutting planes.
5088 # Return the used vector which goes from the middle point to its projection.
5089 # @param groupName - optional name of a group where created mesh segments will
5091 # @ingroup l2_modif_duplicat
5092 def MakePolyLine(self, segments, groupName='', isPreview=False ):
5093 editor = self.editor
5095 editor = self.mesh.GetMeshEditPreviewer()
5096 segmentsRes = editor.MakePolyLine( segments, groupName )
5097 for i, seg in enumerate( segmentsRes ):
5098 segments[i].vector = seg.vector
5100 return editor.GetPreviewData()
5103 ## Return a cached numerical functor by its type.
5104 # @param theCriterion functor type - an item of SMESH.FunctorType enumeration.
5105 # Type SMESH.FunctorType._items in the Python Console to see all items.
5106 # Note that not all items correspond to numerical functors.
5107 # @return SMESH_NumericalFunctor. The functor is already initialized
5109 # @ingroup l1_measurements
5110 def GetFunctor(self, funcType ):
5111 fn = self.functors[ funcType._v ]
5113 fn = self.smeshpyD.GetFunctor(funcType)
5114 fn.SetMesh(self.mesh)
5115 self.functors[ EnumToLong(funcType) ] = fn
5118 ## Return value of a functor for a given element
5119 # @param funcType an item of SMESH.FunctorType enum
5120 # Type "SMESH.FunctorType._items" in the Python Console to see all items.
5121 # @param elemId element or node ID
5122 # @param isElem @a elemId is ID of element or node
5123 # @return the functor value or zero in case of invalid arguments
5124 # @ingroup l1_measurements
5125 def FunctorValue(self, funcType, elemId, isElem=True):
5126 fn = self.GetFunctor( funcType )
5127 if fn.GetElementType() == self.GetElementType(elemId, isElem):
5128 val = fn.GetValue(elemId)
5133 ## Get length of 1D element or sum of lengths of all 1D mesh elements
5134 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
5135 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
5136 # @ingroup l1_measurements
5137 def GetLength(self, elemId=None):
5140 length = self.smeshpyD.GetLength(self)
5142 length = self.FunctorValue(SMESH.FT_Length, elemId)
5145 ## Get area of 2D element or sum of areas of all 2D mesh elements
5146 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
5147 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
5148 # @ingroup l1_measurements
5149 def GetArea(self, elemId=None):
5152 area = self.smeshpyD.GetArea(self)
5154 area = self.FunctorValue(SMESH.FT_Area, elemId)
5157 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
5158 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
5159 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
5160 # @ingroup l1_measurements
5161 def GetVolume(self, elemId=None):
5164 volume = self.smeshpyD.GetVolume(self)
5166 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
5169 ## Get maximum element length.
5170 # @param elemId mesh element ID
5171 # @return element's maximum length value
5172 # @ingroup l1_measurements
5173 def GetMaxElementLength(self, elemId):
5174 if self.GetElementType(elemId, True) == SMESH.VOLUME:
5175 ftype = SMESH.FT_MaxElementLength3D
5177 ftype = SMESH.FT_MaxElementLength2D
5178 return self.FunctorValue(ftype, elemId)
5180 ## Get aspect ratio of 2D or 3D element.
5181 # @param elemId mesh element ID
5182 # @return element's aspect ratio value
5183 # @ingroup l1_measurements
5184 def GetAspectRatio(self, elemId):
5185 if self.GetElementType(elemId, True) == SMESH.VOLUME:
5186 ftype = SMESH.FT_AspectRatio3D
5188 ftype = SMESH.FT_AspectRatio
5189 return self.FunctorValue(ftype, elemId)
5191 ## Get warping angle of 2D element.
5192 # @param elemId mesh element ID
5193 # @return element's warping angle value
5194 # @ingroup l1_measurements
5195 def GetWarping(self, elemId):
5196 return self.FunctorValue(SMESH.FT_Warping, elemId)
5198 ## Get minimum angle of 2D element.
5199 # @param elemId mesh element ID
5200 # @return element's minimum angle value
5201 # @ingroup l1_measurements
5202 def GetMinimumAngle(self, elemId):
5203 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
5205 ## Get taper of 2D element.
5206 # @param elemId mesh element ID
5207 # @return element's taper value
5208 # @ingroup l1_measurements
5209 def GetTaper(self, elemId):
5210 return self.FunctorValue(SMESH.FT_Taper, elemId)
5212 ## Get skew of 2D element.
5213 # @param elemId mesh element ID
5214 # @return element's skew value
5215 # @ingroup l1_measurements
5216 def GetSkew(self, elemId):
5217 return self.FunctorValue(SMESH.FT_Skew, elemId)
5219 ## Return minimal and maximal value of a given functor.
5220 # @param funType a functor type, an item of SMESH.FunctorType enum
5221 # (one of SMESH.FunctorType._items)
5222 # @param meshPart a part of mesh (group, sub-mesh) to treat
5223 # @return tuple (min,max)
5224 # @ingroup l1_measurements
5225 def GetMinMax(self, funType, meshPart=None):
5226 unRegister = genObjUnRegister()
5227 if isinstance( meshPart, list ):
5228 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
5229 unRegister.set( meshPart )
5230 if isinstance( meshPart, Mesh ):
5231 meshPart = meshPart.mesh
5232 fun = self.GetFunctor( funType )
5235 if hasattr( meshPart, "SetMesh" ):
5236 meshPart.SetMesh( self.mesh ) # set mesh to filter
5237 hist = fun.GetLocalHistogram( 1, False, meshPart )
5239 hist = fun.GetHistogram( 1, False )
5241 return hist[0].min, hist[0].max
5244 pass # end of Mesh class
5247 ## Private class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
5248 # with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
5250 class meshProxy(SMESH._objref_SMESH_Mesh):
5251 def __init__(self, *args):
5252 SMESH._objref_SMESH_Mesh.__init__(self, *args)
5253 def __deepcopy__(self, memo=None):
5254 new = self.__class__(self)
5256 def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
5257 if len( args ) == 3:
5258 args += SMESH.ALL_NODES, True
5259 return SMESH._objref_SMESH_Mesh.CreateDimGroup(self, *args)
5260 def ExportToMEDX(self, *args): # function removed
5261 print("WARNING: ExportToMEDX() is deprecated, use ExportMED() instead")
5262 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5263 SMESH._objref_SMESH_Mesh.ExportMED(self, *args)
5264 def ExportToMED(self, *args): # function removed
5265 print("WARNING: ExportToMED() is deprecated, use ExportMED() instead")
5266 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5267 while len(args) < 4: # !!!! nb of parameters for ExportToMED IDL's method
5269 SMESH._objref_SMESH_Mesh.ExportMED(self, *args)
5270 def ExportPartToMED(self, *args): # 'version' parameter removed
5271 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5272 SMESH._objref_SMESH_Mesh.ExportPartToMED(self, *args)
5273 def ExportMED(self, *args): # signature of method changed
5274 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5275 while len(args) < 4: # !!!! nb of parameters for ExportToMED IDL's method
5277 SMESH._objref_SMESH_Mesh.ExportMED(self, *args)
5279 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
5282 ## Private class wrapping SMESH.SMESH_SubMesh in order to add Compute()
5284 class submeshProxy(SMESH._objref_SMESH_subMesh):
5285 def __init__(self, *args):
5286 SMESH._objref_SMESH_subMesh.__init__(self, *args)
5288 def __deepcopy__(self, memo=None):
5289 new = self.__class__(self)
5292 ## Compute the sub-mesh and return the status of the computation
5293 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
5294 # @return True or False
5296 # This is a method of SMESH.SMESH_submesh that can be obtained via Mesh.GetSubMesh() or
5297 # @ref smesh_algorithm.Mesh_Algorithm.GetSubMesh() "Mesh_Algorithm.GetSubMesh()".
5298 # @ingroup l2_submeshes
5299 def Compute(self,refresh=False):
5301 self.mesh = Mesh( smeshBuilder(), None, self.GetMesh())
5303 ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
5305 if salome.sg.hasDesktop():
5306 smeshgui = salome.ImportComponentGUI("SMESH")
5308 smeshgui.SetMeshIcon( salome.ObjectToID( self ), ok, (self.GetNumberOfElements()==0) )
5309 if refresh: salome.sg.updateObjBrowser()
5314 omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy)
5317 ## Private class used to compensate change of CORBA API of SMESH_MeshEditor for backward
5318 # compatibility with old dump scripts which call SMESH_MeshEditor directly and not via
5321 class meshEditor(SMESH._objref_SMESH_MeshEditor):
5322 def __init__(self, *args):
5323 SMESH._objref_SMESH_MeshEditor.__init__(self, *args)
5325 def __getattr__(self, name ): # method called if an attribute not found
5326 if not self.mesh: # look for name() method in Mesh class
5327 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
5328 if hasattr( self.mesh, name ):
5329 return getattr( self.mesh, name )
5330 if name == "ExtrusionAlongPathObjX":
5331 return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
5332 print("meshEditor: attribute '%s' NOT FOUND" % name)
5334 def __deepcopy__(self, memo=None):
5335 new = self.__class__(self)
5337 def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
5338 if len( args ) == 1: args += False,
5339 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
5340 def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
5341 if len( args ) == 2: args += False,
5342 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
5343 def MergeNodes(self,*args): # 2 args added (NodesToKeep,AvoidMakingHoles)
5344 if len( args ) == 1:
5345 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [], False )
5346 NodesToKeep = args[1]
5347 AvoidMakingHoles = args[2] if len( args ) == 3 else False
5348 unRegister = genObjUnRegister()
5350 if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
5351 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
5352 if not isinstance( NodesToKeep, list ):
5353 NodesToKeep = [ NodesToKeep ]
5354 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep, AvoidMakingHoles )
5356 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
5358 ## Private class wrapping SMESH.SMESH_Pattern CORBA class in order to treat Notebook
5359 # variables in some methods
5361 class Pattern(SMESH._objref_SMESH_Pattern):
5363 def LoadFromFile(self, patternTextOrFile ):
5364 text = patternTextOrFile
5365 if os.path.exists( text ):
5366 text = open( patternTextOrFile ).read()
5368 return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
5370 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
5371 decrFun = lambda i: i-1
5372 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
5373 theMesh.SetParameters(Parameters)
5374 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
5376 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
5377 decrFun = lambda i: i-1
5378 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
5379 theMesh.SetParameters(Parameters)
5380 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
5382 def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
5383 if isinstance( mesh, Mesh ):
5384 mesh = mesh.GetMesh()
5385 return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
5387 # Registering the new proxy for Pattern
5388 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
5390 ## Private class used to bind methods creating algorithms to the class Mesh
5393 def __init__(self, method):
5395 self.defaultAlgoType = ""
5396 self.algoTypeToClass = {}
5397 self.method = method
5399 # Store a python class of algorithm
5400 def add(self, algoClass):
5401 if inspect.isclass(algoClass) and \
5402 hasattr(algoClass, "algoType"):
5403 self.algoTypeToClass[ algoClass.algoType ] = algoClass
5404 if not self.defaultAlgoType and \
5405 hasattr( algoClass, "isDefault") and algoClass.isDefault:
5406 self.defaultAlgoType = algoClass.algoType
5407 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
5409 # Create a copy of self and assign mesh to the copy
5410 def copy(self, mesh):
5411 other = algoCreator( self.method )
5412 other.defaultAlgoType = self.defaultAlgoType
5413 other.algoTypeToClass = self.algoTypeToClass
5417 # Create an instance of algorithm
5418 def __call__(self,algo="",geom=0,*args):
5421 if isinstance( algo, str ):
5423 elif ( isinstance( algo, geomBuilder.GEOM._objref_GEOM_Object ) and \
5424 not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object )):
5429 if isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
5431 elif not algoType and isinstance( geom, str ):
5436 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ) and not shape:
5438 elif isinstance( arg, str ) and not algoType:
5441 import traceback, sys
5442 msg = "Warning. Unexpected argument in mesh.%s() ---> %s" % ( self.method, arg )
5443 sys.stderr.write( msg + '\n' )
5444 tb = traceback.extract_stack(None,2)
5445 traceback.print_list( [tb[0]] )
5447 algoType = self.defaultAlgoType
5448 if not algoType and self.algoTypeToClass:
5449 algoType = sorted( self.algoTypeToClass.keys() )[0]
5450 if algoType in self.algoTypeToClass:
5451 #print "Create algo",algoType
5453 return self.algoTypeToClass[ algoType ]( self.mesh, shape )
5454 raise RuntimeError( "No class found for algo type %s" % algoType)
5457 ## Private class used to substitute and store variable parameters of hypotheses.
5459 class hypMethodWrapper:
5460 def __init__(self, hyp, method):
5462 self.method = method
5463 #print "REBIND:", method.__name__
5466 # call a method of hypothesis with calling SetVarParameter() before
5467 def __call__(self,*args):
5469 return self.method( self.hyp, *args ) # hypothesis method with no args
5471 #print "MethWrapper.__call__",self.method.__name__, args
5473 parsed = ParseParameters(*args) # replace variables with their values
5474 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
5475 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
5476 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
5477 # maybe there is a replaced string arg which is not variable
5478 result = self.method( self.hyp, *args )
5479 except ValueError as detail: # raised by ParseParameters()
5481 result = self.method( self.hyp, *args )
5482 except omniORB.CORBA.BAD_PARAM:
5483 raise ValueError(detail) # wrong variable name
5488 ## A helper class that calls UnRegister() of SALOME.GenericObj'es stored in it
5490 class genObjUnRegister:
5492 def __init__(self, genObj=None):
5493 self.genObjList = []
5497 def set(self, genObj):
5498 "Store one or a list of of SALOME.GenericObj'es"
5499 if isinstance( genObj, list ):
5500 self.genObjList.extend( genObj )
5502 self.genObjList.append( genObj )
5506 for genObj in self.genObjList:
5507 if genObj and hasattr( genObj, "UnRegister" ):
5511 ## Bind methods creating mesher plug-ins to the Mesh class
5513 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
5515 #print "pluginName: ", pluginName
5516 pluginBuilderName = pluginName + "Builder"
5518 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
5519 except Exception as e:
5520 from salome_utils import verbose
5521 if verbose(): print("Exception while loading %s: %s" % ( pluginBuilderName, e ))
5523 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5524 plugin = eval( pluginBuilderName )
5525 #print " plugin:" , str(plugin)
5527 # add methods creating algorithms to Mesh
5528 for k in dir( plugin ):
5529 if k[0] == '_': continue
5530 algo = getattr( plugin, k )
5531 #print " algo:", str(algo)
5532 if inspect.isclass(algo) and hasattr(algo, "meshMethod"):
5533 #print " meshMethod:" , str(algo.meshMethod)
5534 if not hasattr( Mesh, algo.meshMethod ):
5535 setattr( Mesh, algo.meshMethod, algoCreator( algo.meshMethod ))
5537 getattr( Mesh, algo.meshMethod ).add( algo )