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 pass # end of class smeshBuilder
1224 #Registering the new proxy for SMESH_Gen
1225 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1227 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1228 # interface to create or load meshes.
1233 # salome.salome_init()
1234 # from salome.smesh import smeshBuilder
1235 # smesh = smeshBuilder.New()
1237 # @param isPublished If False, the notebool will not be used.
1238 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1239 # @return smeshBuilder instance
1241 def New( isPublished = True, instance=None):
1243 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1244 interface to create or load meshes.
1248 salome.salome_init()
1249 from salome.smesh import smeshBuilder
1250 smesh = smeshBuilder.New()
1253 isPublished If False, the notebool will not be used.
1254 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1256 smeshBuilder instance
1264 smeshInst = smeshBuilder()
1265 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1266 smeshInst.init_smesh(isPublished)
1270 # Public class: Mesh
1271 # ==================
1273 ## This class allows defining and managing a mesh.
1274 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1275 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1276 # new nodes and elements and by changing the existing entities), to get information
1277 # about a mesh and to export a mesh in different formats.
1278 class Mesh(metaclass=MeshMeta):
1285 # Create a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1286 # sets the GUI name of this mesh to \a name.
1287 # @param smeshpyD an instance of smeshBuilder class
1288 # @param geompyD an instance of geomBuilder class
1289 # @param obj Shape to be meshed or SMESH_Mesh object
1290 # @param name Study name of the mesh
1291 # @ingroup l2_construct
1292 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1293 self.smeshpyD = smeshpyD
1294 self.geompyD = geompyD
1299 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1302 # publish geom of mesh (issue 0021122)
1303 if not self.geom.GetStudyEntry():
1307 geo_name = name + " shape"
1309 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1310 geompyD.addToStudy( self.geom, geo_name )
1311 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1313 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1316 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1318 self.smeshpyD.SetName(self.mesh, name)
1320 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1323 self.geom = self.mesh.GetShapeToMesh()
1325 self.editor = self.mesh.GetMeshEditor()
1326 self.functors = [None] * EnumToLong(SMESH.FT_Undefined)
1328 # set self to algoCreator's
1329 for attrName in dir(self):
1330 attr = getattr( self, attrName )
1331 if isinstance( attr, algoCreator ):
1332 setattr( self, attrName, attr.copy( self ))
1337 ## Destructor. Clean-up resources
1340 #self.mesh.UnRegister()
1344 ## Initialize the Mesh object from an instance of SMESH_Mesh interface
1345 # @param theMesh a SMESH_Mesh object
1346 # @ingroup l2_construct
1347 def SetMesh(self, theMesh):
1348 # do not call Register() as this prevents mesh servant deletion at closing study
1349 #if self.mesh: self.mesh.UnRegister()
1352 #self.mesh.Register()
1353 self.geom = self.mesh.GetShapeToMesh()
1356 ## Return the mesh, that is an instance of SMESH_Mesh interface
1357 # @return a SMESH_Mesh object
1358 # @ingroup l2_construct
1362 ## Get the name of the mesh
1363 # @return the name of the mesh as a string
1364 # @ingroup l2_construct
1366 name = GetName(self.GetMesh())
1369 ## Set a name to the mesh
1370 # @param name a new name of the mesh
1371 # @ingroup l2_construct
1372 def SetName(self, name):
1373 self.smeshpyD.SetName(self.GetMesh(), name)
1375 ## Get a sub-mesh object associated to a \a geom geometrical object.
1376 # @param geom a geometrical object (shape)
1377 # @param name a name for the sub-mesh in the Object Browser
1378 # @return an object of type SMESH.SMESH_subMesh, representing a part of mesh,
1379 # which lies on the given shape
1381 # The sub-mesh object gives access to the IDs of nodes and elements.
1382 # The sub-mesh object has the following methods:
1383 # - SMESH.SMESH_subMesh.GetNumberOfElements()
1384 # - SMESH.SMESH_subMesh.GetNumberOfNodes( all )
1385 # - SMESH.SMESH_subMesh.GetElementsId()
1386 # - SMESH.SMESH_subMesh.GetElementsByType( ElementType )
1387 # - SMESH.SMESH_subMesh.GetNodesId()
1388 # - SMESH.SMESH_subMesh.GetSubShape()
1389 # - SMESH.SMESH_subMesh.GetFather()
1390 # - SMESH.SMESH_subMesh.GetId()
1391 # @note A sub-mesh is implicitly created when a sub-shape is specified at
1392 # creating an algorithm, for example: <code>algo1D = mesh.Segment(geom=Edge_1) </code>
1393 # creates a sub-mesh on @c Edge_1 and assign Wire Discretization algorithm to it.
1394 # The created sub-mesh can be retrieved from the algorithm:
1395 # <code>submesh = algo1D.GetSubMesh()</code>
1396 # @ingroup l2_submeshes
1397 def GetSubMesh(self, geom, name):
1398 AssureGeomPublished( self, geom, name )
1399 submesh = self.mesh.GetSubMesh( geom, name )
1402 ## Return the shape associated to the mesh
1403 # @return a GEOM_Object
1404 # @ingroup l2_construct
1408 ## Associate the given shape to the mesh (entails the recreation of the mesh)
1409 # @param geom the shape to be meshed (GEOM_Object)
1410 # @ingroup l2_construct
1411 def SetShape(self, geom):
1412 self.mesh = self.smeshpyD.CreateMesh(geom)
1414 ## Load mesh from the study after opening the study
1418 ## Return true if the hypotheses are defined well
1419 # @param theSubObject a sub-shape of a mesh shape
1420 # @return True or False
1421 # @ingroup l2_construct
1422 def IsReadyToCompute(self, theSubObject):
1423 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1425 ## Return errors of hypotheses definition.
1426 # The list of errors is empty if everything is OK.
1427 # @param theSubObject a sub-shape of a mesh shape
1428 # @return a list of errors
1429 # @ingroup l2_construct
1430 def GetAlgoState(self, theSubObject):
1431 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1433 ## Return a geometrical object on which the given element was built.
1434 # The returned geometrical object, if not nil, is either found in the
1435 # study or published by this method with the given name
1436 # @param theElementID the id of the mesh element
1437 # @param theGeomName the user-defined name of the geometrical object
1438 # @return GEOM::GEOM_Object instance
1439 # @ingroup l1_meshinfo
1440 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1441 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1443 ## Return the mesh dimension depending on the dimension of the underlying shape
1444 # or, if the mesh is not based on any shape, basing on deimension of elements
1445 # @return mesh dimension as an integer value [0,3]
1446 # @ingroup l1_meshinfo
1447 def MeshDimension(self):
1448 if self.mesh.HasShapeToMesh():
1449 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1450 if len( shells ) > 0 :
1452 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1454 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1459 if self.NbVolumes() > 0: return 3
1460 if self.NbFaces() > 0: return 2
1461 if self.NbEdges() > 0: return 1
1464 ## Evaluate size of prospective mesh on a shape
1465 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1466 # To know predicted number of e.g. edges, inquire it this way
1467 # Evaluate()[ EnumToLong( Entity_Edge )]
1468 # @ingroup l2_construct
1469 def Evaluate(self, geom=0):
1470 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1472 geom = self.mesh.GetShapeToMesh()
1475 return self.smeshpyD.Evaluate(self.mesh, geom)
1478 ## Compute the mesh and return the status of the computation
1479 # @param geom geomtrical shape on which mesh data should be computed
1480 # @param discardModifs if True and the mesh has been edited since
1481 # a last total re-compute and that may prevent successful partial re-compute,
1482 # then the mesh is cleaned before Compute()
1483 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1484 # @return True or False
1485 # @ingroup l2_construct
1486 def Compute(self, geom=0, discardModifs=False, refresh=False):
1487 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1489 geom = self.mesh.GetShapeToMesh()
1494 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1496 ok = self.smeshpyD.Compute(self.mesh, geom)
1497 except SALOME.SALOME_Exception as ex:
1498 print("Mesh computation failed, exception caught:")
1499 print(" ", ex.details.text)
1502 print("Mesh computation failed, exception caught:")
1503 traceback.print_exc()
1507 # Treat compute errors
1508 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1510 for err in computeErrors:
1511 if self.mesh.HasShapeToMesh():
1512 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1514 stdErrors = ["OK", #COMPERR_OK
1515 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1516 "std::exception", #COMPERR_STD_EXCEPTION
1517 "OCC exception", #COMPERR_OCC_EXCEPTION
1518 "..", #COMPERR_SLM_EXCEPTION
1519 "Unknown exception", #COMPERR_EXCEPTION
1520 "Memory allocation problem", #COMPERR_MEMORY_PB
1521 "Algorithm failed", #COMPERR_ALGO_FAILED
1522 "Unexpected geometry", #COMPERR_BAD_SHAPE
1523 "Warning", #COMPERR_WARNING
1524 "Computation cancelled",#COMPERR_CANCELED
1525 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1527 if err.code < len(stdErrors): errText = stdErrors[err.code]
1529 errText = "code %s" % -err.code
1530 if errText: errText += ". "
1531 errText += err.comment
1532 if allReasons: allReasons += "\n"
1534 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1536 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1540 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1542 if err.isGlobalAlgo:
1550 reason = '%s %sD algorithm is missing' % (glob, dim)
1551 elif err.state == HYP_MISSING:
1552 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1553 % (glob, dim, name, dim))
1554 elif err.state == HYP_NOTCONFORM:
1555 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1556 elif err.state == HYP_BAD_PARAMETER:
1557 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1558 % ( glob, dim, name ))
1559 elif err.state == HYP_BAD_GEOMETRY:
1560 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1561 'geometry' % ( glob, dim, name ))
1562 elif err.state == HYP_HIDDEN_ALGO:
1563 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1564 'algorithm of upper dimension generating %sD mesh'
1565 % ( glob, dim, name, glob, dim ))
1567 reason = ("For unknown reason. "
1568 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1570 if allReasons: allReasons += "\n"
1571 allReasons += "- " + reason
1573 if not ok or allReasons != "":
1574 msg = '"' + GetName(self.mesh) + '"'
1575 if ok: msg += " has been computed with warnings"
1576 else: msg += " has not been computed"
1577 if allReasons != "": msg += ":"
1582 if salome.sg.hasDesktop():
1583 if not isinstance( refresh, list): # not a call from subMesh.Compute()
1584 smeshgui = salome.ImportComponentGUI("SMESH")
1586 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1587 if refresh: salome.sg.updateObjBrowser()
1591 ## Return a list of error messages (SMESH.ComputeError) of the last Compute()
1592 # @ingroup l2_construct
1593 def GetComputeErrors(self, shape=0 ):
1595 shape = self.mesh.GetShapeToMesh()
1596 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1598 ## Return a name of a sub-shape by its ID
1599 # @param subShapeID a unique ID of a sub-shape
1600 # @return a string describing the sub-shape; possible variants:
1601 # - "Face_12" (published sub-shape)
1602 # - FACE #3 (not published sub-shape)
1603 # - sub-shape #3 (invalid sub-shape ID)
1604 # - #3 (error in this function)
1605 # @ingroup l1_auxiliary
1606 def GetSubShapeName(self, subShapeID ):
1607 if not self.mesh.HasShapeToMesh():
1611 mainIOR = salome.orb.object_to_string( self.GetShape() )
1613 mainSO = s.FindObjectIOR(mainIOR)
1616 shapeText = '"%s"' % mainSO.GetName()
1617 subIt = s.NewChildIterator(mainSO)
1619 subSO = subIt.Value()
1621 obj = subSO.GetObject()
1622 if not obj: continue
1623 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1626 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1629 if ids == subShapeID:
1630 shapeText = '"%s"' % subSO.GetName()
1632 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1634 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1636 shapeText = 'sub-shape #%s' % (subShapeID)
1638 shapeText = "#%s" % (subShapeID)
1641 ## Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1642 # error of an algorithm
1643 # @param publish if @c True, the returned groups will be published in the study
1644 # @return a list of GEOM groups each named after a failed algorithm
1645 # @ingroup l2_construct
1646 def GetFailedShapes(self, publish=False):
1649 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1650 for err in computeErrors:
1651 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1652 if not shape: continue
1653 if err.algoName in algo2shapes:
1654 algo2shapes[ err.algoName ].append( shape )
1656 algo2shapes[ err.algoName ] = [ shape ]
1660 for algoName, shapes in list(algo2shapes.items()):
1662 groupType = EnumToLong( shapes[0].GetShapeType() )
1663 otherTypeShapes = []
1665 group = self.geompyD.CreateGroup( self.geom, groupType )
1666 for shape in shapes:
1667 if shape.GetShapeType() == shapes[0].GetShapeType():
1668 sameTypeShapes.append( shape )
1670 otherTypeShapes.append( shape )
1671 self.geompyD.UnionList( group, sameTypeShapes )
1673 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1675 group.SetName( algoName )
1676 groups.append( group )
1677 shapes = otherTypeShapes
1680 for group in groups:
1681 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1684 ## Return sub-mesh objects list in meshing order
1685 # @return list of lists of sub-meshes
1686 # @ingroup l2_construct
1687 def GetMeshOrder(self):
1688 return self.mesh.GetMeshOrder()
1690 ## Set order in which concurrent sub-meshes should be meshed
1691 # @param submeshes list of lists of sub-meshes
1692 # @ingroup l2_construct
1693 def SetMeshOrder(self, submeshes):
1694 return self.mesh.SetMeshOrder(submeshes)
1696 ## Remove all nodes and elements generated on geometry. Imported elements remain.
1697 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1698 # @ingroup l2_construct
1699 def Clear(self, refresh=False):
1701 if ( salome.sg.hasDesktop() ):
1702 smeshgui = salome.ImportComponentGUI("SMESH")
1704 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1705 if refresh: salome.sg.updateObjBrowser()
1707 ## Remove all nodes and elements of indicated shape
1708 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1709 # @param geomId the ID of a sub-shape to remove elements on
1710 # @ingroup l2_submeshes
1711 def ClearSubMesh(self, geomId, refresh=False):
1712 self.mesh.ClearSubMesh(geomId)
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 ## Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1720 # @param fineness [0.0,1.0] defines mesh fineness
1721 # @return True or False
1722 # @ingroup l3_algos_basic
1723 def AutomaticTetrahedralization(self, fineness=0):
1724 dim = self.MeshDimension()
1726 self.RemoveGlobalHypotheses()
1727 self.Segment().AutomaticLength(fineness)
1729 self.Triangle().LengthFromEdges()
1734 return self.Compute()
1736 ## Compute an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1737 # @param fineness [0.0, 1.0] defines mesh fineness
1738 # @return True or False
1739 # @ingroup l3_algos_basic
1740 def AutomaticHexahedralization(self, fineness=0):
1741 dim = self.MeshDimension()
1742 # assign the hypotheses
1743 self.RemoveGlobalHypotheses()
1744 self.Segment().AutomaticLength(fineness)
1751 return self.Compute()
1753 ## Assign a hypothesis
1754 # @param hyp a hypothesis to assign
1755 # @param geom a subhape of mesh geometry
1756 # @return SMESH.Hypothesis_Status
1757 # @ingroup l2_editing
1758 def AddHypothesis(self, hyp, geom=0):
1759 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1760 hyp, geom = geom, hyp
1761 if isinstance( hyp, Mesh_Algorithm ):
1762 hyp = hyp.GetAlgorithm()
1767 geom = self.mesh.GetShapeToMesh()
1770 if self.mesh.HasShapeToMesh():
1771 hyp_type = hyp.GetName()
1772 lib_name = hyp.GetLibName()
1773 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1774 # if checkAll and geom:
1775 # checkAll = geom.GetType() == 37
1777 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1779 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1780 status = self.mesh.AddHypothesis(geom, hyp)
1782 status = HYP_BAD_GEOMETRY, ""
1783 hyp_name = GetName( hyp )
1786 geom_name = geom.GetName()
1787 isAlgo = hyp._narrow( SMESH_Algo )
1788 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1791 ## Return True if an algorithm of hypothesis is assigned to a given shape
1792 # @param hyp a hypothesis to check
1793 # @param geom a subhape of mesh geometry
1794 # @return True of False
1795 # @ingroup l2_editing
1796 def IsUsedHypothesis(self, hyp, geom):
1797 if not hyp: # or not geom
1799 if isinstance( hyp, Mesh_Algorithm ):
1800 hyp = hyp.GetAlgorithm()
1802 hyps = self.GetHypothesisList(geom)
1804 if h.GetId() == hyp.GetId():
1808 ## Unassign a hypothesis
1809 # @param hyp a hypothesis to unassign
1810 # @param geom a sub-shape of mesh geometry
1811 # @return SMESH.Hypothesis_Status
1812 # @ingroup l2_editing
1813 def RemoveHypothesis(self, hyp, geom=0):
1816 if isinstance( hyp, Mesh_Algorithm ):
1817 hyp = hyp.GetAlgorithm()
1823 if self.IsUsedHypothesis( hyp, shape ):
1824 return self.mesh.RemoveHypothesis( shape, hyp )
1825 hypName = GetName( hyp )
1826 geoName = GetName( shape )
1827 print("WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName ))
1830 ## Get the list of hypotheses added on a geometry
1831 # @param geom a sub-shape of mesh geometry
1832 # @return the sequence of SMESH_Hypothesis
1833 # @ingroup l2_editing
1834 def GetHypothesisList(self, geom):
1835 return self.mesh.GetHypothesisList( geom )
1837 ## Remove all global hypotheses
1838 # @ingroup l2_editing
1839 def RemoveGlobalHypotheses(self):
1840 current_hyps = self.mesh.GetHypothesisList( self.geom )
1841 for hyp in current_hyps:
1842 self.mesh.RemoveHypothesis( self.geom, hyp )
1846 ## Export the mesh in a file in MED format
1847 ## allowing to overwrite the file if it exists or add the exported data to its contents
1848 # @param fileName is the file name
1849 # @param auto_groups boolean parameter for creating/not creating
1850 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1851 # the typical use is auto_groups=False.
1852 # @param overwrite boolean parameter for overwriting/not overwriting the file
1853 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1854 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1855 # - 1D if all mesh nodes lie on OX coordinate axis, or
1856 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1857 # - 3D in the rest cases.<br>
1858 # If @a autoDimension is @c False, the space dimension is always 3.
1859 # @param fields list of GEOM fields defined on the shape to mesh.
1860 # @param geomAssocFields each character of this string means a need to export a
1861 # corresponding field; correspondence between fields and characters is following:
1862 # - 'v' stands for "_vertices _" field;
1863 # - 'e' stands for "_edges _" field;
1864 # - 'f' stands for "_faces _" field;
1865 # - 's' stands for "_solids _" field.
1866 # @ingroup l2_impexp
1867 def ExportMED(self, *args, **kwargs):
1868 # process positional arguments
1869 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
1871 auto_groups = args[1] if len(args) > 1 else False
1872 overwrite = args[2] if len(args) > 2 else True
1873 meshPart = args[3] if len(args) > 3 else None
1874 autoDimension = args[4] if len(args) > 4 else True
1875 fields = args[5] if len(args) > 5 else []
1876 geomAssocFields = args[6] if len(args) > 6 else ''
1877 # process keywords arguments
1878 auto_groups = kwargs.get("auto_groups", auto_groups)
1879 overwrite = kwargs.get("overwrite", overwrite)
1880 meshPart = kwargs.get("meshPart", meshPart)
1881 autoDimension = kwargs.get("autoDimension", autoDimension)
1882 fields = kwargs.get("fields", fields)
1883 geomAssocFields = kwargs.get("geomAssocFields", geomAssocFields)
1884 # invoke engine's function
1885 if meshPart or fields or geomAssocFields:
1886 unRegister = genObjUnRegister()
1887 if isinstance( meshPart, list ):
1888 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1889 unRegister.set( meshPart )
1890 self.mesh.ExportPartToMED( meshPart, fileName, auto_groups, overwrite, autoDimension,
1891 fields, geomAssocFields)
1893 self.mesh.ExportMED(fileName, auto_groups, overwrite, autoDimension)
1895 ## Export the mesh in a file in SAUV format
1896 # @param f is the file name
1897 # @param auto_groups boolean parameter for creating/not creating
1898 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1899 # the typical use is auto_groups=false.
1900 # @ingroup l2_impexp
1901 def ExportSAUV(self, f, auto_groups=0):
1902 self.mesh.ExportSAUV(f, auto_groups)
1904 ## Export the mesh in a file in DAT format
1905 # @param f the file name
1906 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1907 # @ingroup l2_impexp
1908 def ExportDAT(self, f, meshPart=None):
1910 unRegister = genObjUnRegister()
1911 if isinstance( meshPart, list ):
1912 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1913 unRegister.set( meshPart )
1914 self.mesh.ExportPartToDAT( meshPart, f )
1916 self.mesh.ExportDAT(f)
1918 ## Export the mesh in a file in UNV format
1919 # @param f the file name
1920 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1921 # @ingroup l2_impexp
1922 def ExportUNV(self, f, meshPart=None):
1924 unRegister = genObjUnRegister()
1925 if isinstance( meshPart, list ):
1926 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1927 unRegister.set( meshPart )
1928 self.mesh.ExportPartToUNV( meshPart, f )
1930 self.mesh.ExportUNV(f)
1932 ## Export the mesh in a file in STL format
1933 # @param f the file name
1934 # @param ascii defines the file encoding
1935 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1936 # @ingroup l2_impexp
1937 def ExportSTL(self, f, ascii=1, meshPart=None):
1939 unRegister = genObjUnRegister()
1940 if isinstance( meshPart, list ):
1941 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1942 unRegister.set( meshPart )
1943 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1945 self.mesh.ExportSTL(f, ascii)
1947 ## Export the mesh in a file in CGNS format
1948 # @param f is the file name
1949 # @param overwrite boolean parameter for overwriting/not overwriting the file
1950 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1951 # @param groupElemsByType if true all elements of same entity type are exported at ones,
1952 # else elements are exported in order of their IDs which can cause creation
1953 # of multiple cgns sections
1954 # @ingroup l2_impexp
1955 def ExportCGNS(self, f, overwrite=1, meshPart=None, groupElemsByType=False):
1956 unRegister = genObjUnRegister()
1957 if isinstance( meshPart, list ):
1958 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1959 unRegister.set( meshPart )
1960 if isinstance( meshPart, Mesh ):
1961 meshPart = meshPart.mesh
1963 meshPart = self.mesh
1964 self.mesh.ExportCGNS(meshPart, f, overwrite, groupElemsByType)
1966 ## Export the mesh in a file in GMF format.
1967 # GMF files must have .mesh extension for the ASCII format and .meshb for
1968 # the bynary format. Other extensions are not allowed.
1969 # @param f is the file name
1970 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1971 # @ingroup l2_impexp
1972 def ExportGMF(self, f, meshPart=None):
1973 unRegister = genObjUnRegister()
1974 if isinstance( meshPart, list ):
1975 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1976 unRegister.set( meshPart )
1977 if isinstance( meshPart, Mesh ):
1978 meshPart = meshPart.mesh
1980 meshPart = self.mesh
1981 self.mesh.ExportGMF(meshPart, f, True)
1983 ## Deprecated, used only for compatibility! Please, use ExportMED() method instead.
1984 # Export the mesh in a file in MED format
1985 # allowing to overwrite the file if it exists or add the exported data to its contents
1986 # @param fileName the file name
1987 # @param opt boolean parameter for creating/not creating
1988 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1989 # @param overwrite boolean parameter for overwriting/not overwriting the file
1990 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1991 # - 1D if all mesh nodes lie on OX coordinate axis, or
1992 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1993 # - 3D in the rest cases.<br>
1994 # If @a autoDimension is @c False, the space dimension is always 3.
1995 # @ingroup l2_impexp
1996 def ExportToMED(self, *args, **kwargs):
1997 print("WARNING: ExportToMED() is deprecated, use ExportMED() instead")
1998 # process positional arguments
1999 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
2001 auto_groups = args[1] if len(args) > 1 else False
2002 overwrite = args[2] if len(args) > 2 else True
2003 autoDimension = args[3] if len(args) > 3 else True
2004 # process keywords arguments
2005 auto_groups = kwargs.get("opt", auto_groups) # old keyword name
2006 auto_groups = kwargs.get("auto_groups", auto_groups) # new keyword name
2007 overwrite = kwargs.get("overwrite", overwrite)
2008 autoDimension = kwargs.get("autoDimension", autoDimension)
2009 # invoke engine's function
2010 self.mesh.ExportMED(fileName, auto_groups, overwrite, autoDimension)
2012 ## Deprecated, used only for compatibility! Please, use ExportMED() method instead.
2013 # Export the mesh in a file in MED format
2014 # allowing to overwrite the file if it exists or add the exported data to its contents
2015 # @param fileName the file name
2016 # @param opt boolean parameter for creating/not creating
2017 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
2018 # @param overwrite boolean parameter for overwriting/not overwriting the file
2019 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
2020 # - 1D if all mesh nodes lie on OX coordinate axis, or
2021 # - 2D if all mesh nodes lie on XOY coordinate plane, or
2022 # - 3D in the rest cases.<br>
2023 # If @a autoDimension is @c False, the space dimension is always 3.
2024 # @ingroup l2_impexp
2025 def ExportToMEDX(self, *args, **kwargs):
2026 print("WARNING: ExportToMEDX() is deprecated, use ExportMED() instead")
2027 # process positional arguments
2028 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
2030 auto_groups = args[1] if len(args) > 1 else False
2031 overwrite = args[2] if len(args) > 2 else True
2032 autoDimension = args[3] if len(args) > 3 else True
2033 # process keywords arguments
2034 auto_groups = kwargs.get("auto_groups", auto_groups)
2035 overwrite = kwargs.get("overwrite", overwrite)
2036 autoDimension = kwargs.get("autoDimension", autoDimension)
2037 # invoke engine's function
2038 self.mesh.ExportMED(fileName, auto_groups, overwrite, autoDimension)
2040 # Operations with groups:
2041 # ----------------------
2043 ## Create an empty mesh group
2044 # @param elementType the type of elements in the group; either of
2045 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2046 # @param name the name of the mesh group
2047 # @return SMESH_Group
2048 # @ingroup l2_grps_create
2049 def CreateEmptyGroup(self, elementType, name):
2050 return self.mesh.CreateGroup(elementType, name)
2052 ## Create a mesh group based on the geometric object \a grp
2053 # and gives a \a name, \n if this parameter is not defined
2054 # the name is the same as the geometric group name \n
2055 # Note: Works like GroupOnGeom().
2056 # @param grp a geometric group, a vertex, an edge, a face or a solid
2057 # @param name the name of the mesh group
2058 # @return SMESH_GroupOnGeom
2059 # @ingroup l2_grps_create
2060 def Group(self, grp, name=""):
2061 return self.GroupOnGeom(grp, name)
2063 ## Create a mesh group based on the geometrical object \a grp
2064 # and gives a \a name, \n if this parameter is not defined
2065 # the name is the same as the geometrical group name
2066 # @param grp a geometrical group, a vertex, an edge, a face or a solid
2067 # @param name the name of the mesh group
2068 # @param typ the type of elements in the group; either of
2069 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
2070 # automatically detected by the type of the geometry
2071 # @return SMESH_GroupOnGeom
2072 # @ingroup l2_grps_create
2073 def GroupOnGeom(self, grp, name="", typ=None):
2074 AssureGeomPublished( self, grp, name )
2076 name = grp.GetName()
2078 typ = self._groupTypeFromShape( grp )
2079 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
2081 ## Pivate method to get a type of group on geometry
2082 def _groupTypeFromShape( self, shape ):
2083 tgeo = str(shape.GetShapeType())
2084 if tgeo == "VERTEX":
2086 elif tgeo == "EDGE":
2088 elif tgeo == "FACE" or tgeo == "SHELL":
2090 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
2092 elif tgeo == "COMPOUND":
2093 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
2095 raise ValueError("_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape))
2096 return self._groupTypeFromShape( sub[0] )
2098 raise ValueError("_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape))
2101 ## Create a mesh group with given \a name based on the \a filter which
2102 ## is a special type of group dynamically updating it's contents during
2103 ## mesh modification
2104 # @param typ the type of elements in the group; either of
2105 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2106 # @param name the name of the mesh group
2107 # @param filter the filter defining group contents
2108 # @return SMESH_GroupOnFilter
2109 # @ingroup l2_grps_create
2110 def GroupOnFilter(self, typ, name, filter):
2111 return self.mesh.CreateGroupFromFilter(typ, name, filter)
2113 ## Create a mesh group by the given ids of elements
2114 # @param groupName the name of the mesh group
2115 # @param elementType the type of elements in the group; either of
2116 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2117 # @param elemIDs either the list of ids, group, sub-mesh, or filter
2118 # @return SMESH_Group
2119 # @ingroup l2_grps_create
2120 def MakeGroupByIds(self, groupName, elementType, elemIDs):
2121 group = self.mesh.CreateGroup(elementType, groupName)
2122 if isinstance( elemIDs, Mesh ):
2123 elemIDs = elemIDs.GetMesh()
2124 if hasattr( elemIDs, "GetIDs" ):
2125 if hasattr( elemIDs, "SetMesh" ):
2126 elemIDs.SetMesh( self.GetMesh() )
2127 group.AddFrom( elemIDs )
2132 ## Create a mesh group by the given conditions
2133 # @param groupName the name of the mesh group
2134 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2135 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
2136 # Type SMESH.FunctorType._items in the Python Console to see all values.
2137 # Note that the items starting from FT_LessThan are not suitable for CritType.
2138 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
2139 # @param Threshold the threshold value (range of ids as string, shape, numeric)
2140 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2141 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2142 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2143 # @return SMESH_GroupOnFilter
2144 # @ingroup l2_grps_create
2148 CritType=FT_Undefined,
2151 UnaryOp=FT_Undefined,
2153 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2154 group = self.MakeGroupByCriterion(groupName, aCriterion)
2157 ## Create a mesh group by the given criterion
2158 # @param groupName the name of the mesh group
2159 # @param Criterion the instance of Criterion class
2160 # @return SMESH_GroupOnFilter
2161 # @ingroup l2_grps_create
2162 def MakeGroupByCriterion(self, groupName, Criterion):
2163 return self.MakeGroupByCriteria( groupName, [Criterion] )
2165 ## Create a mesh group by the given criteria (list of criteria)
2166 # @param groupName the name of the mesh group
2167 # @param theCriteria the list of criteria
2168 # @param binOp binary operator used when binary operator of criteria is undefined
2169 # @return SMESH_GroupOnFilter
2170 # @ingroup l2_grps_create
2171 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2172 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2173 group = self.MakeGroupByFilter(groupName, aFilter)
2176 ## Create a mesh group by the given filter
2177 # @param groupName the name of the mesh group
2178 # @param theFilter the instance of Filter class
2179 # @return SMESH_GroupOnFilter
2180 # @ingroup l2_grps_create
2181 def MakeGroupByFilter(self, groupName, theFilter):
2182 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2183 #theFilter.SetMesh( self.mesh )
2184 #group.AddFrom( theFilter )
2185 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2189 # @ingroup l2_grps_delete
2190 def RemoveGroup(self, group):
2191 self.mesh.RemoveGroup(group)
2193 ## Remove a group with its contents
2194 # @ingroup l2_grps_delete
2195 def RemoveGroupWithContents(self, group):
2196 self.mesh.RemoveGroupWithContents(group)
2198 ## Get the list of groups existing in the mesh in the order
2199 # of creation (starting from the oldest one)
2200 # @param elemType type of elements the groups contain; either of
2201 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2202 # by default groups of elements of all types are returned
2203 # @return a sequence of SMESH_GroupBase
2204 # @ingroup l2_grps_create
2205 def GetGroups(self, elemType = SMESH.ALL):
2206 groups = self.mesh.GetGroups()
2207 if elemType == SMESH.ALL:
2211 if g.GetType() == elemType:
2212 typedGroups.append( g )
2217 ## Get the number of groups existing in the mesh
2218 # @return the quantity of groups as an integer value
2219 # @ingroup l2_grps_create
2221 return self.mesh.NbGroups()
2223 ## Get the list of names of groups existing in the mesh
2224 # @return list of strings
2225 # @ingroup l2_grps_create
2226 def GetGroupNames(self):
2227 groups = self.GetGroups()
2229 for group in groups:
2230 names.append(group.GetName())
2233 ## Find groups by name and type
2234 # @param name name of the group of interest
2235 # @param elemType type of elements the groups contain; either of
2236 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2237 # by default one group of any type of elements is returned
2238 # if elemType == SMESH.ALL then all groups of any type are returned
2239 # @return a list of SMESH_GroupBase's
2240 # @ingroup l2_grps_create
2241 def GetGroupByName(self, name, elemType = None):
2243 for group in self.GetGroups():
2244 if group.GetName() == name:
2245 if elemType is None:
2247 if ( elemType == SMESH.ALL or
2248 group.GetType() == elemType ):
2249 groups.append( group )
2252 ## Produce a union of two groups.
2253 # A new group is created. All mesh elements that are
2254 # present in the initial groups are added to the new one
2255 # @return an instance of SMESH_Group
2256 # @ingroup l2_grps_operon
2257 def UnionGroups(self, group1, group2, name):
2258 return self.mesh.UnionGroups(group1, group2, name)
2260 ## Produce a union list of groups.
2261 # New group is created. All mesh elements that are present in
2262 # initial groups are added to the new one
2263 # @return an instance of SMESH_Group
2264 # @ingroup l2_grps_operon
2265 def UnionListOfGroups(self, groups, name):
2266 return self.mesh.UnionListOfGroups(groups, name)
2268 ## Prodice an intersection of two groups.
2269 # A new group is created. All mesh elements that are common
2270 # for the two initial groups are added to the new one.
2271 # @return an instance of SMESH_Group
2272 # @ingroup l2_grps_operon
2273 def IntersectGroups(self, group1, group2, name):
2274 return self.mesh.IntersectGroups(group1, group2, name)
2276 ## Produce an intersection of groups.
2277 # New group is created. All mesh elements that are present in all
2278 # initial groups simultaneously are added to the new one
2279 # @return an instance of SMESH_Group
2280 # @ingroup l2_grps_operon
2281 def IntersectListOfGroups(self, groups, name):
2282 return self.mesh.IntersectListOfGroups(groups, name)
2284 ## Produce a cut of two groups.
2285 # A new group is created. All mesh elements that are present in
2286 # the main group but are not present in the tool group are added to the new one
2287 # @return an instance of SMESH_Group
2288 # @ingroup l2_grps_operon
2289 def CutGroups(self, main_group, tool_group, name):
2290 return self.mesh.CutGroups(main_group, tool_group, name)
2292 ## Produce a cut of groups.
2293 # A new group is created. All mesh elements that are present in main groups
2294 # but do not present in tool groups are added to the new one
2295 # @return an instance of SMESH_Group
2296 # @ingroup l2_grps_operon
2297 def CutListOfGroups(self, main_groups, tool_groups, name):
2298 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2301 # Create a standalone group of entities basing on nodes of other groups.
2302 # \param groups - list of reference groups, sub-meshes or filters, of any type.
2303 # \param elemType - a type of elements to include to the new group; either of
2304 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2305 # \param name - a name of the new group.
2306 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2307 # basing on number of element nodes common with reference \a groups.
2308 # Meaning of possible values are:
2309 # - SMESH.ALL_NODES - include if all nodes are common,
2310 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2311 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2312 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2313 # \param underlyingOnly - if \c True (default), an element is included to the
2314 # new group provided that it is based on nodes of an element of \a groups;
2315 # in this case the reference \a groups are supposed to be of higher dimension
2316 # than \a elemType, which can be useful for example to get all faces lying on
2317 # volumes of the reference \a groups.
2318 # @return an instance of SMESH_Group
2319 # @ingroup l2_grps_operon
2320 def CreateDimGroup(self, groups, elemType, name,
2321 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2322 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2324 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2327 ## Convert group on geom into standalone group
2328 # @ingroup l2_grps_operon
2329 def ConvertToStandalone(self, group):
2330 return self.mesh.ConvertToStandalone(group)
2332 # Get some info about mesh:
2333 # ------------------------
2335 ## Return the log of nodes and elements added or removed
2336 # since the previous clear of the log.
2337 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2338 # @return list of log_block structures:
2343 # @ingroup l1_auxiliary
2344 def GetLog(self, clearAfterGet):
2345 return self.mesh.GetLog(clearAfterGet)
2347 ## Clear the log of nodes and elements added or removed since the previous
2348 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2349 # @ingroup l1_auxiliary
2351 self.mesh.ClearLog()
2353 ## Toggle auto color mode on the object.
2354 # @param theAutoColor the flag which toggles auto color mode.
2356 # If switched on, a default color of a new group in Create Group dialog is chosen randomly.
2357 # @ingroup l1_grouping
2358 def SetAutoColor(self, theAutoColor):
2359 self.mesh.SetAutoColor(theAutoColor)
2361 ## Get flag of object auto color mode.
2362 # @return True or False
2363 # @ingroup l1_grouping
2364 def GetAutoColor(self):
2365 return self.mesh.GetAutoColor()
2367 ## Get the internal ID
2368 # @return integer value, which is the internal Id of the mesh
2369 # @ingroup l1_auxiliary
2371 return self.mesh.GetId()
2373 ## Check the group names for duplications.
2374 # Consider the maximum group name length stored in MED file.
2375 # @return True or False
2376 # @ingroup l1_grouping
2377 def HasDuplicatedGroupNamesMED(self):
2378 return self.mesh.HasDuplicatedGroupNamesMED()
2380 ## Obtain the mesh editor tool
2381 # @return an instance of SMESH_MeshEditor
2382 # @ingroup l1_modifying
2383 def GetMeshEditor(self):
2386 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2387 # can be passed as argument to a method accepting mesh, group or sub-mesh
2388 # @param ids list of IDs
2389 # @param elemType type of elements; this parameter is used to distinguish
2390 # IDs of nodes from IDs of elements; by default ids are treated as
2391 # IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2392 # @return an instance of SMESH_IDSource
2393 # @warning call UnRegister() for the returned object as soon as it is no more useful:
2394 # idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2395 # mesh.DoSomething( idSrc )
2396 # idSrc.UnRegister()
2397 # @ingroup l1_auxiliary
2398 def GetIDSource(self, ids, elemType = SMESH.ALL):
2399 if isinstance( ids, int ):
2401 return self.editor.MakeIDSource(ids, elemType)
2404 # Get information about mesh contents:
2405 # ------------------------------------
2407 ## Get the mesh statistic
2408 # @return dictionary type element - count of elements
2409 # @ingroup l1_meshinfo
2410 def GetMeshInfo(self, obj = None):
2411 if not obj: obj = self.mesh
2412 return self.smeshpyD.GetMeshInfo(obj)
2414 ## Return the number of nodes in the mesh
2415 # @return an integer value
2416 # @ingroup l1_meshinfo
2418 return self.mesh.NbNodes()
2420 ## Return the number of elements in the mesh
2421 # @return an integer value
2422 # @ingroup l1_meshinfo
2423 def NbElements(self):
2424 return self.mesh.NbElements()
2426 ## Return the number of 0d elements in the mesh
2427 # @return an integer value
2428 # @ingroup l1_meshinfo
2429 def Nb0DElements(self):
2430 return self.mesh.Nb0DElements()
2432 ## Return the number of ball discrete elements in the mesh
2433 # @return an integer value
2434 # @ingroup l1_meshinfo
2436 return self.mesh.NbBalls()
2438 ## Return the number of edges in the mesh
2439 # @return an integer value
2440 # @ingroup l1_meshinfo
2442 return self.mesh.NbEdges()
2444 ## Return the number of edges with the given order in the mesh
2445 # @param elementOrder the order of elements:
2446 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2447 # @return an integer value
2448 # @ingroup l1_meshinfo
2449 def NbEdgesOfOrder(self, elementOrder):
2450 return self.mesh.NbEdgesOfOrder(elementOrder)
2452 ## Return the number of faces in the mesh
2453 # @return an integer value
2454 # @ingroup l1_meshinfo
2456 return self.mesh.NbFaces()
2458 ## Return the number of faces with the given order in the mesh
2459 # @param elementOrder the order of elements:
2460 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2461 # @return an integer value
2462 # @ingroup l1_meshinfo
2463 def NbFacesOfOrder(self, elementOrder):
2464 return self.mesh.NbFacesOfOrder(elementOrder)
2466 ## Return the number of triangles in the mesh
2467 # @return an integer value
2468 # @ingroup l1_meshinfo
2469 def NbTriangles(self):
2470 return self.mesh.NbTriangles()
2472 ## Return the number of triangles with the given order in the mesh
2473 # @param elementOrder is the order of elements:
2474 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2475 # @return an integer value
2476 # @ingroup l1_meshinfo
2477 def NbTrianglesOfOrder(self, elementOrder):
2478 return self.mesh.NbTrianglesOfOrder(elementOrder)
2480 ## Return the number of biquadratic triangles in the mesh
2481 # @return an integer value
2482 # @ingroup l1_meshinfo
2483 def NbBiQuadTriangles(self):
2484 return self.mesh.NbBiQuadTriangles()
2486 ## Return the number of quadrangles in the mesh
2487 # @return an integer value
2488 # @ingroup l1_meshinfo
2489 def NbQuadrangles(self):
2490 return self.mesh.NbQuadrangles()
2492 ## Return the number of quadrangles with the given order in the mesh
2493 # @param elementOrder the order of elements:
2494 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2495 # @return an integer value
2496 # @ingroup l1_meshinfo
2497 def NbQuadranglesOfOrder(self, elementOrder):
2498 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2500 ## Return the number of biquadratic quadrangles in the mesh
2501 # @return an integer value
2502 # @ingroup l1_meshinfo
2503 def NbBiQuadQuadrangles(self):
2504 return self.mesh.NbBiQuadQuadrangles()
2506 ## Return the number of polygons of given order in the mesh
2507 # @param elementOrder the order of elements:
2508 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2509 # @return an integer value
2510 # @ingroup l1_meshinfo
2511 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2512 return self.mesh.NbPolygonsOfOrder(elementOrder)
2514 ## Return the number of volumes in the mesh
2515 # @return an integer value
2516 # @ingroup l1_meshinfo
2517 def NbVolumes(self):
2518 return self.mesh.NbVolumes()
2520 ## Return the number of volumes with the given order in the mesh
2521 # @param elementOrder the order of elements:
2522 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2523 # @return an integer value
2524 # @ingroup l1_meshinfo
2525 def NbVolumesOfOrder(self, elementOrder):
2526 return self.mesh.NbVolumesOfOrder(elementOrder)
2528 ## Return the number of tetrahedrons in the mesh
2529 # @return an integer value
2530 # @ingroup l1_meshinfo
2532 return self.mesh.NbTetras()
2534 ## Return the number of tetrahedrons with the given order in the mesh
2535 # @param elementOrder the order of elements:
2536 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2537 # @return an integer value
2538 # @ingroup l1_meshinfo
2539 def NbTetrasOfOrder(self, elementOrder):
2540 return self.mesh.NbTetrasOfOrder(elementOrder)
2542 ## Return the number of hexahedrons in the mesh
2543 # @return an integer value
2544 # @ingroup l1_meshinfo
2546 return self.mesh.NbHexas()
2548 ## Return the number of hexahedrons with the given order in the mesh
2549 # @param elementOrder the order of elements:
2550 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2551 # @return an integer value
2552 # @ingroup l1_meshinfo
2553 def NbHexasOfOrder(self, elementOrder):
2554 return self.mesh.NbHexasOfOrder(elementOrder)
2556 ## Return the number of triquadratic hexahedrons in the mesh
2557 # @return an integer value
2558 # @ingroup l1_meshinfo
2559 def NbTriQuadraticHexas(self):
2560 return self.mesh.NbTriQuadraticHexas()
2562 ## Return the number of pyramids in the mesh
2563 # @return an integer value
2564 # @ingroup l1_meshinfo
2565 def NbPyramids(self):
2566 return self.mesh.NbPyramids()
2568 ## Return the number of pyramids with the given order in the mesh
2569 # @param elementOrder the order of elements:
2570 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2571 # @return an integer value
2572 # @ingroup l1_meshinfo
2573 def NbPyramidsOfOrder(self, elementOrder):
2574 return self.mesh.NbPyramidsOfOrder(elementOrder)
2576 ## Return the number of prisms in the mesh
2577 # @return an integer value
2578 # @ingroup l1_meshinfo
2580 return self.mesh.NbPrisms()
2582 ## Return the number of prisms with the given order in the mesh
2583 # @param elementOrder the order of elements:
2584 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2585 # @return an integer value
2586 # @ingroup l1_meshinfo
2587 def NbPrismsOfOrder(self, elementOrder):
2588 return self.mesh.NbPrismsOfOrder(elementOrder)
2590 ## Return the number of hexagonal prisms in the mesh
2591 # @return an integer value
2592 # @ingroup l1_meshinfo
2593 def NbHexagonalPrisms(self):
2594 return self.mesh.NbHexagonalPrisms()
2596 ## Return the number of polyhedrons in the mesh
2597 # @return an integer value
2598 # @ingroup l1_meshinfo
2599 def NbPolyhedrons(self):
2600 return self.mesh.NbPolyhedrons()
2602 ## Return the number of submeshes in the mesh
2603 # @return an integer value
2604 # @ingroup l1_meshinfo
2605 def NbSubMesh(self):
2606 return self.mesh.NbSubMesh()
2608 ## Return the list of mesh elements IDs
2609 # @return the list of integer values
2610 # @ingroup l1_meshinfo
2611 def GetElementsId(self):
2612 return self.mesh.GetElementsId()
2614 ## Return the list of IDs of mesh elements with the given type
2615 # @param elementType the required type of elements, either of
2616 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2617 # @return list of integer values
2618 # @ingroup l1_meshinfo
2619 def GetElementsByType(self, elementType):
2620 return self.mesh.GetElementsByType(elementType)
2622 ## Return the list of mesh nodes IDs
2623 # @return the list of integer values
2624 # @ingroup l1_meshinfo
2625 def GetNodesId(self):
2626 return self.mesh.GetNodesId()
2628 # Get the information about mesh elements:
2629 # ------------------------------------
2631 ## Return the type of mesh element
2632 # @return the value from SMESH::ElementType enumeration
2633 # Type SMESH.ElementType._items in the Python Console to see all possible values.
2634 # @ingroup l1_meshinfo
2635 def GetElementType(self, id, iselem=True):
2636 return self.mesh.GetElementType(id, iselem)
2638 ## Return the geometric type of mesh element
2639 # @return the value from SMESH::EntityType enumeration
2640 # Type SMESH.EntityType._items in the Python Console to see all possible values.
2641 # @ingroup l1_meshinfo
2642 def GetElementGeomType(self, id):
2643 return self.mesh.GetElementGeomType(id)
2645 ## Return the shape type of mesh element
2646 # @return the value from SMESH::GeometryType enumeration.
2647 # Type SMESH.GeometryType._items in the Python Console to see all possible values.
2648 # @ingroup l1_meshinfo
2649 def GetElementShape(self, id):
2650 return self.mesh.GetElementShape(id)
2652 ## Return the list of submesh elements IDs
2653 # @param Shape a geom object(sub-shape)
2654 # Shape must be the sub-shape of a ShapeToMesh()
2655 # @return the list of integer values
2656 # @ingroup l1_meshinfo
2657 def GetSubMeshElementsId(self, Shape):
2658 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2659 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2662 return self.mesh.GetSubMeshElementsId(ShapeID)
2664 ## Return the list of submesh nodes IDs
2665 # @param Shape a geom object(sub-shape)
2666 # Shape must be the sub-shape of a ShapeToMesh()
2667 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2668 # @return the list of integer values
2669 # @ingroup l1_meshinfo
2670 def GetSubMeshNodesId(self, Shape, all):
2671 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2672 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2675 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2677 ## Return type of elements on given shape
2678 # @param Shape a geom object(sub-shape)
2679 # Shape must be a sub-shape of a ShapeToMesh()
2680 # @return element type
2681 # @ingroup l1_meshinfo
2682 def GetSubMeshElementType(self, Shape):
2683 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2684 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2687 return self.mesh.GetSubMeshElementType(ShapeID)
2689 ## Get the mesh description
2690 # @return string value
2691 # @ingroup l1_meshinfo
2693 return self.mesh.Dump()
2696 # Get the information about nodes and elements of a mesh by its IDs:
2697 # -----------------------------------------------------------
2699 ## Get XYZ coordinates of a node
2700 # \n If there is no nodes for the given ID - return an empty list
2701 # @return a list of double precision values
2702 # @ingroup l1_meshinfo
2703 def GetNodeXYZ(self, id):
2704 return self.mesh.GetNodeXYZ(id)
2706 ## Return list of IDs of inverse elements for the given node
2707 # \n If there is no node for the given ID - return an empty list
2708 # @return a list of integer values
2709 # @ingroup l1_meshinfo
2710 def GetNodeInverseElements(self, id):
2711 return self.mesh.GetNodeInverseElements(id)
2713 ## Return the position of a node on the shape
2714 # @return SMESH::NodePosition
2715 # @ingroup l1_meshinfo
2716 def GetNodePosition(self,NodeID):
2717 return self.mesh.GetNodePosition(NodeID)
2719 ## Return the position of an element on the shape
2720 # @return SMESH::ElementPosition
2721 # @ingroup l1_meshinfo
2722 def GetElementPosition(self,ElemID):
2723 return self.mesh.GetElementPosition(ElemID)
2725 ## Return the ID of the shape, on which the given node was generated.
2726 # @return an integer value > 0 or -1 if there is no node for the given
2727 # ID or the node is not assigned to any geometry
2728 # @ingroup l1_meshinfo
2729 def GetShapeID(self, id):
2730 return self.mesh.GetShapeID(id)
2732 ## Return the ID of the shape, on which the given element was generated.
2733 # @return an integer value > 0 or -1 if there is no element for the given
2734 # ID or the element is not assigned to any geometry
2735 # @ingroup l1_meshinfo
2736 def GetShapeIDForElem(self,id):
2737 return self.mesh.GetShapeIDForElem(id)
2739 ## Return the number of nodes of the given element
2740 # @return an integer value > 0 or -1 if there is no element for the given ID
2741 # @ingroup l1_meshinfo
2742 def GetElemNbNodes(self, id):
2743 return self.mesh.GetElemNbNodes(id)
2745 ## Return the node ID the given (zero based) index for the given element
2746 # \n If there is no element for the given ID - return -1
2747 # \n If there is no node for the given index - return -2
2748 # @return an integer value
2749 # @ingroup l1_meshinfo
2750 def GetElemNode(self, id, index):
2751 return self.mesh.GetElemNode(id, index)
2753 ## Return the IDs of nodes of the given element
2754 # @return a list of integer values
2755 # @ingroup l1_meshinfo
2756 def GetElemNodes(self, id):
2757 return self.mesh.GetElemNodes(id)
2759 ## Return true if the given node is the medium node in the given quadratic element
2760 # @ingroup l1_meshinfo
2761 def IsMediumNode(self, elementID, nodeID):
2762 return self.mesh.IsMediumNode(elementID, nodeID)
2764 ## Return true if the given node is the medium node in one of quadratic elements
2765 # @param nodeID ID of the node
2766 # @param elementType the type of elements to check a state of the node, either of
2767 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2768 # @ingroup l1_meshinfo
2769 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2770 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2772 ## Return the number of edges for the given element
2773 # @ingroup l1_meshinfo
2774 def ElemNbEdges(self, id):
2775 return self.mesh.ElemNbEdges(id)
2777 ## Return the number of faces for the given element
2778 # @ingroup l1_meshinfo
2779 def ElemNbFaces(self, id):
2780 return self.mesh.ElemNbFaces(id)
2782 ## Return nodes of given face (counted from zero) for given volumic element.
2783 # @ingroup l1_meshinfo
2784 def GetElemFaceNodes(self,elemId, faceIndex):
2785 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2787 ## Return three components of normal of given mesh face
2788 # (or an empty array in KO case)
2789 # @ingroup l1_meshinfo
2790 def GetFaceNormal(self, faceId, normalized=False):
2791 return self.mesh.GetFaceNormal(faceId,normalized)
2793 ## Return an element based on all given nodes.
2794 # @ingroup l1_meshinfo
2795 def FindElementByNodes(self, nodes):
2796 return self.mesh.FindElementByNodes(nodes)
2798 ## Return elements including all given nodes.
2799 # @ingroup l1_meshinfo
2800 def GetElementsByNodes(self, nodes, elemType=SMESH.ALL):
2801 return self.mesh.GetElementsByNodes( nodes, elemType )
2803 ## Return true if the given element is a polygon
2804 # @ingroup l1_meshinfo
2805 def IsPoly(self, id):
2806 return self.mesh.IsPoly(id)
2808 ## Return true if the given element is quadratic
2809 # @ingroup l1_meshinfo
2810 def IsQuadratic(self, id):
2811 return self.mesh.IsQuadratic(id)
2813 ## Return diameter of a ball discrete element or zero in case of an invalid \a id
2814 # @ingroup l1_meshinfo
2815 def GetBallDiameter(self, id):
2816 return self.mesh.GetBallDiameter(id)
2818 ## Return XYZ coordinates of the barycenter of the given element
2819 # \n If there is no element for the given ID - return an empty list
2820 # @return a list of three double values
2821 # @ingroup l1_meshinfo
2822 def BaryCenter(self, id):
2823 return self.mesh.BaryCenter(id)
2825 ## Pass mesh elements through the given filter and return IDs of fitting elements
2826 # @param theFilter SMESH_Filter
2827 # @return a list of ids
2828 # @ingroup l1_controls
2829 def GetIdsFromFilter(self, theFilter):
2830 theFilter.SetMesh( self.mesh )
2831 return theFilter.GetIDs()
2833 # Get mesh measurements information:
2834 # ------------------------------------
2836 ## Verify whether a 2D mesh element has free edges (edges connected to one face only)\n
2837 # Return a list of special structures (borders).
2838 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2839 # @ingroup l1_measurements
2840 def GetFreeBorders(self):
2841 aFilterMgr = self.smeshpyD.CreateFilterManager()
2842 aPredicate = aFilterMgr.CreateFreeEdges()
2843 aPredicate.SetMesh(self.mesh)
2844 aBorders = aPredicate.GetBorders()
2845 aFilterMgr.UnRegister()
2848 ## Get minimum distance between two nodes, elements or distance to the origin
2849 # @param id1 first node/element id
2850 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2851 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2852 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2853 # @return minimum distance value
2854 # @sa GetMinDistance()
2855 # @ingroup l1_measurements
2856 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2857 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2858 return aMeasure.value
2860 ## Get measure structure specifying minimum distance data between two objects
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 Measure structure
2867 # @ingroup l1_measurements
2868 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2870 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2872 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2875 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2877 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2882 aMeasurements = self.smeshpyD.CreateMeasurements()
2883 aMeasure = aMeasurements.MinDistance(id1, id2)
2884 genObjUnRegister([aMeasurements,id1, id2])
2887 ## Get bounding box of the specified object(s)
2888 # @param objects single source object or list of source objects or list of nodes/elements IDs
2889 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2890 # @c False specifies that @a objects are nodes
2891 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2892 # @sa GetBoundingBox()
2893 # @ingroup l1_measurements
2894 def BoundingBox(self, objects=None, isElem=False):
2895 result = self.GetBoundingBox(objects, isElem)
2899 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2902 ## Get measure structure specifying bounding box data of the specified object(s)
2903 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2904 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2905 # @c False specifies that @a objects are nodes
2906 # @return Measure structure
2908 # @ingroup l1_measurements
2909 def GetBoundingBox(self, IDs=None, isElem=False):
2912 elif isinstance(IDs, tuple):
2914 if not isinstance(IDs, list):
2916 if len(IDs) > 0 and isinstance(IDs[0], int):
2919 unRegister = genObjUnRegister()
2921 if isinstance(o, Mesh):
2922 srclist.append(o.mesh)
2923 elif hasattr(o, "_narrow"):
2924 src = o._narrow(SMESH.SMESH_IDSource)
2925 if src: srclist.append(src)
2927 elif isinstance(o, list):
2929 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2931 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2932 unRegister.set( srclist[-1] )
2935 aMeasurements = self.smeshpyD.CreateMeasurements()
2936 unRegister.set( aMeasurements )
2937 aMeasure = aMeasurements.BoundingBox(srclist)
2940 # Mesh edition (SMESH_MeshEditor functionality):
2941 # ---------------------------------------------
2943 ## Remove the elements from the mesh by ids
2944 # @param IDsOfElements is a list of ids of elements to remove
2945 # @return True or False
2946 # @ingroup l2_modif_del
2947 def RemoveElements(self, IDsOfElements):
2948 return self.editor.RemoveElements(IDsOfElements)
2950 ## Remove nodes from mesh by ids
2951 # @param IDsOfNodes is a list of ids of nodes to remove
2952 # @return True or False
2953 # @ingroup l2_modif_del
2954 def RemoveNodes(self, IDsOfNodes):
2955 return self.editor.RemoveNodes(IDsOfNodes)
2957 ## Remove all orphan (free) nodes from mesh
2958 # @return number of the removed nodes
2959 # @ingroup l2_modif_del
2960 def RemoveOrphanNodes(self):
2961 return self.editor.RemoveOrphanNodes()
2963 ## Add a node to the mesh by coordinates
2964 # @return Id of the new node
2965 # @ingroup l2_modif_add
2966 def AddNode(self, x, y, z):
2967 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2968 if hasVars: self.mesh.SetParameters(Parameters)
2969 return self.editor.AddNode( x, y, z)
2971 ## Create a 0D element on a node with given number.
2972 # @param IDOfNode the ID of node for creation of the element.
2973 # @param DuplicateElements to add one more 0D element to a node or not
2974 # @return the Id of the new 0D element
2975 # @ingroup l2_modif_add
2976 def Add0DElement( self, IDOfNode, DuplicateElements=True ):
2977 return self.editor.Add0DElement( IDOfNode, DuplicateElements )
2979 ## Create 0D elements on all nodes of the given elements except those
2980 # nodes on which a 0D element already exists.
2981 # @param theObject an object on whose nodes 0D elements will be created.
2982 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2983 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2984 # @param theGroupName optional name of a group to add 0D elements created
2985 # and/or found on nodes of \a theObject.
2986 # @param DuplicateElements to add one more 0D element to a node or not
2987 # @return an object (a new group or a temporary SMESH_IDSource) holding
2988 # IDs of new and/or found 0D elements. IDs of 0D elements
2989 # can be retrieved from the returned object by calling GetIDs()
2990 # @ingroup l2_modif_add
2991 def Add0DElementsToAllNodes(self, theObject, theGroupName="", DuplicateElements=False):
2992 unRegister = genObjUnRegister()
2993 if isinstance( theObject, Mesh ):
2994 theObject = theObject.GetMesh()
2995 elif isinstance( theObject, list ):
2996 theObject = self.GetIDSource( theObject, SMESH.ALL )
2997 unRegister.set( theObject )
2998 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName, DuplicateElements )
3000 ## Create a ball element on a node with given ID.
3001 # @param IDOfNode the ID of node for creation of the element.
3002 # @param diameter the bal diameter.
3003 # @return the Id of the new ball element
3004 # @ingroup l2_modif_add
3005 def AddBall(self, IDOfNode, diameter):
3006 return self.editor.AddBall( IDOfNode, diameter )
3008 ## Create a linear or quadratic edge (this is determined
3009 # by the number of given nodes).
3010 # @param IDsOfNodes the list of node IDs for creation of the element.
3011 # The order of nodes in this list should correspond to the description
3012 # of MED. \n This description is located by the following link:
3013 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3014 # @return the Id of the new edge
3015 # @ingroup l2_modif_add
3016 def AddEdge(self, IDsOfNodes):
3017 return self.editor.AddEdge(IDsOfNodes)
3019 ## Create a linear or quadratic face (this is determined
3020 # by the number of given nodes).
3021 # @param IDsOfNodes the list of node IDs for creation of the element.
3022 # The order of nodes in this list should correspond to the description
3023 # of MED. \n This description is located by the following link:
3024 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3025 # @return the Id of the new face
3026 # @ingroup l2_modif_add
3027 def AddFace(self, IDsOfNodes):
3028 return self.editor.AddFace(IDsOfNodes)
3030 ## Add a polygonal face to the mesh by the list of node IDs
3031 # @param IdsOfNodes the list of node IDs for creation of the element.
3032 # @return the Id of the new face
3033 # @ingroup l2_modif_add
3034 def AddPolygonalFace(self, IdsOfNodes):
3035 return self.editor.AddPolygonalFace(IdsOfNodes)
3037 ## Add a quadratic polygonal face to the mesh by the list of node IDs
3038 # @param IdsOfNodes the list of node IDs for creation of the element;
3039 # corner nodes follow first.
3040 # @return the Id of the new face
3041 # @ingroup l2_modif_add
3042 def AddQuadPolygonalFace(self, IdsOfNodes):
3043 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
3045 ## Create both simple and quadratic volume (this is determined
3046 # by the number of given nodes).
3047 # @param IDsOfNodes the list of node IDs for creation of the element.
3048 # The order of nodes in this list should correspond to the description
3049 # of MED. \n This description is located by the following link:
3050 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3051 # @return the Id of the new volumic element
3052 # @ingroup l2_modif_add
3053 def AddVolume(self, IDsOfNodes):
3054 return self.editor.AddVolume(IDsOfNodes)
3056 ## Create a volume of many faces, giving nodes for each face.
3057 # @param IdsOfNodes the list of node IDs for volume creation face by face.
3058 # @param Quantities the list of integer values, Quantities[i]
3059 # gives the quantity of nodes in face number i.
3060 # @return the Id of the new volumic element
3061 # @ingroup l2_modif_add
3062 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
3063 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
3065 ## Create a volume of many faces, giving the IDs of the existing faces.
3066 # @param IdsOfFaces the list of face IDs for volume creation.
3068 # Note: The created volume will refer only to the nodes
3069 # of the given faces, not to the faces themselves.
3070 # @return the Id of the new volumic element
3071 # @ingroup l2_modif_add
3072 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
3073 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
3076 ## @brief Binds a node to a vertex
3077 # @param NodeID a node ID
3078 # @param Vertex a vertex or vertex ID
3079 # @return True if succeed else raises an exception
3080 # @ingroup l2_modif_add
3081 def SetNodeOnVertex(self, NodeID, Vertex):
3082 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
3083 VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
3087 self.editor.SetNodeOnVertex(NodeID, VertexID)
3088 except SALOME.SALOME_Exception as inst:
3089 raise ValueError(inst.details.text)
3093 ## @brief Stores the node position on an edge
3094 # @param NodeID a node ID
3095 # @param Edge an edge or edge ID
3096 # @param paramOnEdge a parameter on the edge where the node is located
3097 # @return True if succeed else raises an exception
3098 # @ingroup l2_modif_add
3099 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
3100 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
3101 EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
3105 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
3106 except SALOME.SALOME_Exception as inst:
3107 raise ValueError(inst.details.text)
3110 ## @brief Stores node position on a face
3111 # @param NodeID a node ID
3112 # @param Face a face or face ID
3113 # @param u U parameter on the face where the node is located
3114 # @param v V parameter on the face where the node is located
3115 # @return True if succeed else raises an exception
3116 # @ingroup l2_modif_add
3117 def SetNodeOnFace(self, NodeID, Face, u, v):
3118 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
3119 FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
3123 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
3124 except SALOME.SALOME_Exception as inst:
3125 raise ValueError(inst.details.text)
3128 ## @brief Binds a node to a solid
3129 # @param NodeID a node ID
3130 # @param Solid a solid or solid ID
3131 # @return True if succeed else raises an exception
3132 # @ingroup l2_modif_add
3133 def SetNodeInVolume(self, NodeID, Solid):
3134 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
3135 SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
3139 self.editor.SetNodeInVolume(NodeID, SolidID)
3140 except SALOME.SALOME_Exception as inst:
3141 raise ValueError(inst.details.text)
3144 ## @brief Bind an element to a shape
3145 # @param ElementID an element ID
3146 # @param Shape a shape or shape ID
3147 # @return True if succeed else raises an exception
3148 # @ingroup l2_modif_add
3149 def SetMeshElementOnShape(self, ElementID, Shape):
3150 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
3151 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3155 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
3156 except SALOME.SALOME_Exception as inst:
3157 raise ValueError(inst.details.text)
3161 ## Move the node with the given id
3162 # @param NodeID the id of the node
3163 # @param x a new X coordinate
3164 # @param y a new Y coordinate
3165 # @param z a new Z coordinate
3166 # @return True if succeed else False
3167 # @ingroup l2_modif_edit
3168 def MoveNode(self, NodeID, x, y, z):
3169 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3170 if hasVars: self.mesh.SetParameters(Parameters)
3171 return self.editor.MoveNode(NodeID, x, y, z)
3173 ## Find the node closest to a point and moves it to a point location
3174 # @param x the X coordinate of a point
3175 # @param y the Y coordinate of a point
3176 # @param z the Z coordinate of a point
3177 # @param NodeID if specified (>0), the node with this ID is moved,
3178 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
3179 # @return the ID of a node
3180 # @ingroup l2_modif_edit
3181 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3182 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3183 if hasVars: self.mesh.SetParameters(Parameters)
3184 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3186 ## Find the node closest to a point
3187 # @param x the X coordinate of a point
3188 # @param y the Y coordinate of a point
3189 # @param z the Z coordinate of a point
3190 # @return the ID of a node
3191 # @ingroup l1_meshinfo
3192 def FindNodeClosestTo(self, x, y, z):
3193 #preview = self.mesh.GetMeshEditPreviewer()
3194 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3195 return self.editor.FindNodeClosestTo(x, y, z)
3197 ## Find the elements where a point lays IN or ON
3198 # @param x the X coordinate of a point
3199 # @param y the Y coordinate of a point
3200 # @param z the Z coordinate of a point
3201 # @param elementType type of elements to find; either of
3202 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3203 # means elements of any type excluding nodes, discrete and 0D elements.
3204 # @param meshPart a part of mesh (group, sub-mesh) to search within
3205 # @return list of IDs of found elements
3206 # @ingroup l1_meshinfo
3207 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3209 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
3211 return self.editor.FindElementsByPoint(x, y, z, elementType)
3213 ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
3214 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
3215 # UNKNOWN state means that either mesh is wrong or the analysis fails.
3216 # @ingroup l1_meshinfo
3217 def GetPointState(self, x, y, z):
3218 return self.editor.GetPointState(x, y, z)
3220 ## Check if a 2D mesh is manifold
3221 # @ingroup l1_controls
3222 def IsManifold(self):
3223 return self.editor.IsManifold()
3225 ## Check if orientation of 2D elements is coherent
3226 # @ingroup l1_controls
3227 def IsCoherentOrientation2D(self):
3228 return self.editor.IsCoherentOrientation2D()
3230 ## Find the node closest to a point and moves it to a point location
3231 # @param x the X coordinate of a point
3232 # @param y the Y coordinate of a point
3233 # @param z the Z coordinate of a point
3234 # @return the ID of a moved node
3235 # @ingroup l2_modif_edit
3236 def MeshToPassThroughAPoint(self, x, y, z):
3237 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3239 ## Replace two neighbour triangles sharing Node1-Node2 link
3240 # with the triangles built on the same 4 nodes but having other common link.
3241 # @param NodeID1 the ID of the first node
3242 # @param NodeID2 the ID of the second node
3243 # @return false if proper faces were not found
3244 # @ingroup l2_modif_cutquadr
3245 def InverseDiag(self, NodeID1, NodeID2):
3246 return self.editor.InverseDiag(NodeID1, NodeID2)
3248 ## Replace two neighbour triangles sharing Node1-Node2 link
3249 # with a quadrangle built on the same 4 nodes.
3250 # @param NodeID1 the ID of the first node
3251 # @param NodeID2 the ID of the second node
3252 # @return false if proper faces were not found
3253 # @ingroup l2_modif_unitetri
3254 def DeleteDiag(self, NodeID1, NodeID2):
3255 return self.editor.DeleteDiag(NodeID1, NodeID2)
3257 ## Reorient elements by ids
3258 # @param IDsOfElements if undefined reorients all mesh elements
3259 # @return True if succeed else False
3260 # @ingroup l2_modif_changori
3261 def Reorient(self, IDsOfElements=None):
3262 if IDsOfElements == None:
3263 IDsOfElements = self.GetElementsId()
3264 return self.editor.Reorient(IDsOfElements)
3266 ## Reorient all elements of the object
3267 # @param theObject mesh, submesh or group
3268 # @return True if succeed else False
3269 # @ingroup l2_modif_changori
3270 def ReorientObject(self, theObject):
3271 if ( isinstance( theObject, Mesh )):
3272 theObject = theObject.GetMesh()
3273 return self.editor.ReorientObject(theObject)
3275 ## Reorient faces contained in \a the2DObject.
3276 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3277 # @param theDirection is a desired direction of normal of \a theFace.
3278 # It can be either a GEOM vector or a list of coordinates [x,y,z].
3279 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3280 # compared with theDirection. It can be either ID of face or a point
3281 # by which the face will be found. The point can be given as either
3282 # a GEOM vertex or a list of point coordinates.
3283 # @return number of reoriented faces
3284 # @ingroup l2_modif_changori
3285 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3286 unRegister = genObjUnRegister()
3288 if isinstance( the2DObject, Mesh ):
3289 the2DObject = the2DObject.GetMesh()
3290 if isinstance( the2DObject, list ):
3291 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3292 unRegister.set( the2DObject )
3293 # check theDirection
3294 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3295 theDirection = self.smeshpyD.GetDirStruct( theDirection )
3296 if isinstance( theDirection, list ):
3297 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
3298 # prepare theFace and thePoint
3299 theFace = theFaceOrPoint
3300 thePoint = PointStruct(0,0,0)
3301 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3302 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3304 if isinstance( theFaceOrPoint, list ):
3305 thePoint = PointStruct( *theFaceOrPoint )
3307 if isinstance( theFaceOrPoint, PointStruct ):
3308 thePoint = theFaceOrPoint
3310 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3312 ## Reorient faces according to adjacent volumes.
3313 # @param the2DObject is a mesh, sub-mesh, group or list of
3314 # either IDs of faces or face groups.
3315 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3316 # @param theOutsideNormal to orient faces to have their normals
3317 # pointing either \a outside or \a inside the adjacent volumes.
3318 # @return number of reoriented faces.
3319 # @ingroup l2_modif_changori
3320 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3321 unRegister = genObjUnRegister()
3323 if not isinstance( the2DObject, list ):
3324 the2DObject = [ the2DObject ]
3325 elif the2DObject and isinstance( the2DObject[0], int ):
3326 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3327 unRegister.set( the2DObject )
3328 the2DObject = [ the2DObject ]
3329 for i,obj2D in enumerate( the2DObject ):
3330 if isinstance( obj2D, Mesh ):
3331 the2DObject[i] = obj2D.GetMesh()
3332 if isinstance( obj2D, list ):
3333 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3334 unRegister.set( the2DObject[i] )
3336 if isinstance( the3DObject, Mesh ):
3337 the3DObject = the3DObject.GetMesh()
3338 if isinstance( the3DObject, list ):
3339 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3340 unRegister.set( the3DObject )
3341 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3343 ## Fuse the neighbouring triangles into quadrangles.
3344 # @param IDsOfElements The triangles to be fused.
3345 # @param theCriterion a numerical functor, in terms of enum SMESH.FunctorType, used to
3346 # applied to possible quadrangles to choose a neighbour to fuse with.
3347 # Type SMESH.FunctorType._items in the Python Console to see all items.
3348 # Note that not all items correspond to numerical functors.
3349 # @param MaxAngle is the maximum angle between element normals at which the fusion
3350 # is still performed; theMaxAngle is measured in radians.
3351 # Also it could be a name of variable which defines angle in degrees.
3352 # @return TRUE in case of success, FALSE otherwise.
3353 # @ingroup l2_modif_unitetri
3354 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3355 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3356 self.mesh.SetParameters(Parameters)
3357 if not IDsOfElements:
3358 IDsOfElements = self.GetElementsId()
3359 Functor = self.smeshpyD.GetFunctor(theCriterion)
3360 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3362 ## Fuse the neighbouring triangles of the object into quadrangles
3363 # @param theObject is mesh, submesh or group
3364 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType,
3365 # applied to possible quadrangles to choose a neighbour to fuse with.
3366 # Type SMESH.FunctorType._items in the Python Console to see all items.
3367 # Note that not all items correspond to numerical functors.
3368 # @param MaxAngle a max angle between element normals at which the fusion
3369 # is still performed; theMaxAngle is measured in radians.
3370 # @return TRUE in case of success, FALSE otherwise.
3371 # @ingroup l2_modif_unitetri
3372 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3373 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3374 self.mesh.SetParameters(Parameters)
3375 if isinstance( theObject, Mesh ):
3376 theObject = theObject.GetMesh()
3377 Functor = self.smeshpyD.GetFunctor(theCriterion)
3378 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3380 ## Split quadrangles into triangles.
3381 # @param IDsOfElements the faces to be splitted.
3382 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3383 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3384 # value, then quadrangles will be split by the smallest diagonal.
3385 # Type SMESH.FunctorType._items in the Python Console to see all items.
3386 # Note that not all items correspond to numerical functors.
3387 # @return TRUE in case of success, FALSE otherwise.
3388 # @ingroup l2_modif_cutquadr
3389 def QuadToTri (self, IDsOfElements, theCriterion = None):
3390 if IDsOfElements == []:
3391 IDsOfElements = self.GetElementsId()
3392 if theCriterion is None:
3393 theCriterion = FT_MaxElementLength2D
3394 Functor = self.smeshpyD.GetFunctor(theCriterion)
3395 return self.editor.QuadToTri(IDsOfElements, Functor)
3397 ## Split quadrangles into triangles.
3398 # @param theObject the object from which the list of elements is taken,
3399 # this is mesh, submesh or group
3400 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3401 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3402 # value, then quadrangles will be split by the smallest diagonal.
3403 # Type SMESH.FunctorType._items in the Python Console to see all items.
3404 # Note that not all items correspond to numerical functors.
3405 # @return TRUE in case of success, FALSE otherwise.
3406 # @ingroup l2_modif_cutquadr
3407 def QuadToTriObject (self, theObject, theCriterion = None):
3408 if ( isinstance( theObject, Mesh )):
3409 theObject = theObject.GetMesh()
3410 if theCriterion is None:
3411 theCriterion = FT_MaxElementLength2D
3412 Functor = self.smeshpyD.GetFunctor(theCriterion)
3413 return self.editor.QuadToTriObject(theObject, Functor)
3415 ## Split each of given quadrangles into 4 triangles. A node is added at the center of
3417 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3418 # group or a list of face IDs. By default all quadrangles are split
3419 # @ingroup l2_modif_cutquadr
3420 def QuadTo4Tri (self, theElements=[]):
3421 unRegister = genObjUnRegister()
3422 if isinstance( theElements, Mesh ):
3423 theElements = theElements.mesh
3424 elif not theElements:
3425 theElements = self.mesh
3426 elif isinstance( theElements, list ):
3427 theElements = self.GetIDSource( theElements, SMESH.FACE )
3428 unRegister.set( theElements )
3429 return self.editor.QuadTo4Tri( theElements )
3431 ## Split quadrangles into triangles.
3432 # @param IDsOfElements the faces to be splitted
3433 # @param Diag13 is used to choose a diagonal for splitting.
3434 # @return TRUE in case of success, FALSE otherwise.
3435 # @ingroup l2_modif_cutquadr
3436 def SplitQuad (self, IDsOfElements, Diag13):
3437 if IDsOfElements == []:
3438 IDsOfElements = self.GetElementsId()
3439 return self.editor.SplitQuad(IDsOfElements, Diag13)
3441 ## Split quadrangles into triangles.
3442 # @param theObject the object from which the list of elements is taken,
3443 # this is mesh, submesh or group
3444 # @param Diag13 is used to choose a diagonal for splitting.
3445 # @return TRUE in case of success, FALSE otherwise.
3446 # @ingroup l2_modif_cutquadr
3447 def SplitQuadObject (self, theObject, Diag13):
3448 if ( isinstance( theObject, Mesh )):
3449 theObject = theObject.GetMesh()
3450 return self.editor.SplitQuadObject(theObject, Diag13)
3452 ## Find a better splitting of the given quadrangle.
3453 # @param IDOfQuad the ID of the quadrangle to be splitted.
3454 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3455 # choose a diagonal for splitting.
3456 # Type SMESH.FunctorType._items in the Python Console to see all items.
3457 # Note that not all items correspond to numerical functors.
3458 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3459 # diagonal is better, 0 if error occurs.
3460 # @ingroup l2_modif_cutquadr
3461 def BestSplit (self, IDOfQuad, theCriterion):
3462 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3464 ## Split volumic elements into tetrahedrons
3465 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3466 # @param method flags passing splitting method:
3467 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3468 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3469 # @ingroup l2_modif_cutquadr
3470 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3471 unRegister = genObjUnRegister()
3472 if isinstance( elems, Mesh ):
3473 elems = elems.GetMesh()
3474 if ( isinstance( elems, list )):
3475 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3476 unRegister.set( elems )
3477 self.editor.SplitVolumesIntoTetra(elems, method)
3480 ## Split bi-quadratic elements into linear ones without creation of additional nodes:
3481 # - bi-quadratic triangle will be split into 3 linear quadrangles;
3482 # - bi-quadratic quadrangle will be split into 4 linear quadrangles;
3483 # - tri-quadratic hexahedron will be split into 8 linear hexahedra.
3484 # Quadratic elements of lower dimension adjacent to the split bi-quadratic element
3485 # will be split in order to keep the mesh conformal.
3486 # @param elems - elements to split: sub-meshes, groups, filters or element IDs;
3487 # if None (default), all bi-quadratic elements will be split
3488 # @ingroup l2_modif_cutquadr
3489 def SplitBiQuadraticIntoLinear(self, elems=None):
3490 unRegister = genObjUnRegister()
3491 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
3492 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
3493 unRegister.set( elems )
3495 elems = [ self.GetMesh() ]
3496 if isinstance( elems, Mesh ):
3497 elems = [ elems.GetMesh() ]
3498 if not isinstance( elems, list ):
3500 self.editor.SplitBiQuadraticIntoLinear( elems )
3502 ## Split hexahedra into prisms
3503 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3504 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3505 # gives a normal vector defining facets to split into triangles.
3506 # @a startHexPoint can be either a triple of coordinates or a vertex.
3507 # @param facetNormal a normal to a facet to split into triangles of a
3508 # hexahedron found by @a startHexPoint.
3509 # @a facetNormal can be either a triple of coordinates or an edge.
3510 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3511 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3512 # @param allDomains if @c False, only hexahedra adjacent to one closest
3513 # to @a startHexPoint are split, else @a startHexPoint
3514 # is used to find the facet to split in all domains present in @a elems.
3515 # @ingroup l2_modif_cutquadr
3516 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3517 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3519 unRegister = genObjUnRegister()
3520 if isinstance( elems, Mesh ):
3521 elems = elems.GetMesh()
3522 if ( isinstance( elems, list )):
3523 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3524 unRegister.set( elems )
3527 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3528 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3529 elif isinstance( startHexPoint, list ):
3530 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3533 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3534 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3535 elif isinstance( facetNormal, list ):
3536 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3539 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3541 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3543 ## Split quadrangle faces near triangular facets of volumes
3545 # @ingroup l2_modif_cutquadr
3546 def SplitQuadsNearTriangularFacets(self):
3547 faces_array = self.GetElementsByType(SMESH.FACE)
3548 for face_id in faces_array:
3549 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3550 quad_nodes = self.mesh.GetElemNodes(face_id)
3551 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3552 isVolumeFound = False
3553 for node1_elem in node1_elems:
3554 if not isVolumeFound:
3555 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3556 nb_nodes = self.GetElemNbNodes(node1_elem)
3557 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3558 volume_elem = node1_elem
3559 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3560 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3561 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3562 isVolumeFound = True
3563 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3564 self.SplitQuad([face_id], False) # diagonal 2-4
3565 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3566 isVolumeFound = True
3567 self.SplitQuad([face_id], True) # diagonal 1-3
3568 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3569 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3570 isVolumeFound = True
3571 self.SplitQuad([face_id], True) # diagonal 1-3
3573 ## @brief Splits hexahedrons into tetrahedrons.
3575 # This operation uses pattern mapping functionality for splitting.
3576 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3577 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3578 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3579 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3580 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3581 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3582 # @return TRUE in case of success, FALSE otherwise.
3583 # @ingroup l2_modif_cutquadr
3584 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3585 # Pattern: 5.---------.6
3590 # (0,0,1) 4.---------.7 * |
3597 # (0,0,0) 0.---------.3
3598 pattern_tetra = "!!! Nb of points: \n 8 \n\
3608 !!! Indices of points of 6 tetras: \n\
3616 pattern = self.smeshpyD.GetPattern()
3617 isDone = pattern.LoadFromFile(pattern_tetra)
3619 print('Pattern.LoadFromFile :', pattern.GetErrorCode())
3622 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3623 isDone = pattern.MakeMesh(self.mesh, False, False)
3624 if not isDone: print('Pattern.MakeMesh :', pattern.GetErrorCode())
3626 # split quafrangle faces near triangular facets of volumes
3627 self.SplitQuadsNearTriangularFacets()
3631 ## @brief Split hexahedrons into prisms.
3633 # Uses the pattern mapping functionality for splitting.
3634 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3635 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3636 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3637 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3638 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3639 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3640 # @return TRUE in case of success, FALSE otherwise.
3641 # @ingroup l2_modif_cutquadr
3642 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3643 # Pattern: 5.---------.6
3648 # (0,0,1) 4.---------.7 |
3655 # (0,0,0) 0.---------.3
3656 pattern_prism = "!!! Nb of points: \n 8 \n\
3666 !!! Indices of points of 2 prisms: \n\
3670 pattern = self.smeshpyD.GetPattern()
3671 isDone = pattern.LoadFromFile(pattern_prism)
3673 print('Pattern.LoadFromFile :', pattern.GetErrorCode())
3676 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3677 isDone = pattern.MakeMesh(self.mesh, False, False)
3678 if not isDone: print('Pattern.MakeMesh :', pattern.GetErrorCode())
3680 # Split quafrangle faces near triangular facets of volumes
3681 self.SplitQuadsNearTriangularFacets()
3686 # @param IDsOfElements the list if ids of elements to smooth
3687 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3688 # Note that nodes built on edges and boundary nodes are always fixed.
3689 # @param MaxNbOfIterations the maximum number of iterations
3690 # @param MaxAspectRatio varies in range [1.0, inf]
3691 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3692 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3693 # @return TRUE in case of success, FALSE otherwise.
3694 # @ingroup l2_modif_smooth
3695 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3696 MaxNbOfIterations, MaxAspectRatio, Method):
3697 if IDsOfElements == []:
3698 IDsOfElements = self.GetElementsId()
3699 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3700 self.mesh.SetParameters(Parameters)
3701 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3702 MaxNbOfIterations, MaxAspectRatio, Method)
3704 ## Smooth elements which belong to the given object
3705 # @param theObject the object to smooth
3706 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3707 # Note that nodes built on edges and boundary nodes are always fixed.
3708 # @param MaxNbOfIterations the maximum number of iterations
3709 # @param MaxAspectRatio varies in range [1.0, inf]
3710 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3711 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3712 # @return TRUE in case of success, FALSE otherwise.
3713 # @ingroup l2_modif_smooth
3714 def SmoothObject(self, theObject, IDsOfFixedNodes,
3715 MaxNbOfIterations, MaxAspectRatio, Method):
3716 if ( isinstance( theObject, Mesh )):
3717 theObject = theObject.GetMesh()
3718 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3719 MaxNbOfIterations, MaxAspectRatio, Method)
3721 ## Parametrically smooth the given elements
3722 # @param IDsOfElements the list if ids of elements to smooth
3723 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3724 # Note that nodes built on edges and boundary nodes are always fixed.
3725 # @param MaxNbOfIterations the maximum number of iterations
3726 # @param MaxAspectRatio varies in range [1.0, inf]
3727 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3728 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3729 # @return TRUE in case of success, FALSE otherwise.
3730 # @ingroup l2_modif_smooth
3731 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3732 MaxNbOfIterations, MaxAspectRatio, Method):
3733 if IDsOfElements == []:
3734 IDsOfElements = self.GetElementsId()
3735 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3736 self.mesh.SetParameters(Parameters)
3737 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3738 MaxNbOfIterations, MaxAspectRatio, Method)
3740 ## Parametrically smooth the elements which belong to the given object
3741 # @param theObject the object to smooth
3742 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3743 # Note that nodes built on edges and boundary nodes are always fixed.
3744 # @param MaxNbOfIterations the maximum number of iterations
3745 # @param MaxAspectRatio varies in range [1.0, inf]
3746 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3747 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3748 # @return TRUE in case of success, FALSE otherwise.
3749 # @ingroup l2_modif_smooth
3750 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3751 MaxNbOfIterations, MaxAspectRatio, Method):
3752 if ( isinstance( theObject, Mesh )):
3753 theObject = theObject.GetMesh()
3754 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3755 MaxNbOfIterations, MaxAspectRatio, Method)
3757 ## Convert the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3758 # them with quadratic with the same id.
3759 # @param theForce3d new node creation method:
3760 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3761 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3762 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3763 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3764 # @return SMESH.ComputeError which can hold a warning
3765 # @ingroup l2_modif_tofromqu
3766 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3767 if isinstance( theSubMesh, Mesh ):
3768 theSubMesh = theSubMesh.mesh
3770 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3773 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3775 self.editor.ConvertToQuadratic(theForce3d)
3776 error = self.editor.GetLastError()
3777 if error and error.comment:
3778 print(error.comment)
3781 ## Convert the mesh from quadratic to ordinary,
3782 # deletes old quadratic elements, \n replacing
3783 # them with ordinary mesh elements with the same id.
3784 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3785 # @ingroup l2_modif_tofromqu
3786 def ConvertFromQuadratic(self, theSubMesh=None):
3788 self.editor.ConvertFromQuadraticObject(theSubMesh)
3790 return self.editor.ConvertFromQuadratic()
3792 ## Create 2D mesh as skin on boundary faces of a 3D mesh
3793 # @return TRUE if operation has been completed successfully, FALSE otherwise
3794 # @ingroup l2_modif_add
3795 def Make2DMeshFrom3D(self):
3796 return self.editor.Make2DMeshFrom3D()
3798 ## Create missing boundary elements
3799 # @param elements - elements whose boundary is to be checked:
3800 # mesh, group, sub-mesh or list of elements
3801 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3802 # @param dimension - defines type of boundary elements to create, either of
3803 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3804 # SMESH.BND_1DFROM3D create mesh edges on all borders of free facets of 3D cells
3805 # @param groupName - a name of group to store created boundary elements in,
3806 # "" means not to create the group
3807 # @param meshName - a name of new mesh to store created boundary elements in,
3808 # "" means not to create the new mesh
3809 # @param toCopyElements - if true, the checked elements will be copied into
3810 # the new mesh else only boundary elements will be copied into the new mesh
3811 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3812 # boundary elements will be copied into the new mesh
3813 # @return tuple (mesh, group) where boundary elements were added to
3814 # @ingroup l2_modif_add
3815 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3816 toCopyElements=False, toCopyExistingBondary=False):
3817 unRegister = genObjUnRegister()
3818 if isinstance( elements, Mesh ):
3819 elements = elements.GetMesh()
3820 if ( isinstance( elements, list )):
3821 elemType = SMESH.ALL
3822 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3823 elements = self.editor.MakeIDSource(elements, elemType)
3824 unRegister.set( elements )
3825 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3826 toCopyElements,toCopyExistingBondary)
3827 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3831 # @brief Create missing boundary elements around either the whole mesh or
3832 # groups of elements
3833 # @param dimension - defines type of boundary elements to create, either of
3834 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3835 # @param groupName - a name of group to store all boundary elements in,
3836 # "" means not to create the group
3837 # @param meshName - a name of a new mesh, which is a copy of the initial
3838 # mesh + created boundary elements; "" means not to create the new mesh
3839 # @param toCopyAll - if true, the whole initial mesh will be copied into
3840 # the new mesh else only boundary elements will be copied into the new mesh
3841 # @param groups - groups of elements to make boundary around
3842 # @retval tuple( long, mesh, groups )
3843 # long - number of added boundary elements
3844 # mesh - the mesh where elements were added to
3845 # group - the group of boundary elements or None
3847 # @ingroup l2_modif_add
3848 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3849 toCopyAll=False, groups=[]):
3850 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3852 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3853 return nb, mesh, group
3855 ## Renumber mesh nodes (Obsolete, does nothing)
3856 # @ingroup l2_modif_renumber
3857 def RenumberNodes(self):
3858 self.editor.RenumberNodes()
3860 ## Renumber mesh elements (Obsole, does nothing)
3861 # @ingroup l2_modif_renumber
3862 def RenumberElements(self):
3863 self.editor.RenumberElements()
3865 ## Private method converting \a arg into a list of SMESH_IdSource's
3866 def _getIdSourceList(self, arg, idType, unRegister):
3867 if arg and isinstance( arg, list ):
3868 if isinstance( arg[0], int ):
3869 arg = self.GetIDSource( arg, idType )
3870 unRegister.set( arg )
3871 elif isinstance( arg[0], Mesh ):
3872 arg[0] = arg[0].GetMesh()
3873 elif isinstance( arg, Mesh ):
3875 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3879 ## Generate new elements by rotation of the given elements and nodes around the axis
3880 # @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3881 # @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3882 # @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3883 # @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3884 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3885 # which defines angle in degrees
3886 # @param NbOfSteps the number of steps
3887 # @param Tolerance tolerance
3888 # @param MakeGroups forces the generation of new groups from existing ones
3889 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3890 # of all steps, else - size of each step
3891 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3892 # @ingroup l2_modif_extrurev
3893 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3894 MakeGroups=False, TotalAngle=False):
3895 unRegister = genObjUnRegister()
3896 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3897 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3898 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3900 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3901 Axis = self.smeshpyD.GetAxisStruct( Axis )
3902 if isinstance( Axis, list ):
3903 Axis = SMESH.AxisStruct( *Axis )
3905 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3906 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3907 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3908 self.mesh.SetParameters(Parameters)
3909 if TotalAngle and NbOfSteps:
3910 AngleInRadians /= NbOfSteps
3911 return self.editor.RotationSweepObjects( nodes, edges, faces,
3912 Axis, AngleInRadians,
3913 NbOfSteps, Tolerance, MakeGroups)
3915 ## Generate new elements by rotation of the elements around the axis
3916 # @param IDsOfElements the list of ids of elements to sweep
3917 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3918 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3919 # @param NbOfSteps the number of steps
3920 # @param Tolerance tolerance
3921 # @param MakeGroups forces the generation of new groups from existing ones
3922 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3923 # of all steps, else - size of each step
3924 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3925 # @ingroup l2_modif_extrurev
3926 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3927 MakeGroups=False, TotalAngle=False):
3928 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3929 AngleInRadians, NbOfSteps, Tolerance,
3930 MakeGroups, TotalAngle)
3932 ## Generate new elements by rotation of the elements of object around the axis
3933 # @param theObject object which elements should be sweeped.
3934 # It can be a mesh, a sub mesh or a group.
3935 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3936 # @param AngleInRadians the angle of Rotation
3937 # @param NbOfSteps number of steps
3938 # @param Tolerance tolerance
3939 # @param MakeGroups forces the generation of new groups from existing ones
3940 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3941 # of all steps, else - size of each step
3942 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3943 # @ingroup l2_modif_extrurev
3944 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3945 MakeGroups=False, TotalAngle=False):
3946 return self.RotationSweepObjects( [], theObject, theObject, Axis,
3947 AngleInRadians, NbOfSteps, Tolerance,
3948 MakeGroups, TotalAngle )
3950 ## Generate new elements by rotation of the elements of object around the axis
3951 # @param theObject object which elements should be sweeped.
3952 # It can be a mesh, a sub mesh or a group.
3953 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3954 # @param AngleInRadians the angle of Rotation
3955 # @param NbOfSteps number of steps
3956 # @param Tolerance tolerance
3957 # @param MakeGroups forces the generation of new groups from existing ones
3958 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3959 # of all steps, else - size of each step
3960 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3961 # @ingroup l2_modif_extrurev
3962 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3963 MakeGroups=False, TotalAngle=False):
3964 return self.RotationSweepObjects([],theObject,[], Axis,
3965 AngleInRadians, NbOfSteps, Tolerance,
3966 MakeGroups, TotalAngle)
3968 ## Generate new elements by rotation of the elements of object around the axis
3969 # @param theObject object which elements should be sweeped.
3970 # It can be a mesh, a sub mesh or a group.
3971 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3972 # @param AngleInRadians the angle of Rotation
3973 # @param NbOfSteps number of steps
3974 # @param Tolerance tolerance
3975 # @param MakeGroups forces the generation of new groups from existing ones
3976 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3977 # of all steps, else - size of each step
3978 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3979 # @ingroup l2_modif_extrurev
3980 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3981 MakeGroups=False, TotalAngle=False):
3982 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3983 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3985 ## Generate new elements by extrusion of the given elements and nodes
3986 # @param nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3987 # @param edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3988 # @param faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3989 # @param StepVector vector or DirStruct or 3 vector components, defining
3990 # the direction and value of extrusion for one step (the total extrusion
3991 # length will be NbOfSteps * ||StepVector||)
3992 # @param NbOfSteps the number of steps
3993 # @param MakeGroups forces the generation of new groups from existing ones
3994 # @param scaleFactors optional scale factors to apply during extrusion
3995 # @param linearVariation if @c True, scaleFactors are spread over all @a scaleFactors,
3996 # else scaleFactors[i] is applied to nodes at the i-th extrusion step
3997 # @param basePoint optional scaling center; if not provided, a gravity center of
3998 # nodes and elements being extruded is used as the scaling center.
4000 # - a list of tree components of the point or
4003 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4004 # @ingroup l2_modif_extrurev
4005 # @ref tui_extrusion example
4006 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False,
4007 scaleFactors=[], linearVariation=False, basePoint=[] ):
4008 unRegister = genObjUnRegister()
4009 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
4010 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
4011 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
4013 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
4014 StepVector = self.smeshpyD.GetDirStruct(StepVector)
4015 if isinstance( StepVector, list ):
4016 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
4018 if isinstance( basePoint, int):
4019 xyz = self.GetNodeXYZ( basePoint )
4021 raise RuntimeError("Invalid node ID: %s" % basePoint)
4023 if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
4024 basePoint = self.geompyD.PointCoordinates( basePoint )
4026 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
4027 Parameters = StepVector.PS.parameters + var_separator + Parameters
4028 self.mesh.SetParameters(Parameters)
4030 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
4031 StepVector, NbOfSteps,
4032 scaleFactors, linearVariation, basePoint,
4036 ## Generate new elements by extrusion of the elements with given ids
4037 # @param IDsOfElements the list of ids of elements or nodes for extrusion
4038 # @param StepVector vector or DirStruct or 3 vector components, defining
4039 # the direction and value of extrusion for one step (the total extrusion
4040 # length will be NbOfSteps * ||StepVector||)
4041 # @param NbOfSteps the number of steps
4042 # @param MakeGroups forces the generation of new groups from existing ones
4043 # @param IsNodes is True if elements with given ids are nodes
4044 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4045 # @ingroup l2_modif_extrurev
4046 # @ref tui_extrusion example
4047 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
4049 if IsNodes: n = IDsOfElements
4050 else : e,f, = IDsOfElements,IDsOfElements
4051 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
4053 ## Generate new elements by extrusion along the normal to a discretized surface or wire
4054 # @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh.
4055 # Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
4056 # @param StepSize length of one extrusion step (the total extrusion
4057 # length will be \a NbOfSteps * \a StepSize ).
4058 # @param NbOfSteps number of extrusion steps.
4059 # @param ByAverageNormal if True each node is translated by \a StepSize
4060 # along the average of the normal vectors to the faces sharing the node;
4061 # else each node is translated along the same average normal till
4062 # intersection with the plane got by translation of the face sharing
4063 # the node along its own normal by \a StepSize.
4064 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
4065 # for every node of \a Elements.
4066 # @param MakeGroups forces generation of new groups from existing ones.
4067 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
4068 # is not yet implemented. This parameter is used if \a Elements contains
4069 # both faces and edges, i.e. \a Elements is a Mesh.
4070 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
4071 # empty list otherwise.
4072 # @ingroup l2_modif_extrurev
4073 # @ref tui_extrusion example
4074 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
4075 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
4076 unRegister = genObjUnRegister()
4077 if isinstance( Elements, Mesh ):
4078 Elements = [ Elements.GetMesh() ]
4079 if isinstance( Elements, list ):
4081 raise RuntimeError("Elements empty!")
4082 if isinstance( Elements[0], int ):
4083 Elements = self.GetIDSource( Elements, SMESH.ALL )
4084 unRegister.set( Elements )
4085 if not isinstance( Elements, list ):
4086 Elements = [ Elements ]
4087 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
4088 self.mesh.SetParameters(Parameters)
4089 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
4090 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
4092 ## Generate new elements by extrusion of the elements or nodes which belong to the object
4093 # @param theObject the object whose elements or nodes should be processed.
4094 # It can be a mesh, a sub-mesh or a group.
4095 # @param StepVector vector or DirStruct or 3 vector components, defining
4096 # the direction and value of extrusion for one step (the total extrusion
4097 # length will be NbOfSteps * ||StepVector||)
4098 # @param NbOfSteps the number of steps
4099 # @param MakeGroups forces the generation of new groups from existing ones
4100 # @param IsNodes is True if elements to extrude are nodes
4101 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4102 # @ingroup l2_modif_extrurev
4103 # @ref tui_extrusion example
4104 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
4106 if IsNodes: n = theObject
4107 else : e,f, = theObject,theObject
4108 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
4110 ## Generate new elements by extrusion of edges which belong to the object
4111 # @param theObject object whose 1D elements should be processed.
4112 # It can be a mesh, a sub-mesh or a group.
4113 # @param StepVector vector or DirStruct or 3 vector components, defining
4114 # the direction and value of extrusion for one step (the total extrusion
4115 # length will be NbOfSteps * ||StepVector||)
4116 # @param NbOfSteps the number of steps
4117 # @param MakeGroups to generate new groups from existing ones
4118 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4119 # @ingroup l2_modif_extrurev
4120 # @ref tui_extrusion example
4121 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
4122 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
4124 ## Generate new elements by extrusion of faces which belong to the object
4125 # @param theObject object whose 2D elements should be processed.
4126 # It can be a mesh, a sub-mesh or a group.
4127 # @param StepVector vector or DirStruct or 3 vector components, defining
4128 # the direction and value of extrusion for one step (the total extrusion
4129 # length will be NbOfSteps * ||StepVector||)
4130 # @param NbOfSteps the number of steps
4131 # @param MakeGroups forces the generation of new groups from existing ones
4132 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4133 # @ingroup l2_modif_extrurev
4134 # @ref tui_extrusion example
4135 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
4136 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
4138 ## Generate new elements by extrusion of the elements with given ids
4139 # @param IDsOfElements is ids of elements
4140 # @param StepVector vector or DirStruct or 3 vector components, defining
4141 # the direction and value of extrusion for one step (the total extrusion
4142 # length will be NbOfSteps * ||StepVector||)
4143 # @param NbOfSteps the number of steps
4144 # @param ExtrFlags sets flags for extrusion
4145 # @param SewTolerance uses for comparing locations of nodes if flag
4146 # EXTRUSION_FLAG_SEW is set
4147 # @param MakeGroups forces the generation of new groups from existing ones
4148 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4149 # @ingroup l2_modif_extrurev
4150 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
4151 ExtrFlags, SewTolerance, MakeGroups=False):
4152 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
4153 StepVector = self.smeshpyD.GetDirStruct(StepVector)
4154 if isinstance( StepVector, list ):
4155 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
4156 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
4157 ExtrFlags, SewTolerance, MakeGroups)
4159 ## Generate new elements by extrusion of the given elements and nodes along the path.
4160 # The path of extrusion must be a meshed edge.
4161 # @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
4162 # @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
4163 # @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
4164 # @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4165 # @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
4166 # contains not only path segments, else it can be None
4167 # @param NodeStart the first or the last node on the path. Defines the direction of extrusion
4168 # @param HasAngles allows the shape to be rotated around the path
4169 # to get the resulting mesh in a helical fashion
4170 # @param Angles list of angles
4171 # @param LinearVariation forces the computation of rotation angles as linear
4172 # variation of the given Angles along path steps
4173 # @param HasRefPoint allows using the reference point
4174 # @param RefPoint the point around which the shape is rotated (the mass center of the
4175 # shape by default). The User can specify any point as the Reference Point.
4176 # @param MakeGroups forces the generation of new groups from existing ones
4177 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
4178 # @ingroup l2_modif_extrurev
4179 # @ref tui_extrusion_along_path example
4180 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
4181 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
4182 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
4183 unRegister = genObjUnRegister()
4184 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
4185 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
4186 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
4188 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
4189 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4190 if isinstance( RefPoint, list ):
4191 if not RefPoint: RefPoint = [0,0,0]
4192 RefPoint = SMESH.PointStruct( *RefPoint )
4193 if isinstance( PathMesh, Mesh ):
4194 PathMesh = PathMesh.GetMesh()
4195 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4196 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4197 self.mesh.SetParameters(Parameters)
4198 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
4199 PathMesh, PathShape, NodeStart,
4200 HasAngles, Angles, LinearVariation,
4201 HasRefPoint, RefPoint, MakeGroups)
4203 ## Generate new elements by extrusion of the given elements
4204 # The path of extrusion must be a meshed edge.
4205 # @param Base mesh or group, or sub-mesh, or list of ids of elements for extrusion
4206 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4207 # @param NodeStart the start node from Path. Defines the direction of extrusion
4208 # @param HasAngles allows the shape to be rotated around the path
4209 # to get the resulting mesh in a helical fashion
4210 # @param Angles list of angles in radians
4211 # @param LinearVariation forces the computation of rotation angles as linear
4212 # variation of the given Angles along path steps
4213 # @param HasRefPoint allows using the reference point
4214 # @param RefPoint the point around which the elements are rotated (the mass
4215 # center of the elements by default).
4216 # The User can specify any point as the Reference Point.
4217 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
4218 # @param MakeGroups forces the generation of new groups from existing ones
4219 # @param ElemType type of elements for extrusion (if param Base is a mesh)
4220 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4221 # only SMESH::Extrusion_Error otherwise
4222 # @ingroup l2_modif_extrurev
4223 # @ref tui_extrusion_along_path example
4224 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
4225 HasAngles=False, Angles=[], LinearVariation=False,
4226 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
4227 ElemType=SMESH.FACE):
4229 if ElemType == SMESH.NODE: n = Base
4230 if ElemType == SMESH.EDGE: e = Base
4231 if ElemType == SMESH.FACE: f = Base
4232 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
4233 HasAngles, Angles, LinearVariation,
4234 HasRefPoint, RefPoint, MakeGroups)
4235 if MakeGroups: return gr,er
4238 ## Generate new elements by extrusion of the given elements
4239 # The path of extrusion must be a meshed edge.
4240 # @param IDsOfElements ids of elements
4241 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
4242 # @param PathShape shape(edge) defines the sub-mesh for the path
4243 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4244 # @param HasAngles allows the shape to be rotated around the path
4245 # to get the resulting mesh in a helical fashion
4246 # @param Angles list of angles in radians
4247 # @param HasRefPoint allows using the reference point
4248 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4249 # The User can specify any point as the Reference Point.
4250 # @param MakeGroups forces the generation of new groups from existing ones
4251 # @param LinearVariation forces the computation of rotation angles as linear
4252 # variation of the given Angles along path steps
4253 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4254 # only SMESH::Extrusion_Error otherwise
4255 # @ingroup l2_modif_extrurev
4256 # @ref tui_extrusion_along_path example
4257 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
4258 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4259 MakeGroups=False, LinearVariation=False):
4260 n,e,f = [],IDsOfElements,IDsOfElements
4261 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
4262 NodeStart, HasAngles, Angles,
4264 HasRefPoint, RefPoint, MakeGroups)
4265 if MakeGroups: return gr,er
4268 ## Generate new elements by extrusion of the elements which belong to the object
4269 # The path of extrusion must be a meshed edge.
4270 # @param theObject the object whose elements should be processed.
4271 # It can be a mesh, a sub-mesh or a group.
4272 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4273 # @param PathShape shape(edge) defines the sub-mesh for the path
4274 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4275 # @param HasAngles allows the shape to be rotated around the path
4276 # to get the resulting mesh in a helical fashion
4277 # @param Angles list of angles
4278 # @param HasRefPoint allows using the reference point
4279 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4280 # The User can specify any point as the Reference Point.
4281 # @param MakeGroups forces the generation of new groups from existing ones
4282 # @param LinearVariation forces the computation of rotation angles as linear
4283 # variation of the given Angles along path steps
4284 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4285 # only SMESH::Extrusion_Error otherwise
4286 # @ingroup l2_modif_extrurev
4287 # @ref tui_extrusion_along_path example
4288 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4289 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4290 MakeGroups=False, LinearVariation=False):
4291 n,e,f = [],theObject,theObject
4292 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4293 HasAngles, Angles, LinearVariation,
4294 HasRefPoint, RefPoint, MakeGroups)
4295 if MakeGroups: return gr,er
4298 ## Generate new elements by extrusion of mesh segments which belong to the object
4299 # The path of extrusion must be a meshed edge.
4300 # @param theObject the object whose 1D elements should be processed.
4301 # It can be a mesh, a sub-mesh or a group.
4302 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4303 # @param PathShape shape(edge) defines the sub-mesh for the path
4304 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4305 # @param HasAngles allows the shape to be rotated around the path
4306 # to get the resulting mesh in a helical fashion
4307 # @param Angles list of angles
4308 # @param HasRefPoint allows using the reference point
4309 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4310 # The User can specify any point as the Reference Point.
4311 # @param MakeGroups forces the generation of new groups from existing ones
4312 # @param LinearVariation forces the computation of rotation angles as linear
4313 # variation of the given Angles along path steps
4314 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4315 # only SMESH::Extrusion_Error otherwise
4316 # @ingroup l2_modif_extrurev
4317 # @ref tui_extrusion_along_path example
4318 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4319 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4320 MakeGroups=False, LinearVariation=False):
4321 n,e,f = [],theObject,[]
4322 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4323 HasAngles, Angles, LinearVariation,
4324 HasRefPoint, RefPoint, MakeGroups)
4325 if MakeGroups: return gr,er
4328 ## Generate new elements by extrusion of faces which belong to the object
4329 # The path of extrusion must be a meshed edge.
4330 # @param theObject the object whose 2D elements should be processed.
4331 # It can be a mesh, a sub-mesh or a group.
4332 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4333 # @param PathShape shape(edge) defines the sub-mesh for the path
4334 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4335 # @param HasAngles allows the shape to be rotated around the path
4336 # to get the resulting mesh in a helical fashion
4337 # @param Angles list of angles
4338 # @param HasRefPoint allows using the reference point
4339 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4340 # The User can specify any point as the Reference Point.
4341 # @param MakeGroups forces the generation of new groups from existing ones
4342 # @param LinearVariation forces the computation of rotation angles as linear
4343 # variation of the given Angles along path steps
4344 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4345 # only SMESH::Extrusion_Error otherwise
4346 # @ingroup l2_modif_extrurev
4347 # @ref tui_extrusion_along_path example
4348 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4349 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4350 MakeGroups=False, LinearVariation=False):
4351 n,e,f = [],[],theObject
4352 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4353 HasAngles, Angles, LinearVariation,
4354 HasRefPoint, RefPoint, MakeGroups)
4355 if MakeGroups: return gr,er
4358 ## Create a symmetrical copy of mesh elements
4359 # @param IDsOfElements list of elements ids
4360 # @param Mirror is AxisStruct or geom object(point, line, plane)
4361 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4362 # If the Mirror is a geom object this parameter is unnecessary
4363 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4364 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4365 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4366 # @ingroup l2_modif_trsf
4367 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4368 if IDsOfElements == []:
4369 IDsOfElements = self.GetElementsId()
4370 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4371 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4372 theMirrorType = Mirror._mirrorType
4374 self.mesh.SetParameters(Mirror.parameters)
4375 if Copy and MakeGroups:
4376 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4377 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4380 ## Create a new mesh by a symmetrical copy of mesh elements
4381 # @param IDsOfElements the list of elements ids
4382 # @param Mirror is AxisStruct or geom object (point, line, plane)
4383 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4384 # If the Mirror is a geom object this parameter is unnecessary
4385 # @param MakeGroups to generate new groups from existing ones
4386 # @param NewMeshName a name of the new mesh to create
4387 # @return instance of Mesh class
4388 # @ingroup l2_modif_trsf
4389 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4390 if IDsOfElements == []:
4391 IDsOfElements = self.GetElementsId()
4392 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4393 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4394 theMirrorType = Mirror._mirrorType
4396 self.mesh.SetParameters(Mirror.parameters)
4397 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4398 MakeGroups, NewMeshName)
4399 return Mesh(self.smeshpyD,self.geompyD,mesh)
4401 ## Create a symmetrical copy of the object
4402 # @param theObject mesh, submesh or group
4403 # @param Mirror AxisStruct or geom object (point, line, plane)
4404 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4405 # If the Mirror is a geom object this parameter is unnecessary
4406 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4407 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4408 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4409 # @ingroup l2_modif_trsf
4410 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4411 if ( isinstance( theObject, Mesh )):
4412 theObject = theObject.GetMesh()
4413 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4414 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4415 theMirrorType = Mirror._mirrorType
4417 self.mesh.SetParameters(Mirror.parameters)
4418 if Copy and MakeGroups:
4419 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4420 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4423 ## Create a new mesh by a symmetrical copy of the object
4424 # @param theObject mesh, submesh or group
4425 # @param Mirror AxisStruct or geom object (point, line, plane)
4426 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4427 # If the Mirror is a geom object this parameter is unnecessary
4428 # @param MakeGroups forces the generation of new groups from existing ones
4429 # @param NewMeshName the name of the new mesh to create
4430 # @return instance of Mesh class
4431 # @ingroup l2_modif_trsf
4432 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4433 if ( isinstance( theObject, Mesh )):
4434 theObject = theObject.GetMesh()
4435 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4436 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4437 theMirrorType = Mirror._mirrorType
4439 self.mesh.SetParameters(Mirror.parameters)
4440 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4441 MakeGroups, NewMeshName)
4442 return Mesh( self.smeshpyD,self.geompyD,mesh )
4444 ## Translate the elements
4445 # @param IDsOfElements list of elements ids
4446 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4447 # @param Copy allows copying the translated elements
4448 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4449 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4450 # @ingroup l2_modif_trsf
4451 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4452 if IDsOfElements == []:
4453 IDsOfElements = self.GetElementsId()
4454 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4455 Vector = self.smeshpyD.GetDirStruct(Vector)
4456 if isinstance( Vector, list ):
4457 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4458 self.mesh.SetParameters(Vector.PS.parameters)
4459 if Copy and MakeGroups:
4460 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4461 self.editor.Translate(IDsOfElements, Vector, Copy)
4464 ## Create a new mesh of translated elements
4465 # @param IDsOfElements list of elements ids
4466 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4467 # @param MakeGroups forces the generation of new groups from existing ones
4468 # @param NewMeshName the name of the newly created mesh
4469 # @return instance of Mesh class
4470 # @ingroup l2_modif_trsf
4471 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4472 if IDsOfElements == []:
4473 IDsOfElements = self.GetElementsId()
4474 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4475 Vector = self.smeshpyD.GetDirStruct(Vector)
4476 if isinstance( Vector, list ):
4477 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4478 self.mesh.SetParameters(Vector.PS.parameters)
4479 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4480 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4482 ## Translate the object
4483 # @param theObject the object to translate (mesh, submesh, or group)
4484 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4485 # @param Copy allows copying the translated elements
4486 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4487 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4488 # @ingroup l2_modif_trsf
4489 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4490 if ( isinstance( theObject, Mesh )):
4491 theObject = theObject.GetMesh()
4492 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4493 Vector = self.smeshpyD.GetDirStruct(Vector)
4494 if isinstance( Vector, list ):
4495 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4496 self.mesh.SetParameters(Vector.PS.parameters)
4497 if Copy and MakeGroups:
4498 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4499 self.editor.TranslateObject(theObject, Vector, Copy)
4502 ## Create a new mesh from the translated object
4503 # @param theObject the object to translate (mesh, submesh, or group)
4504 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4505 # @param MakeGroups forces the generation of new groups from existing ones
4506 # @param NewMeshName the name of the newly created mesh
4507 # @return instance of Mesh class
4508 # @ingroup l2_modif_trsf
4509 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4510 if isinstance( theObject, Mesh ):
4511 theObject = theObject.GetMesh()
4512 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4513 Vector = self.smeshpyD.GetDirStruct(Vector)
4514 if isinstance( Vector, list ):
4515 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4516 self.mesh.SetParameters(Vector.PS.parameters)
4517 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4518 return Mesh( self.smeshpyD, self.geompyD, mesh )
4523 # @param theObject - the object to translate (mesh, submesh, or group)
4524 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4525 # @param theScaleFact - list of 1-3 scale factors for axises
4526 # @param Copy - allows copying the translated elements
4527 # @param MakeGroups - forces the generation of new groups from existing
4529 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4530 # empty list otherwise
4531 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4532 unRegister = genObjUnRegister()
4533 if ( isinstance( theObject, Mesh )):
4534 theObject = theObject.GetMesh()
4535 if ( isinstance( theObject, list )):
4536 theObject = self.GetIDSource(theObject, SMESH.ALL)
4537 unRegister.set( theObject )
4538 if ( isinstance( thePoint, list )):
4539 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4540 if ( isinstance( theScaleFact, float )):
4541 theScaleFact = [theScaleFact]
4542 if ( isinstance( theScaleFact, int )):
4543 theScaleFact = [ float(theScaleFact)]
4545 self.mesh.SetParameters(thePoint.parameters)
4547 if Copy and MakeGroups:
4548 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4549 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4552 ## Create a new mesh from the translated object
4553 # @param theObject - the object to translate (mesh, submesh, or group)
4554 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4555 # @param theScaleFact - list of 1-3 scale factors for axises
4556 # @param MakeGroups - forces the generation of new groups from existing ones
4557 # @param NewMeshName - the name of the newly created mesh
4558 # @return instance of Mesh class
4559 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4560 unRegister = genObjUnRegister()
4561 if (isinstance(theObject, Mesh)):
4562 theObject = theObject.GetMesh()
4563 if ( isinstance( theObject, list )):
4564 theObject = self.GetIDSource(theObject,SMESH.ALL)
4565 unRegister.set( theObject )
4566 if ( isinstance( thePoint, list )):
4567 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4568 if ( isinstance( theScaleFact, float )):
4569 theScaleFact = [theScaleFact]
4570 if ( isinstance( theScaleFact, int )):
4571 theScaleFact = [ float(theScaleFact)]
4573 self.mesh.SetParameters(thePoint.parameters)
4574 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4575 MakeGroups, NewMeshName)
4576 return Mesh( self.smeshpyD, self.geompyD, mesh )
4580 ## Rotate the elements
4581 # @param IDsOfElements list of elements ids
4582 # @param Axis the axis of rotation (AxisStruct or geom line)
4583 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4584 # @param Copy allows copying the rotated elements
4585 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4586 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4587 # @ingroup l2_modif_trsf
4588 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4589 if IDsOfElements == []:
4590 IDsOfElements = self.GetElementsId()
4591 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4592 Axis = self.smeshpyD.GetAxisStruct(Axis)
4593 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4594 Parameters = Axis.parameters + var_separator + Parameters
4595 self.mesh.SetParameters(Parameters)
4596 if Copy and MakeGroups:
4597 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4598 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4601 ## Create a new mesh of rotated elements
4602 # @param IDsOfElements list of element ids
4603 # @param Axis the axis of rotation (AxisStruct or geom line)
4604 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4605 # @param MakeGroups forces the generation of new groups from existing ones
4606 # @param NewMeshName the name of the newly created mesh
4607 # @return instance of Mesh class
4608 # @ingroup l2_modif_trsf
4609 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4610 if IDsOfElements == []:
4611 IDsOfElements = self.GetElementsId()
4612 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4613 Axis = self.smeshpyD.GetAxisStruct(Axis)
4614 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4615 Parameters = Axis.parameters + var_separator + Parameters
4616 self.mesh.SetParameters(Parameters)
4617 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4618 MakeGroups, NewMeshName)
4619 return Mesh( self.smeshpyD, self.geompyD, mesh )
4621 ## Rotate the object
4622 # @param theObject the object to rotate( mesh, submesh, or group)
4623 # @param Axis the axis of rotation (AxisStruct or geom line)
4624 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4625 # @param Copy allows copying the rotated elements
4626 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4627 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4628 # @ingroup l2_modif_trsf
4629 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4630 if (isinstance(theObject, Mesh)):
4631 theObject = theObject.GetMesh()
4632 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4633 Axis = self.smeshpyD.GetAxisStruct(Axis)
4634 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4635 Parameters = Axis.parameters + ":" + Parameters
4636 self.mesh.SetParameters(Parameters)
4637 if Copy and MakeGroups:
4638 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4639 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4642 ## Create a new mesh from the rotated object
4643 # @param theObject the object to rotate (mesh, submesh, or group)
4644 # @param Axis the axis of rotation (AxisStruct or geom line)
4645 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4646 # @param MakeGroups forces the generation of new groups from existing ones
4647 # @param NewMeshName the name of the newly created mesh
4648 # @return instance of Mesh class
4649 # @ingroup l2_modif_trsf
4650 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4651 if (isinstance( theObject, Mesh )):
4652 theObject = theObject.GetMesh()
4653 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4654 Axis = self.smeshpyD.GetAxisStruct(Axis)
4655 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4656 Parameters = Axis.parameters + ":" + Parameters
4657 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4658 MakeGroups, NewMeshName)
4659 self.mesh.SetParameters(Parameters)
4660 return Mesh( self.smeshpyD, self.geompyD, mesh )
4662 ## Find groups of adjacent nodes within Tolerance.
4663 # @param Tolerance the value of tolerance
4664 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4665 # corner and medium nodes in separate groups thus preventing
4666 # their further merge.
4667 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4668 # @ingroup l2_modif_trsf
4669 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
4670 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
4672 ## Find groups of ajacent nodes within Tolerance.
4673 # @param Tolerance the value of tolerance
4674 # @param SubMeshOrGroup SubMesh, Group or Filter
4675 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
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 FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
4682 exceptNodes=[], SeparateCornerAndMediumNodes=False):
4683 unRegister = genObjUnRegister()
4684 if (isinstance( SubMeshOrGroup, Mesh )):
4685 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4686 if not isinstance( exceptNodes, list ):
4687 exceptNodes = [ exceptNodes ]
4688 if exceptNodes and isinstance( exceptNodes[0], int ):
4689 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
4690 unRegister.set( exceptNodes )
4691 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
4692 exceptNodes, SeparateCornerAndMediumNodes)
4695 # @param GroupsOfNodes a list of groups of nodes IDs for merging
4696 # (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
4697 # by nodes 1 and 25 correspondingly in all elements and groups
4698 # @param NodesToKeep nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
4699 # If @a NodesToKeep does not include a node to keep for some group to merge,
4700 # then the first node in the group is kept.
4701 # @param AvoidMakingHoles prevent merging nodes which cause removal of elements becoming
4703 # @ingroup l2_modif_trsf
4704 def MergeNodes (self, GroupsOfNodes, NodesToKeep=[], AvoidMakingHoles=False):
4705 # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
4706 self.editor.MergeNodes( GroupsOfNodes, NodesToKeep, AvoidMakingHoles )
4708 ## Find the elements built on the same nodes.
4709 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4710 # @return the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
4711 # @ingroup l2_modif_trsf
4712 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4713 if not MeshOrSubMeshOrGroup:
4714 MeshOrSubMeshOrGroup=self.mesh
4715 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4716 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4717 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4719 ## Merge elements in each given group.
4720 # @param GroupsOfElementsID a list of groups of elements IDs for merging
4721 # (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
4722 # replaced by elements 1 and 25 in all groups)
4723 # @ingroup l2_modif_trsf
4724 def MergeElements(self, GroupsOfElementsID):
4725 self.editor.MergeElements(GroupsOfElementsID)
4727 ## Leave one element and remove all other elements built on the same nodes.
4728 # @ingroup l2_modif_trsf
4729 def MergeEqualElements(self):
4730 self.editor.MergeEqualElements()
4732 ## Returns all or only closed free borders
4733 # @return list of SMESH.FreeBorder's
4734 # @ingroup l2_modif_trsf
4735 def FindFreeBorders(self, ClosedOnly=True):
4736 return self.editor.FindFreeBorders( ClosedOnly )
4738 ## Fill with 2D elements a hole defined by a SMESH.FreeBorder.
4739 # @param FreeBorder either a SMESH.FreeBorder or a list on node IDs. These nodes
4740 # must describe all sequential nodes of the hole border. The first and the last
4741 # nodes must be the same. Use FindFreeBorders() to get nodes of holes.
4742 # @ingroup l2_modif_trsf
4743 def FillHole(self, holeNodes):
4744 if holeNodes and isinstance( holeNodes, list ) and isinstance( holeNodes[0], int ):
4745 holeNodes = SMESH.FreeBorder(nodeIDs=holeNodes)
4746 if not isinstance( holeNodes, SMESH.FreeBorder ):
4747 raise TypeError("holeNodes must be either SMESH.FreeBorder or list of integer and not %s" % holeNodes)
4748 self.editor.FillHole( holeNodes )
4750 ## Return groups of FreeBorder's coincident within the given tolerance.
4751 # @param tolerance the tolerance. If the tolerance <= 0.0 then one tenth of an average
4752 # size of elements adjacent to free borders being compared is used.
4753 # @return SMESH.CoincidentFreeBorders structure
4754 # @ingroup l2_modif_trsf
4755 def FindCoincidentFreeBorders (self, tolerance=0.):
4756 return self.editor.FindCoincidentFreeBorders( tolerance )
4758 ## Sew FreeBorder's of each group
4759 # @param freeBorders either a SMESH.CoincidentFreeBorders structure or a list of lists
4760 # where each enclosed list contains node IDs of a group of coincident free
4761 # borders such that each consequent triple of IDs within a group describes
4762 # a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
4763 # last node of a border.
4764 # For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
4765 # groups of coincident free borders, each group including two borders.
4766 # @param createPolygons if @c True faces adjacent to free borders are converted to
4767 # polygons if a node of opposite border falls on a face edge, else such
4768 # faces are split into several ones.
4769 # @param createPolyhedra if @c True volumes adjacent to free borders are converted to
4770 # polyhedra if a node of opposite border falls on a volume edge, else such
4771 # volumes, if any, remain intact and the mesh becomes non-conformal.
4772 # @return a number of successfully sewed groups
4773 # @ingroup l2_modif_trsf
4774 def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
4775 if freeBorders and isinstance( freeBorders, list ):
4776 # construct SMESH.CoincidentFreeBorders
4777 if isinstance( freeBorders[0], int ):
4778 freeBorders = [freeBorders]
4780 coincidentGroups = []
4781 for nodeList in freeBorders:
4782 if not nodeList or len( nodeList ) % 3:
4783 raise ValueError("Wrong number of nodes in this group: %s" % nodeList)
4786 group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
4787 borders.append( SMESH.FreeBorder( nodeList[:3] ))
4788 nodeList = nodeList[3:]
4790 coincidentGroups.append( group )
4792 freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
4794 return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
4797 # @return SMESH::Sew_Error
4798 # @ingroup l2_modif_trsf
4799 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4800 FirstNodeID2, SecondNodeID2, LastNodeID2,
4801 CreatePolygons, CreatePolyedrs):
4802 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4803 FirstNodeID2, SecondNodeID2, LastNodeID2,
4804 CreatePolygons, CreatePolyedrs)
4806 ## Sew conform free borders
4807 # @return SMESH::Sew_Error
4808 # @ingroup l2_modif_trsf
4809 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4810 FirstNodeID2, SecondNodeID2):
4811 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4812 FirstNodeID2, SecondNodeID2)
4814 ## Sew border to side
4815 # @return SMESH::Sew_Error
4816 # @ingroup l2_modif_trsf
4817 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4818 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4819 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4820 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4822 ## Sew two sides of a mesh. The nodes belonging to Side1 are
4823 # merged with the nodes of elements of Side2.
4824 # The number of elements in theSide1 and in theSide2 must be
4825 # equal and they should have similar nodal connectivity.
4826 # The nodes to merge should belong to side borders and
4827 # the first node should be linked to the second.
4828 # @return SMESH::Sew_Error
4829 # @ingroup l2_modif_trsf
4830 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4831 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4832 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4833 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4834 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4835 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4837 ## Set new nodes for the given element.
4838 # @param ide the element id
4839 # @param newIDs nodes ids
4840 # @return If the number of nodes does not correspond to the type of element - return false
4841 # @ingroup l2_modif_edit
4842 def ChangeElemNodes(self, ide, newIDs):
4843 return self.editor.ChangeElemNodes(ide, newIDs)
4845 ## If during the last operation of MeshEditor some nodes were
4846 # created, this method return the list of their IDs, \n
4847 # if new nodes were not created - return empty list
4848 # @return the list of integer values (can be empty)
4849 # @ingroup l2_modif_add
4850 def GetLastCreatedNodes(self):
4851 return self.editor.GetLastCreatedNodes()
4853 ## If during the last operation of MeshEditor some elements were
4854 # created this method return the list of their IDs, \n
4855 # if new elements were not created - return empty list
4856 # @return the list of integer values (can be empty)
4857 # @ingroup l2_modif_add
4858 def GetLastCreatedElems(self):
4859 return self.editor.GetLastCreatedElems()
4861 ## Forget what nodes and elements were created by the last mesh edition operation
4862 # @ingroup l2_modif_add
4863 def ClearLastCreated(self):
4864 self.editor.ClearLastCreated()
4866 ## Create duplicates of given elements, i.e. create new elements based on the
4867 # same nodes as the given ones.
4868 # @param theElements - container of elements to duplicate. It can be a Mesh,
4869 # sub-mesh, group, filter or a list of element IDs. If \a theElements is
4870 # a Mesh, elements of highest dimension are duplicated
4871 # @param theGroupName - a name of group to contain the generated elements.
4872 # If a group with such a name already exists, the new elements
4873 # are added to the existng group, else a new group is created.
4874 # If \a theGroupName is empty, new elements are not added
4876 # @return a group where the new elements are added. None if theGroupName == "".
4877 # @ingroup l2_modif_duplicat
4878 def DoubleElements(self, theElements, theGroupName=""):
4879 unRegister = genObjUnRegister()
4880 if isinstance( theElements, Mesh ):
4881 theElements = theElements.mesh
4882 elif isinstance( theElements, list ):
4883 theElements = self.GetIDSource( theElements, SMESH.ALL )
4884 unRegister.set( theElements )
4885 return self.editor.DoubleElements(theElements, theGroupName)
4887 ## Create a hole in a mesh by doubling the nodes of some particular elements
4888 # @param theNodes identifiers of nodes to be doubled
4889 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4890 # nodes. If list of element identifiers is empty then nodes are doubled but
4891 # they not assigned to elements
4892 # @return TRUE if operation has been completed successfully, FALSE otherwise
4893 # @ingroup l2_modif_duplicat
4894 def DoubleNodes(self, theNodes, theModifiedElems):
4895 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4897 ## Create a hole in a mesh by doubling the nodes of some particular elements
4898 # This method provided for convenience works as DoubleNodes() described above.
4899 # @param theNodeId identifiers of node to be doubled
4900 # @param theModifiedElems identifiers of elements to be updated
4901 # @return TRUE if operation has been completed successfully, FALSE otherwise
4902 # @ingroup l2_modif_duplicat
4903 def DoubleNode(self, theNodeId, theModifiedElems):
4904 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4906 ## Create a hole in a mesh by doubling the nodes of some particular elements
4907 # This method provided for convenience works as DoubleNodes() described above.
4908 # @param theNodes group of nodes to be doubled
4909 # @param theModifiedElems group of elements to be updated.
4910 # @param theMakeGroup forces the generation of a group containing new nodes.
4911 # @return TRUE or a created group if operation has been completed successfully,
4912 # FALSE or None otherwise
4913 # @ingroup l2_modif_duplicat
4914 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4916 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4917 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4919 ## Create a hole in a mesh by doubling the nodes of some particular elements
4920 # This method provided for convenience works as DoubleNodes() described above.
4921 # @param theNodes list of groups of nodes to be doubled
4922 # @param theModifiedElems list of groups of elements to be updated.
4923 # @param theMakeGroup forces the generation of a group containing new nodes.
4924 # @return TRUE if operation has been completed successfully, FALSE otherwise
4925 # @ingroup l2_modif_duplicat
4926 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4928 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4929 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4931 ## Create a hole in a mesh by doubling the nodes of some particular elements
4932 # @param theElems - the list of elements (edges or faces) to be replicated
4933 # The nodes for duplication could be found from these elements
4934 # @param theNodesNot - list of nodes to NOT replicate
4935 # @param theAffectedElems - the list of elements (cells and edges) to which the
4936 # replicated nodes should be associated to.
4937 # @return TRUE if operation has been completed successfully, FALSE otherwise
4938 # @ingroup l2_modif_duplicat
4939 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4940 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4942 ## Create a hole in a mesh by doubling the nodes of some particular elements
4943 # @param theElems - the list of elements (edges or faces) to be replicated
4944 # The nodes for duplication could be found from these elements
4945 # @param theNodesNot - list of nodes to NOT replicate
4946 # @param theShape - shape to detect affected elements (element which geometric center
4947 # located on or inside shape).
4948 # The replicated nodes should be associated to affected elements.
4949 # @return TRUE if operation has been completed successfully, FALSE otherwise
4950 # @ingroup l2_modif_duplicat
4951 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4952 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4954 ## Create a hole in a mesh by doubling the nodes of some particular elements
4955 # This method provided for convenience works as DoubleNodes() described above.
4956 # @param theElems - group of of elements (edges or faces) to be replicated
4957 # @param theNodesNot - group of nodes not to replicated
4958 # @param theAffectedElems - group of elements to which the replicated nodes
4959 # should be associated to.
4960 # @param theMakeGroup forces the generation of a group containing new elements.
4961 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4962 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4963 # FALSE or None otherwise
4964 # @ingroup l2_modif_duplicat
4965 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4966 theMakeGroup=False, theMakeNodeGroup=False):
4967 if theMakeGroup or theMakeNodeGroup:
4968 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4970 theMakeGroup, theMakeNodeGroup)
4971 if theMakeGroup and theMakeNodeGroup:
4974 return twoGroups[ int(theMakeNodeGroup) ]
4975 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4977 ## Create a hole in a mesh by doubling the nodes of some particular elements
4978 # This method provided for convenience works as DoubleNodes() described above.
4979 # @param theElems - group of of elements (edges or faces) to be replicated
4980 # @param theNodesNot - group of nodes not to replicated
4981 # @param theShape - shape to detect affected elements (element which geometric center
4982 # located on or inside shape).
4983 # The replicated nodes should be associated to affected elements.
4984 # @ingroup l2_modif_duplicat
4985 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4986 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4988 ## Create a hole in a mesh by doubling the nodes of some particular elements
4989 # This method provided for convenience works as DoubleNodes() described above.
4990 # @param theElems - list of groups of elements (edges or faces) to be replicated
4991 # @param theNodesNot - list of groups of nodes not to replicated
4992 # @param theAffectedElems - group of elements to which the replicated nodes
4993 # should be associated to.
4994 # @param theMakeGroup forces the generation of a group containing new elements.
4995 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4996 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4997 # FALSE or None otherwise
4998 # @ingroup l2_modif_duplicat
4999 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
5000 theMakeGroup=False, theMakeNodeGroup=False):
5001 if theMakeGroup or theMakeNodeGroup:
5002 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
5004 theMakeGroup, theMakeNodeGroup)
5005 if theMakeGroup and theMakeNodeGroup:
5008 return twoGroups[ int(theMakeNodeGroup) ]
5009 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
5011 ## Create a hole in a mesh by doubling the nodes of some particular elements
5012 # This method provided for convenience works as DoubleNodes() described above.
5013 # @param theElems - list of groups of elements (edges or faces) to be replicated
5014 # @param theNodesNot - list of groups of nodes not to replicated
5015 # @param theShape - shape to detect affected elements (element which geometric center
5016 # located on or inside shape).
5017 # The replicated nodes should be associated to affected elements.
5018 # @return TRUE if operation has been completed successfully, FALSE otherwise
5019 # @ingroup l2_modif_duplicat
5020 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
5021 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
5023 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
5024 # This method is the first step of DoubleNodeElemGroupsInRegion.
5025 # @param theElems - list of groups of nodes or 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 groups of affected elements in order: volumes, faces, edges
5031 # @ingroup l2_modif_duplicat
5032 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
5033 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
5035 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
5036 # The list of groups must describe a partition of the mesh volumes.
5037 # The nodes of the internal faces at the boundaries of the groups are doubled.
5038 # In option, the internal faces are replaced by flat elements.
5039 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
5040 # @param theDomains - list of groups of volumes
5041 # @param createJointElems - if TRUE, create the elements
5042 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
5043 # the boundary between \a theDomains and the rest mesh
5044 # @return TRUE if operation has been completed successfully, FALSE otherwise
5045 # @ingroup l2_modif_duplicat
5046 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
5047 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
5049 ## Double nodes on some external faces and create flat elements.
5050 # Flat elements are mainly used by some types of mechanic calculations.
5052 # Each group of the list must be constituted of faces.
5053 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
5054 # @param theGroupsOfFaces - list of groups of faces
5055 # @return TRUE if operation has been completed successfully, FALSE otherwise
5056 # @ingroup l2_modif_duplicat
5057 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
5058 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
5060 ## identify all the elements around a geom shape, get the faces delimiting the hole
5062 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
5063 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
5065 ## Create a polyline consisting of 1D mesh elements each lying on a 2D element of
5066 # the initial mesh. Positions of new nodes are found by cutting the mesh by the
5067 # plane passing through pairs of points specified by each PolySegment structure.
5068 # If there are several paths connecting a pair of points, the shortest path is
5069 # selected by the module. Position of the cutting plane is defined by the two
5070 # points and an optional vector lying on the plane specified by a PolySegment.
5071 # By default the vector is defined by Mesh module as following. A middle point
5072 # of the two given points is computed. The middle point is projected to the mesh.
5073 # The vector goes from the middle point to the projection point. In case of planar
5074 # mesh, the vector is normal to the mesh.
5075 # @param segments - PolySegment's defining positions of cutting planes.
5076 # Return the used vector which goes from the middle point to its projection.
5077 # @param groupName - optional name of a group where created mesh segments will
5079 # @ingroup l2_modif_duplicat
5080 def MakePolyLine(self, segments, groupName='', isPreview=False ):
5081 editor = self.editor
5083 editor = self.mesh.GetMeshEditPreviewer()
5084 segmentsRes = editor.MakePolyLine( segments, groupName )
5085 for i, seg in enumerate( segmentsRes ):
5086 segments[i].vector = seg.vector
5088 return editor.GetPreviewData()
5091 ## Return a cached numerical functor by its type.
5092 # @param theCriterion functor type - an item of SMESH.FunctorType enumeration.
5093 # Type SMESH.FunctorType._items in the Python Console to see all items.
5094 # Note that not all items correspond to numerical functors.
5095 # @return SMESH_NumericalFunctor. The functor is already initialized
5097 # @ingroup l1_measurements
5098 def GetFunctor(self, funcType ):
5099 fn = self.functors[ funcType._v ]
5101 fn = self.smeshpyD.GetFunctor(funcType)
5102 fn.SetMesh(self.mesh)
5103 self.functors[ EnumToLong(funcType) ] = fn
5106 ## Return value of a functor for a given element
5107 # @param funcType an item of SMESH.FunctorType enum
5108 # Type "SMESH.FunctorType._items" in the Python Console to see all items.
5109 # @param elemId element or node ID
5110 # @param isElem @a elemId is ID of element or node
5111 # @return the functor value or zero in case of invalid arguments
5112 # @ingroup l1_measurements
5113 def FunctorValue(self, funcType, elemId, isElem=True):
5114 fn = self.GetFunctor( funcType )
5115 if fn.GetElementType() == self.GetElementType(elemId, isElem):
5116 val = fn.GetValue(elemId)
5121 ## Get length of 1D element or sum of lengths of all 1D mesh elements
5122 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
5123 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
5124 # @ingroup l1_measurements
5125 def GetLength(self, elemId=None):
5128 length = self.smeshpyD.GetLength(self)
5130 length = self.FunctorValue(SMESH.FT_Length, elemId)
5133 ## Get area of 2D element or sum of areas of all 2D mesh elements
5134 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
5135 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
5136 # @ingroup l1_measurements
5137 def GetArea(self, elemId=None):
5140 area = self.smeshpyD.GetArea(self)
5142 area = self.FunctorValue(SMESH.FT_Area, elemId)
5145 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
5146 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
5147 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
5148 # @ingroup l1_measurements
5149 def GetVolume(self, elemId=None):
5152 volume = self.smeshpyD.GetVolume(self)
5154 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
5157 ## Get maximum element length.
5158 # @param elemId mesh element ID
5159 # @return element's maximum length value
5160 # @ingroup l1_measurements
5161 def GetMaxElementLength(self, elemId):
5162 if self.GetElementType(elemId, True) == SMESH.VOLUME:
5163 ftype = SMESH.FT_MaxElementLength3D
5165 ftype = SMESH.FT_MaxElementLength2D
5166 return self.FunctorValue(ftype, elemId)
5168 ## Get aspect ratio of 2D or 3D element.
5169 # @param elemId mesh element ID
5170 # @return element's aspect ratio value
5171 # @ingroup l1_measurements
5172 def GetAspectRatio(self, elemId):
5173 if self.GetElementType(elemId, True) == SMESH.VOLUME:
5174 ftype = SMESH.FT_AspectRatio3D
5176 ftype = SMESH.FT_AspectRatio
5177 return self.FunctorValue(ftype, elemId)
5179 ## Get warping angle of 2D element.
5180 # @param elemId mesh element ID
5181 # @return element's warping angle value
5182 # @ingroup l1_measurements
5183 def GetWarping(self, elemId):
5184 return self.FunctorValue(SMESH.FT_Warping, elemId)
5186 ## Get minimum angle of 2D element.
5187 # @param elemId mesh element ID
5188 # @return element's minimum angle value
5189 # @ingroup l1_measurements
5190 def GetMinimumAngle(self, elemId):
5191 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
5193 ## Get taper of 2D element.
5194 # @param elemId mesh element ID
5195 # @return element's taper value
5196 # @ingroup l1_measurements
5197 def GetTaper(self, elemId):
5198 return self.FunctorValue(SMESH.FT_Taper, elemId)
5200 ## Get skew of 2D element.
5201 # @param elemId mesh element ID
5202 # @return element's skew value
5203 # @ingroup l1_measurements
5204 def GetSkew(self, elemId):
5205 return self.FunctorValue(SMESH.FT_Skew, elemId)
5207 ## Return minimal and maximal value of a given functor.
5208 # @param funType a functor type, an item of SMESH.FunctorType enum
5209 # (one of SMESH.FunctorType._items)
5210 # @param meshPart a part of mesh (group, sub-mesh) to treat
5211 # @return tuple (min,max)
5212 # @ingroup l1_measurements
5213 def GetMinMax(self, funType, meshPart=None):
5214 unRegister = genObjUnRegister()
5215 if isinstance( meshPart, list ):
5216 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
5217 unRegister.set( meshPart )
5218 if isinstance( meshPart, Mesh ):
5219 meshPart = meshPart.mesh
5220 fun = self.GetFunctor( funType )
5223 if hasattr( meshPart, "SetMesh" ):
5224 meshPart.SetMesh( self.mesh ) # set mesh to filter
5225 hist = fun.GetLocalHistogram( 1, False, meshPart )
5227 hist = fun.GetHistogram( 1, False )
5229 return hist[0].min, hist[0].max
5232 pass # end of Mesh class
5235 ## Private class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
5236 # with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
5238 class meshProxy(SMESH._objref_SMESH_Mesh):
5239 def __init__(self, *args):
5240 SMESH._objref_SMESH_Mesh.__init__(self, *args)
5241 def __deepcopy__(self, memo=None):
5242 new = self.__class__(self)
5244 def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
5245 if len( args ) == 3:
5246 args += SMESH.ALL_NODES, True
5247 return SMESH._objref_SMESH_Mesh.CreateDimGroup(self, *args)
5248 def ExportToMEDX(self, *args): # function removed
5249 print("WARNING: ExportToMEDX() is deprecated, use ExportMED() instead")
5250 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5251 SMESH._objref_SMESH_Mesh.ExportMED(self, *args)
5252 def ExportToMED(self, *args): # function removed
5253 print("WARNING: ExportToMED() is deprecated, use ExportMED() instead")
5254 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5255 while len(args) < 4: # !!!! nb of parameters for ExportToMED IDL's method
5257 SMESH._objref_SMESH_Mesh.ExportMED(self, *args)
5258 def ExportPartToMED(self, *args): # 'version' parameter removed
5259 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5260 SMESH._objref_SMESH_Mesh.ExportPartToMED(self, *args)
5261 def ExportMED(self, *args): # signature of method changed
5262 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5263 while len(args) < 4: # !!!! nb of parameters for ExportToMED IDL's method
5265 SMESH._objref_SMESH_Mesh.ExportMED(self, *args)
5267 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
5270 ## Private class wrapping SMESH.SMESH_SubMesh in order to add Compute()
5272 class submeshProxy(SMESH._objref_SMESH_subMesh):
5273 def __init__(self, *args):
5274 SMESH._objref_SMESH_subMesh.__init__(self, *args)
5276 def __deepcopy__(self, memo=None):
5277 new = self.__class__(self)
5280 ## Compute the sub-mesh and return the status of the computation
5281 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
5282 # @return True or False
5284 # This is a method of SMESH.SMESH_submesh that can be obtained via Mesh.GetSubMesh() or
5285 # @ref smesh_algorithm.Mesh_Algorithm.GetSubMesh() "Mesh_Algorithm.GetSubMesh()".
5286 # @ingroup l2_submeshes
5287 def Compute(self,refresh=False):
5289 self.mesh = Mesh( smeshBuilder(), None, self.GetMesh())
5291 ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
5293 if salome.sg.hasDesktop():
5294 smeshgui = salome.ImportComponentGUI("SMESH")
5296 smeshgui.SetMeshIcon( salome.ObjectToID( self ), ok, (self.GetNumberOfElements()==0) )
5297 if refresh: salome.sg.updateObjBrowser()
5302 omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy)
5305 ## Private class used to compensate change of CORBA API of SMESH_MeshEditor for backward
5306 # compatibility with old dump scripts which call SMESH_MeshEditor directly and not via
5309 class meshEditor(SMESH._objref_SMESH_MeshEditor):
5310 def __init__(self, *args):
5311 SMESH._objref_SMESH_MeshEditor.__init__(self, *args)
5313 def __getattr__(self, name ): # method called if an attribute not found
5314 if not self.mesh: # look for name() method in Mesh class
5315 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
5316 if hasattr( self.mesh, name ):
5317 return getattr( self.mesh, name )
5318 if name == "ExtrusionAlongPathObjX":
5319 return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
5320 print("meshEditor: attribute '%s' NOT FOUND" % name)
5322 def __deepcopy__(self, memo=None):
5323 new = self.__class__(self)
5325 def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
5326 if len( args ) == 1: args += False,
5327 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
5328 def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
5329 if len( args ) == 2: args += False,
5330 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
5331 def MergeNodes(self,*args): # 2 args added (NodesToKeep,AvoidMakingHoles)
5332 if len( args ) == 1:
5333 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [], False )
5334 NodesToKeep = args[1]
5335 AvoidMakingHoles = args[2] if len( args ) == 3 else False
5336 unRegister = genObjUnRegister()
5338 if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
5339 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
5340 if not isinstance( NodesToKeep, list ):
5341 NodesToKeep = [ NodesToKeep ]
5342 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep, AvoidMakingHoles )
5344 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
5346 ## Private class wrapping SMESH.SMESH_Pattern CORBA class in order to treat Notebook
5347 # variables in some methods
5349 class Pattern(SMESH._objref_SMESH_Pattern):
5351 def LoadFromFile(self, patternTextOrFile ):
5352 text = patternTextOrFile
5353 if os.path.exists( text ):
5354 text = open( patternTextOrFile ).read()
5356 return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
5358 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
5359 decrFun = lambda i: i-1
5360 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
5361 theMesh.SetParameters(Parameters)
5362 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
5364 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
5365 decrFun = lambda i: i-1
5366 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
5367 theMesh.SetParameters(Parameters)
5368 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
5370 def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
5371 if isinstance( mesh, Mesh ):
5372 mesh = mesh.GetMesh()
5373 return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
5375 # Registering the new proxy for Pattern
5376 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
5378 ## Private class used to bind methods creating algorithms to the class Mesh
5381 def __init__(self, method):
5383 self.defaultAlgoType = ""
5384 self.algoTypeToClass = {}
5385 self.method = method
5387 # Store a python class of algorithm
5388 def add(self, algoClass):
5389 if inspect.isclass(algoClass) and \
5390 hasattr(algoClass, "algoType"):
5391 self.algoTypeToClass[ algoClass.algoType ] = algoClass
5392 if not self.defaultAlgoType and \
5393 hasattr( algoClass, "isDefault") and algoClass.isDefault:
5394 self.defaultAlgoType = algoClass.algoType
5395 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
5397 # Create a copy of self and assign mesh to the copy
5398 def copy(self, mesh):
5399 other = algoCreator( self.method )
5400 other.defaultAlgoType = self.defaultAlgoType
5401 other.algoTypeToClass = self.algoTypeToClass
5405 # Create an instance of algorithm
5406 def __call__(self,algo="",geom=0,*args):
5409 if isinstance( algo, str ):
5411 elif ( isinstance( algo, geomBuilder.GEOM._objref_GEOM_Object ) and \
5412 not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object )):
5417 if isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
5419 elif not algoType and isinstance( geom, str ):
5424 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ) and not shape:
5426 elif isinstance( arg, str ) and not algoType:
5429 import traceback, sys
5430 msg = "Warning. Unexpected argument in mesh.%s() ---> %s" % ( self.method, arg )
5431 sys.stderr.write( msg + '\n' )
5432 tb = traceback.extract_stack(None,2)
5433 traceback.print_list( [tb[0]] )
5435 algoType = self.defaultAlgoType
5436 if not algoType and self.algoTypeToClass:
5437 algoType = sorted( self.algoTypeToClass.keys() )[0]
5438 if algoType in self.algoTypeToClass:
5439 #print "Create algo",algoType
5441 return self.algoTypeToClass[ algoType ]( self.mesh, shape )
5442 raise RuntimeError( "No class found for algo type %s" % algoType)
5445 ## Private class used to substitute and store variable parameters of hypotheses.
5447 class hypMethodWrapper:
5448 def __init__(self, hyp, method):
5450 self.method = method
5451 #print "REBIND:", method.__name__
5454 # call a method of hypothesis with calling SetVarParameter() before
5455 def __call__(self,*args):
5457 return self.method( self.hyp, *args ) # hypothesis method with no args
5459 #print "MethWrapper.__call__",self.method.__name__, args
5461 parsed = ParseParameters(*args) # replace variables with their values
5462 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
5463 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
5464 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
5465 # maybe there is a replaced string arg which is not variable
5466 result = self.method( self.hyp, *args )
5467 except ValueError as detail: # raised by ParseParameters()
5469 result = self.method( self.hyp, *args )
5470 except omniORB.CORBA.BAD_PARAM:
5471 raise ValueError(detail) # wrong variable name
5476 ## A helper class that calls UnRegister() of SALOME.GenericObj'es stored in it
5478 class genObjUnRegister:
5480 def __init__(self, genObj=None):
5481 self.genObjList = []
5485 def set(self, genObj):
5486 "Store one or a list of of SALOME.GenericObj'es"
5487 if isinstance( genObj, list ):
5488 self.genObjList.extend( genObj )
5490 self.genObjList.append( genObj )
5494 for genObj in self.genObjList:
5495 if genObj and hasattr( genObj, "UnRegister" ):
5499 ## Bind methods creating mesher plug-ins to the Mesh class
5501 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
5503 #print "pluginName: ", pluginName
5504 pluginBuilderName = pluginName + "Builder"
5506 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
5507 except Exception as e:
5508 from salome_utils import verbose
5509 if verbose(): print("Exception while loading %s: %s" % ( pluginBuilderName, e ))
5511 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5512 plugin = eval( pluginBuilderName )
5513 #print " plugin:" , str(plugin)
5515 # add methods creating algorithms to Mesh
5516 for k in dir( plugin ):
5517 if k[0] == '_': continue
5518 algo = getattr( plugin, k )
5519 #print " algo:", str(algo)
5520 if inspect.isclass(algo) and hasattr(algo, "meshMethod"):
5521 #print " meshMethod:" , str(algo.meshMethod)
5522 if not hasattr( Mesh, algo.meshMethod ):
5523 setattr( Mesh, algo.meshMethod, algoCreator( algo.meshMethod ))
5525 getattr( Mesh, algo.meshMethod ).add( algo )