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
88 from salome.smesh.smesh_algorithm import Mesh_Algorithm
95 ## Private class used to workaround a problem that sometimes isinstance(m, Mesh) returns False
98 def __instancecheck__(cls, inst):
99 """Implement isinstance(inst, cls)."""
100 return any(cls.__subclasscheck__(c)
101 for c in {type(inst), inst.__class__})
103 def __subclasscheck__(cls, sub):
104 """Implement issubclass(sub, cls)."""
105 return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
107 ## @addtogroup l1_auxiliary
110 ## Convert an angle from degrees to radians
111 def DegreesToRadians(AngleInDegrees):
113 return AngleInDegrees * pi / 180.0
115 import salome_notebook
116 notebook = salome_notebook.notebook
117 # Salome notebook variable separator
120 ## Return list of variable values from salome notebook.
121 # The last argument, if is callable, is used to modify values got from notebook
122 def ParseParameters(*args):
127 if args and isinstance( args[-1], collections.Callable):
128 args, varModifFun = args[:-1], args[-1]
129 for parameter in args:
131 Parameters += str(parameter) + var_separator
133 if isinstance(parameter,str):
134 # check if there is an inexistent variable name
135 if not notebook.isVariable(parameter):
136 raise ValueError("Variable with name '" + parameter + "' doesn't exist!!!")
137 parameter = notebook.get(parameter)
140 parameter = varModifFun(parameter)
143 Result.append(parameter)
146 Parameters = Parameters[:-1]
147 Result.append( Parameters )
148 Result.append( hasVariables )
151 ## Parse parameters while converting variables to radians
152 def ParseAngles(*args):
153 return ParseParameters( *( args + (DegreesToRadians, )))
155 ## Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
156 # Parameters are stored in PointStruct.parameters attribute
157 def __initPointStruct(point,*args):
158 point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
160 SMESH.PointStruct.__init__ = __initPointStruct
162 ## Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
163 # Parameters are stored in AxisStruct.parameters attribute
164 def __initAxisStruct(ax,*args):
166 raise RuntimeError("Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args )))
167 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
169 SMESH.AxisStruct.__init__ = __initAxisStruct
171 smeshPrecisionConfusion = 1.e-07
172 ## Compare real values using smeshPrecisionConfusion as tolerance
173 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
174 if abs(val1 - val2) < tol:
180 ## Return object name
184 if isinstance(obj, SALOMEDS._objref_SObject):
188 ior = salome.orb.object_to_string(obj)
193 studies = salome.myStudyManager.GetOpenStudies()
194 for sname in studies:
195 s = salome.myStudyManager.GetStudyByName(sname)
197 sobj = s.FindObjectIOR(ior)
198 if not sobj: continue
199 return sobj.GetName()
200 if hasattr(obj, "GetName"):
201 # unknown CORBA object, having GetName() method
204 # unknown CORBA object, no GetName() method
207 if hasattr(obj, "GetName"):
208 # unknown non-CORBA object, having GetName() method
211 raise RuntimeError("Null or invalid object")
213 ## Print error message if a hypothesis was not assigned.
214 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
216 hypType = "algorithm"
218 hypType = "hypothesis"
221 if hasattr( status, "__getitem__" ):
222 status,reason = status[0],status[1]
223 if status == HYP_UNKNOWN_FATAL :
224 reason = "for unknown reason"
225 elif status == HYP_INCOMPATIBLE :
226 reason = "this hypothesis mismatches the algorithm"
227 elif status == HYP_NOTCONFORM :
228 reason = "a non-conform mesh would be built"
229 elif status == HYP_ALREADY_EXIST :
230 if isAlgo: return # it does not influence anything
231 reason = hypType + " of the same dimension is already assigned to this shape"
232 elif status == HYP_BAD_DIM :
233 reason = hypType + " mismatches the shape"
234 elif status == HYP_CONCURENT :
235 reason = "there are concurrent hypotheses on sub-shapes"
236 elif status == HYP_BAD_SUBSHAPE :
237 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
238 elif status == HYP_BAD_GEOMETRY:
239 reason = "the algorithm is not applicable to this geometry"
240 elif status == HYP_HIDDEN_ALGO:
241 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
242 elif status == HYP_HIDING_ALGO:
243 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
244 elif status == HYP_NEED_SHAPE:
245 reason = "algorithm can't work without shape"
246 elif status == HYP_INCOMPAT_HYPS:
252 where = '"%s"' % geomName
254 meshName = GetName( mesh )
255 if meshName and meshName != NO_NAME:
256 where = '"%s" shape in "%s" mesh ' % ( geomName, meshName )
257 if status < HYP_UNKNOWN_FATAL and where:
258 print('"%s" was assigned to %s but %s' %( hypName, where, reason ))
260 print('"%s" was not assigned to %s : %s' %( hypName, where, reason ))
262 print('"%s" was not assigned : %s' %( hypName, reason ))
265 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
266 def AssureGeomPublished(mesh, geom, name=''):
267 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
269 if not geom.GetStudyEntry() and \
270 mesh.smeshpyD.GetCurrentStudy():
272 studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
273 if studyID != mesh.geompyD.myStudyId:
274 mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
276 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
277 # for all groups SubShapeName() return "Compound_-1"
278 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
280 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
282 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
285 ## Return the first vertex of a geometrical edge by ignoring orientation
286 def FirstVertexOnCurve(mesh, edge):
287 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
289 raise TypeError("Given object has no vertices")
290 if len( vv ) == 1: return vv[0]
291 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
292 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
293 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
294 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
297 dist1 += abs( xyz[i] - xyz1[i] )
298 dist2 += abs( xyz[i] - xyz2[i] )
304 # end of l1_auxiliary
308 # Warning: smeshInst is a singleton
314 ## This class allows to create, load or manipulate meshes.
315 # It has a set of methods to create, load or copy meshes, to combine several meshes, etc.
316 # It also has methods to get infos and measure meshes.
317 class smeshBuilder(SMESH._objref_SMESH_Gen):
319 # MirrorType enumeration
320 POINT = SMESH_MeshEditor.POINT
321 AXIS = SMESH_MeshEditor.AXIS
322 PLANE = SMESH_MeshEditor.PLANE
324 # Smooth_Method enumeration
325 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
326 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
328 PrecisionConfusion = smeshPrecisionConfusion
330 # TopAbs_State enumeration
331 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = list(range(4))
333 # Methods of splitting a hexahedron into tetrahedra
334 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
336 def __new__(cls, *args):
340 #print "==== __new__", engine, smeshInst, doLcc
342 if smeshInst is None:
343 # smesh engine is either retrieved from engine, or created
345 # Following test avoids a recursive loop
347 if smeshInst is not None:
348 # smesh engine not created: existing engine found
352 # FindOrLoadComponent called:
353 # 1. CORBA resolution of server
354 # 2. the __new__ method is called again
355 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
356 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
358 # FindOrLoadComponent not called
359 if smeshInst is None:
360 # smeshBuilder instance is created from lcc.FindOrLoadComponent
361 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
362 smeshInst = super(smeshBuilder,cls).__new__(cls)
364 # smesh engine not created: existing engine found
365 #print "==== existing ", engine, smeshInst, doLcc
367 #print "====1 ", smeshInst
370 #print "====2 ", smeshInst
373 def __init__(self, *args):
375 #print "--------------- smeshbuilder __init__ ---", created
378 SMESH._objref_SMESH_Gen.__init__(self, *args)
380 ## Dump component to the Python script
381 # This method overrides IDL function to allow default values for the parameters.
382 # @ingroup l1_auxiliary
383 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
384 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
386 ## Set mode of DumpPython(), \a historical or \a snapshot.
387 # In the \a historical mode, the Python Dump script includes all commands
388 # performed by SMESH engine. In the \a snapshot mode, commands
389 # relating to objects removed from the Study are excluded from the script
390 # as well as commands not influencing the current state of meshes
391 # @ingroup l1_auxiliary
392 def SetDumpPythonHistorical(self, isHistorical):
393 if isHistorical: val = "true"
395 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
397 ## Set the current study and Geometry component
398 # @ingroup l1_auxiliary
399 def init_smesh(self,theStudy,geompyD = None):
401 self.SetCurrentStudy(theStudy,geompyD)
404 notebook.myStudy = theStudy
406 ## Create a mesh. This can be either an empty mesh, possibly having an underlying geometry,
407 # or a mesh wrapping a CORBA mesh given as a parameter.
408 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
409 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
410 # (2) a Geometrical object for meshing or
412 # @param name the name for the new mesh.
413 # @return an instance of Mesh class.
414 # @ingroup l2_construct
415 def Mesh(self, obj=0, name=0):
416 if isinstance(obj,str):
418 return Mesh(self,self.geompyD,obj,name)
420 ## Return a long value from enumeration
421 # @ingroup l1_auxiliary
422 def EnumToLong(self,theItem):
425 ## Return a string representation of the color.
426 # To be used with filters.
427 # @param c color value (SALOMEDS.Color)
428 # @ingroup l1_auxiliary
429 def ColorToString(self,c):
431 if isinstance(c, SALOMEDS.Color):
432 val = "%s;%s;%s" % (c.R, c.G, c.B)
433 elif isinstance(c, str):
436 raise ValueError("Color value should be of string or SALOMEDS.Color type")
439 ## Get PointStruct from vertex
440 # @param theVertex a GEOM object(vertex)
441 # @return SMESH.PointStruct
442 # @ingroup l1_auxiliary
443 def GetPointStruct(self,theVertex):
444 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
445 return PointStruct(x,y,z)
447 ## Get DirStruct from vector
448 # @param theVector a GEOM object(vector)
449 # @return SMESH.DirStruct
450 # @ingroup l1_auxiliary
451 def GetDirStruct(self,theVector):
452 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
453 if(len(vertices) != 2):
454 print("Error: vector object is incorrect.")
456 p1 = self.geompyD.PointCoordinates(vertices[0])
457 p2 = self.geompyD.PointCoordinates(vertices[1])
458 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
459 dirst = DirStruct(pnt)
462 ## Make DirStruct from a triplet
463 # @param x,y,z vector components
464 # @return SMESH.DirStruct
465 # @ingroup l1_auxiliary
466 def MakeDirStruct(self,x,y,z):
467 pnt = PointStruct(x,y,z)
468 return DirStruct(pnt)
470 ## Get AxisStruct from object
471 # @param theObj a GEOM object (line or plane)
472 # @return SMESH.AxisStruct
473 # @ingroup l1_auxiliary
474 def GetAxisStruct(self,theObj):
476 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
479 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
480 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
481 vertex1 = self.geompyD.PointCoordinates(vertex1)
482 vertex2 = self.geompyD.PointCoordinates(vertex2)
483 vertex3 = self.geompyD.PointCoordinates(vertex3)
484 vertex4 = self.geompyD.PointCoordinates(vertex4)
485 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
486 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
487 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] ]
488 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
489 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
490 elif len(edges) == 1:
491 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
492 p1 = self.geompyD.PointCoordinates( vertex1 )
493 p2 = self.geompyD.PointCoordinates( vertex2 )
494 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
495 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
496 elif theObj.GetShapeType() == GEOM.VERTEX:
497 x,y,z = self.geompyD.PointCoordinates( theObj )
498 axis = AxisStruct( x,y,z, 1,0,0,)
499 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
502 # From SMESH_Gen interface:
503 # ------------------------
505 ## Set the given name to the object
506 # @param obj the object to rename
507 # @param name a new object name
508 # @ingroup l1_auxiliary
509 def SetName(self, obj, name):
510 if isinstance( obj, Mesh ):
512 elif isinstance( obj, Mesh_Algorithm ):
513 obj = obj.GetAlgorithm()
514 ior = salome.orb.object_to_string(obj)
515 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
517 ## Set the current mode
518 # @ingroup l1_auxiliary
519 def SetEmbeddedMode( self,theMode ):
520 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
522 ## Get the current mode
523 # @ingroup l1_auxiliary
524 def IsEmbeddedMode(self):
525 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
527 ## Set the current study. Calling SetCurrentStudy( None ) allows to
528 # switch OFF automatic pubilishing in the Study of mesh objects.
529 # @ingroup l1_auxiliary
530 def SetCurrentStudy( self, theStudy, geompyD = None ):
532 from salome.geom import geomBuilder
533 geompyD = geomBuilder.geom
536 self.SetGeomEngine(geompyD)
537 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
540 notebook = salome_notebook.NoteBook( theStudy )
542 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
544 sb = theStudy.NewBuilder()
545 sc = theStudy.FindComponent("SMESH")
546 if sc: sb.LoadWith(sc, self)
550 ## Get the current study
551 # @ingroup l1_auxiliary
552 def GetCurrentStudy(self):
553 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
555 ## Create a Mesh object importing data from the given UNV file
556 # @return an instance of Mesh class
558 def CreateMeshesFromUNV( self,theFileName ):
559 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
560 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
563 ## Create a Mesh object(s) importing data from the given MED file
564 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
566 def CreateMeshesFromMED( self,theFileName ):
567 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
568 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
569 return aMeshes, aStatus
571 ## Create a Mesh object(s) importing data from the given SAUV file
572 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
574 def CreateMeshesFromSAUV( self,theFileName ):
575 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
576 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
577 return aMeshes, aStatus
579 ## Create a Mesh object importing data from the given STL file
580 # @return an instance of Mesh class
582 def CreateMeshesFromSTL( self, theFileName ):
583 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
584 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
587 ## Create Mesh objects importing data from the given CGNS file
588 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
590 def CreateMeshesFromCGNS( self, theFileName ):
591 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
592 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
593 return aMeshes, aStatus
595 ## Create a Mesh object importing data from the given GMF file.
596 # GMF files must have .mesh extension for the ASCII format and .meshb for
598 # @return [ an instance of Mesh class, SMESH.ComputeError ]
600 def CreateMeshesFromGMF( self, theFileName ):
601 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
604 if error.comment: print("*** CreateMeshesFromGMF() errors:\n", error.comment)
605 return Mesh(self, self.geompyD, aSmeshMesh), error
607 ## Concatenate the given meshes into one mesh. All groups of input meshes will be
608 # present in the new mesh.
609 # @param meshes the meshes, sub-meshes and groups to combine into one mesh
610 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
611 # @param mergeNodesAndElements if true, equal nodes and elements are merged
612 # @param mergeTolerance tolerance for merging nodes
613 # @param allGroups forces creation of groups corresponding to every input mesh
614 # @param name name of a new mesh
615 # @return an instance of Mesh class
616 # @ingroup l1_creating
617 def Concatenate( self, meshes, uniteIdenticalGroups,
618 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
620 if not meshes: return None
621 for i,m in enumerate(meshes):
622 if isinstance(m, Mesh):
623 meshes[i] = m.GetMesh()
624 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
625 meshes[0].SetParameters(Parameters)
627 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
628 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
630 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
631 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
632 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
635 ## Create a mesh by copying a part of another mesh.
636 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
637 # to copy nodes or elements not contained in any mesh object,
638 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
639 # @param meshName a name of the new mesh
640 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
641 # @param toKeepIDs to preserve order of the copied elements or not
642 # @return an instance of Mesh class
643 # @ingroup l1_creating
644 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
645 if (isinstance( meshPart, Mesh )):
646 meshPart = meshPart.GetMesh()
647 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
648 return Mesh(self, self.geompyD, mesh)
650 ## Return IDs of sub-shapes
651 # @return the list of integer values
652 # @ingroup l1_auxiliary
653 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
654 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
656 ## Create a pattern mapper.
657 # @return an instance of SMESH_Pattern
659 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
660 # @ingroup l1_modifying
661 def GetPattern(self):
662 return SMESH._objref_SMESH_Gen.GetPattern(self)
664 ## Set number of segments per diagonal of boundary box of geometry, by which
665 # default segment length of appropriate 1D hypotheses is defined in GUI.
666 # Default value is 10.
667 # @ingroup l1_auxiliary
668 def SetBoundaryBoxSegmentation(self, nbSegments):
669 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
671 # Filtering. Auxiliary functions:
672 # ------------------------------
674 ## Create an empty criterion
675 # @return SMESH.Filter.Criterion
676 # @ingroup l1_controls
677 def GetEmptyCriterion(self):
678 Type = self.EnumToLong(FT_Undefined)
679 Compare = self.EnumToLong(FT_Undefined)
683 UnaryOp = self.EnumToLong(FT_Undefined)
684 BinaryOp = self.EnumToLong(FT_Undefined)
687 Precision = -1 ##@1e-07
688 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
689 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
691 ## Create a criterion by the given parameters
692 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
693 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
694 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
695 # Type SMESH.FunctorType._items in the Python Console to see all values.
696 # Note that the items starting from FT_LessThan are not suitable for CritType.
697 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
698 # @param Threshold the threshold value (range of ids as string, shape, numeric)
699 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
700 # @param BinaryOp a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or
702 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
703 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
704 # @return SMESH.Filter.Criterion
706 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
707 # @ingroup l1_controls
708 def GetCriterion(self,elementType,
710 Compare = FT_EqualTo,
712 UnaryOp=FT_Undefined,
713 BinaryOp=FT_Undefined,
715 if not CritType in SMESH.FunctorType._items:
716 raise TypeError("CritType should be of SMESH.FunctorType")
717 aCriterion = self.GetEmptyCriterion()
718 aCriterion.TypeOfElement = elementType
719 aCriterion.Type = self.EnumToLong(CritType)
720 aCriterion.Tolerance = Tolerance
722 aThreshold = Threshold
724 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
725 aCriterion.Compare = self.EnumToLong(Compare)
726 elif Compare == "=" or Compare == "==":
727 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
729 aCriterion.Compare = self.EnumToLong(FT_LessThan)
731 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
732 elif Compare != FT_Undefined:
733 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
736 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
737 FT_BelongToCylinder, FT_LyingOnGeom]:
738 # Check that Threshold is GEOM object
739 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
740 aCriterion.ThresholdStr = GetName(aThreshold)
741 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
742 if not aCriterion.ThresholdID:
743 name = aCriterion.ThresholdStr
745 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
746 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
747 # or a name of GEOM object
748 elif isinstance( aThreshold, str ):
749 aCriterion.ThresholdStr = aThreshold
751 raise TypeError("The Threshold should be a shape.")
752 if isinstance(UnaryOp,float):
753 aCriterion.Tolerance = UnaryOp
754 UnaryOp = FT_Undefined
756 elif CritType == FT_BelongToMeshGroup:
757 # Check that Threshold is a group
758 if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
759 if aThreshold.GetType() != elementType:
760 raise ValueError("Group type mismatches Element type")
761 aCriterion.ThresholdStr = aThreshold.GetName()
762 aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
763 study = self.GetCurrentStudy()
765 so = study.FindObjectIOR( aCriterion.ThresholdID )
769 aCriterion.ThresholdID = entry
771 raise TypeError("The Threshold should be a Mesh Group")
772 elif CritType == FT_RangeOfIds:
773 # Check that Threshold is string
774 if isinstance(aThreshold, str):
775 aCriterion.ThresholdStr = aThreshold
777 raise TypeError("The Threshold should be a string.")
778 elif CritType == FT_CoplanarFaces:
779 # Check the Threshold
780 if isinstance(aThreshold, int):
781 aCriterion.ThresholdID = str(aThreshold)
782 elif isinstance(aThreshold, str):
785 raise ValueError("Invalid ID of mesh face: '%s'"%aThreshold)
786 aCriterion.ThresholdID = aThreshold
788 raise TypeError("The Threshold should be an ID of mesh face and not '%s'"%aThreshold)
789 elif CritType == FT_ConnectedElements:
790 # Check the Threshold
791 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
792 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
793 if not aCriterion.ThresholdID:
794 name = aThreshold.GetName()
796 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
797 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
798 elif isinstance(aThreshold, int): # node id
799 aCriterion.Threshold = aThreshold
800 elif isinstance(aThreshold, list): # 3 point coordinates
801 if len( aThreshold ) < 3:
802 raise ValueError("too few point coordinates, must be 3")
803 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
804 elif isinstance(aThreshold, str):
805 if aThreshold.isdigit():
806 aCriterion.Threshold = aThreshold # node id
808 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
810 raise TypeError("The Threshold should either a VERTEX, or a node ID, "\
811 "or a list of point coordinates and not '%s'"%aThreshold)
812 elif CritType == FT_ElemGeomType:
813 # Check the Threshold
815 aCriterion.Threshold = self.EnumToLong(aThreshold)
816 assert( aThreshold in SMESH.GeometryType._items )
818 if isinstance(aThreshold, int):
819 aCriterion.Threshold = aThreshold
821 raise TypeError("The Threshold should be an integer or SMESH.GeometryType.")
824 elif CritType == FT_EntityType:
825 # Check the Threshold
827 aCriterion.Threshold = self.EnumToLong(aThreshold)
828 assert( aThreshold in SMESH.EntityType._items )
830 if isinstance(aThreshold, int):
831 aCriterion.Threshold = aThreshold
833 raise TypeError("The Threshold should be an integer or SMESH.EntityType.")
837 elif CritType == FT_GroupColor:
838 # Check the Threshold
840 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
842 raise TypeError("The threshold value should be of SALOMEDS.Color type")
844 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
845 FT_LinearOrQuadratic, FT_BadOrientedVolume,
846 FT_BareBorderFace, FT_BareBorderVolume,
847 FT_OverConstrainedFace, FT_OverConstrainedVolume,
848 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
849 # At this point the Threshold is unnecessary
850 if aThreshold == FT_LogicalNOT:
851 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
852 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
853 aCriterion.BinaryOp = aThreshold
857 aThreshold = float(aThreshold)
858 aCriterion.Threshold = aThreshold
860 raise TypeError("The Threshold should be a number.")
863 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
864 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
866 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
867 aCriterion.BinaryOp = self.EnumToLong(Threshold)
869 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
870 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
872 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
873 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
877 ## Create a filter with the given parameters
878 # @param elementType the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
879 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
880 # Type SMESH.FunctorType._items in the Python Console to see all values.
881 # Note that the items starting from FT_LessThan are not suitable for CritType.
882 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
883 # @param Threshold the threshold value (range of ids as string, shape, numeric)
884 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
885 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
886 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
887 # @param mesh the mesh to initialize the filter with
888 # @return SMESH_Filter
890 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
891 # @ingroup l1_controls
892 def GetFilter(self,elementType,
893 CritType=FT_Undefined,
896 UnaryOp=FT_Undefined,
899 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
900 aFilterMgr = self.CreateFilterManager()
901 aFilter = aFilterMgr.CreateFilter()
903 aCriteria.append(aCriterion)
904 aFilter.SetCriteria(aCriteria)
906 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
907 else : aFilter.SetMesh( mesh )
908 aFilterMgr.UnRegister()
911 ## Create a filter from criteria
912 # @param criteria a list of criteria
913 # @param binOp binary operator used when binary operator of criteria is undefined
914 # @return SMESH_Filter
916 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
917 # @ingroup l1_controls
918 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
919 for i in range( len( criteria ) - 1 ):
920 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
921 criteria[i].BinaryOp = self.EnumToLong( binOp )
922 aFilterMgr = self.CreateFilterManager()
923 aFilter = aFilterMgr.CreateFilter()
924 aFilter.SetCriteria(criteria)
925 aFilterMgr.UnRegister()
928 ## Create a numerical functor by its type
929 # @param theCriterion functor type - an item of SMESH.FunctorType enumeration.
930 # Type SMESH.FunctorType._items in the Python Console to see all items.
931 # Note that not all items correspond to numerical functors.
932 # @return SMESH_NumericalFunctor
933 # @ingroup l1_controls
934 def GetFunctor(self,theCriterion):
935 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
937 aFilterMgr = self.CreateFilterManager()
939 if theCriterion == FT_AspectRatio:
940 functor = aFilterMgr.CreateAspectRatio()
941 elif theCriterion == FT_AspectRatio3D:
942 functor = aFilterMgr.CreateAspectRatio3D()
943 elif theCriterion == FT_Warping:
944 functor = aFilterMgr.CreateWarping()
945 elif theCriterion == FT_MinimumAngle:
946 functor = aFilterMgr.CreateMinimumAngle()
947 elif theCriterion == FT_Taper:
948 functor = aFilterMgr.CreateTaper()
949 elif theCriterion == FT_Skew:
950 functor = aFilterMgr.CreateSkew()
951 elif theCriterion == FT_Area:
952 functor = aFilterMgr.CreateArea()
953 elif theCriterion == FT_Volume3D:
954 functor = aFilterMgr.CreateVolume3D()
955 elif theCriterion == FT_MaxElementLength2D:
956 functor = aFilterMgr.CreateMaxElementLength2D()
957 elif theCriterion == FT_MaxElementLength3D:
958 functor = aFilterMgr.CreateMaxElementLength3D()
959 elif theCriterion == FT_MultiConnection:
960 functor = aFilterMgr.CreateMultiConnection()
961 elif theCriterion == FT_MultiConnection2D:
962 functor = aFilterMgr.CreateMultiConnection2D()
963 elif theCriterion == FT_Length:
964 functor = aFilterMgr.CreateLength()
965 elif theCriterion == FT_Length2D:
966 functor = aFilterMgr.CreateLength2D()
967 elif theCriterion == FT_NodeConnectivityNumber:
968 functor = aFilterMgr.CreateNodeConnectivityNumber()
969 elif theCriterion == FT_BallDiameter:
970 functor = aFilterMgr.CreateBallDiameter()
972 print("Error: given parameter is not numerical functor type.")
973 aFilterMgr.UnRegister()
977 # @param theHType mesh hypothesis type (string)
978 # @param theLibName mesh plug-in library name
979 # @return created hypothesis instance
980 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
981 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
983 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
986 # wrap hypothesis methods
987 #print "HYPOTHESIS", theHType
988 for meth_name in dir( hyp.__class__ ):
989 if not meth_name.startswith("Get") and \
990 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
991 method = getattr ( hyp.__class__, meth_name )
992 if isinstance(method, collections.Callable):
993 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
997 ## Get the mesh statistic
998 # @return dictionary "element type" - "count of elements"
999 # @ingroup l1_meshinfo
1000 def GetMeshInfo(self, obj):
1001 if isinstance( obj, Mesh ):
1004 if hasattr(obj, "GetMeshInfo"):
1005 values = obj.GetMeshInfo()
1006 for i in range(SMESH.Entity_Last._v):
1007 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1011 ## Get minimum distance between two objects
1013 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1014 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1016 # @param src1 first source object
1017 # @param src2 second source object
1018 # @param id1 node/element id from the first source
1019 # @param id2 node/element id from the second (or first) source
1020 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1021 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1022 # @return minimum distance value
1023 # @sa GetMinDistance()
1024 # @ingroup l1_measurements
1025 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1026 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1030 result = result.value
1033 ## Get measure structure specifying minimum distance data between two objects
1035 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1036 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1038 # @param src1 first source object
1039 # @param src2 second source object
1040 # @param id1 node/element id from the first source
1041 # @param id2 node/element id from the second (or first) source
1042 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1043 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1044 # @return Measure structure or None if input data is invalid
1046 # @ingroup l1_measurements
1047 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1048 if isinstance(src1, Mesh): src1 = src1.mesh
1049 if isinstance(src2, Mesh): src2 = src2.mesh
1050 if src2 is None and id2 != 0: src2 = src1
1051 if not hasattr(src1, "_narrow"): return None
1052 src1 = src1._narrow(SMESH.SMESH_IDSource)
1053 if not src1: return None
1054 unRegister = genObjUnRegister()
1057 e = m.GetMeshEditor()
1059 src1 = e.MakeIDSource([id1], SMESH.FACE)
1061 src1 = e.MakeIDSource([id1], SMESH.NODE)
1062 unRegister.set( src1 )
1064 if hasattr(src2, "_narrow"):
1065 src2 = src2._narrow(SMESH.SMESH_IDSource)
1066 if src2 and id2 != 0:
1068 e = m.GetMeshEditor()
1070 src2 = e.MakeIDSource([id2], SMESH.FACE)
1072 src2 = e.MakeIDSource([id2], SMESH.NODE)
1073 unRegister.set( src2 )
1076 aMeasurements = self.CreateMeasurements()
1077 unRegister.set( aMeasurements )
1078 result = aMeasurements.MinDistance(src1, src2)
1081 ## Get bounding box of the specified object(s)
1082 # @param objects single source object or list of source objects
1083 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1084 # @sa GetBoundingBox()
1085 # @ingroup l1_measurements
1086 def BoundingBox(self, objects):
1087 result = self.GetBoundingBox(objects)
1091 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1094 ## Get measure structure specifying bounding box data of the specified object(s)
1095 # @param objects single source object or list of source objects
1096 # @return Measure structure
1098 # @ingroup l1_measurements
1099 def GetBoundingBox(self, objects):
1100 if isinstance(objects, tuple):
1101 objects = list(objects)
1102 if not isinstance(objects, list):
1106 if isinstance(o, Mesh):
1107 srclist.append(o.mesh)
1108 elif hasattr(o, "_narrow"):
1109 src = o._narrow(SMESH.SMESH_IDSource)
1110 if src: srclist.append(src)
1113 aMeasurements = self.CreateMeasurements()
1114 result = aMeasurements.BoundingBox(srclist)
1115 aMeasurements.UnRegister()
1118 ## Get sum of lengths of all 1D elements in the mesh object.
1119 # @param obj mesh, submesh or group
1120 # @return sum of lengths of all 1D elements
1121 # @ingroup l1_measurements
1122 def GetLength(self, obj):
1123 if isinstance(obj, Mesh): obj = obj.mesh
1124 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1125 aMeasurements = self.CreateMeasurements()
1126 value = aMeasurements.Length(obj)
1127 aMeasurements.UnRegister()
1130 ## Get sum of areas of all 2D elements in the mesh object.
1131 # @param obj mesh, submesh or group
1132 # @return sum of areas of all 2D elements
1133 # @ingroup l1_measurements
1134 def GetArea(self, obj):
1135 if isinstance(obj, Mesh): obj = obj.mesh
1136 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1137 aMeasurements = self.CreateMeasurements()
1138 value = aMeasurements.Area(obj)
1139 aMeasurements.UnRegister()
1142 ## Get sum of volumes of all 3D elements in the mesh object.
1143 # @param obj mesh, submesh or group
1144 # @return sum of volumes of all 3D elements
1145 # @ingroup l1_measurements
1146 def GetVolume(self, obj):
1147 if isinstance(obj, Mesh): obj = obj.mesh
1148 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1149 aMeasurements = self.CreateMeasurements()
1150 value = aMeasurements.Volume(obj)
1151 aMeasurements.UnRegister()
1154 pass # end of class smeshBuilder
1157 #Registering the new proxy for SMESH_Gen
1158 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1160 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1161 # interface to create or load meshes.
1166 # salome.salome_init()
1167 # from salome.smesh import smeshBuilder
1168 # smesh = smeshBuilder.New(salome.myStudy)
1170 # @param study SALOME study, generally obtained by salome.myStudy.
1171 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1172 # @return smeshBuilder instance
1174 def New( study, instance=None):
1176 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1177 interface to create or load meshes.
1181 salome.salome_init()
1182 from salome.smesh import smeshBuilder
1183 smesh = smeshBuilder.New(salome.myStudy)
1186 study SALOME study, generally obtained by salome.myStudy.
1187 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1189 smeshBuilder instance
1197 smeshInst = smeshBuilder()
1198 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1199 smeshInst.init_smesh(study)
1203 # Public class: Mesh
1204 # ==================
1206 ## This class allows defining and managing a mesh.
1207 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1208 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1209 # new nodes and elements and by changing the existing entities), to get information
1210 # about a mesh and to export a mesh in different formats.
1211 class Mesh(metaclass=MeshMeta):
1218 # Create a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1219 # sets the GUI name of this mesh to \a name.
1220 # @param smeshpyD an instance of smeshBuilder class
1221 # @param geompyD an instance of geomBuilder class
1222 # @param obj Shape to be meshed or SMESH_Mesh object
1223 # @param name Study name of the mesh
1224 # @ingroup l2_construct
1225 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1226 self.smeshpyD=smeshpyD
1227 self.geompyD=geompyD
1232 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1235 # publish geom of mesh (issue 0021122)
1236 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1238 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1239 if studyID != geompyD.myStudyId:
1240 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1243 geo_name = name + " shape"
1245 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1246 geompyD.addToStudy( self.geom, geo_name )
1247 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1249 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1252 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1254 self.smeshpyD.SetName(self.mesh, name)
1256 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1259 self.geom = self.mesh.GetShapeToMesh()
1261 self.editor = self.mesh.GetMeshEditor()
1262 self.functors = [None] * SMESH.FT_Undefined._v
1264 # set self to algoCreator's
1265 for attrName in dir(self):
1266 attr = getattr( self, attrName )
1267 if isinstance( attr, algoCreator ):
1268 setattr( self, attrName, attr.copy( self ))
1273 ## Destructor. Clean-up resources
1276 #self.mesh.UnRegister()
1280 ## Initialize the Mesh object from an instance of SMESH_Mesh interface
1281 # @param theMesh a SMESH_Mesh object
1282 # @ingroup l2_construct
1283 def SetMesh(self, theMesh):
1284 # do not call Register() as this prevents mesh servant deletion at closing study
1285 #if self.mesh: self.mesh.UnRegister()
1288 #self.mesh.Register()
1289 self.geom = self.mesh.GetShapeToMesh()
1292 ## Return the mesh, that is an instance of SMESH_Mesh interface
1293 # @return a SMESH_Mesh object
1294 # @ingroup l2_construct
1298 ## Get the name of the mesh
1299 # @return the name of the mesh as a string
1300 # @ingroup l2_construct
1302 name = GetName(self.GetMesh())
1305 ## Set a name to the mesh
1306 # @param name a new name of the mesh
1307 # @ingroup l2_construct
1308 def SetName(self, name):
1309 self.smeshpyD.SetName(self.GetMesh(), name)
1311 ## Get a sub-mesh object associated to a \a geom geometrical object.
1312 # @param geom a geometrical object (shape)
1313 # @param name a name for the sub-mesh in the Object Browser
1314 # @return an object of type SMESH.SMESH_subMesh, representing a part of mesh,
1315 # which lies on the given shape
1317 # The sub-mesh object gives access to the IDs of nodes and elements.
1318 # The sub-mesh object has the following methods:
1319 # - SMESH.SMESH_subMesh.GetNumberOfElements()
1320 # - SMESH.SMESH_subMesh.GetNumberOfNodes( all )
1321 # - SMESH.SMESH_subMesh.GetElementsId()
1322 # - SMESH.SMESH_subMesh.GetElementsByType( ElementType )
1323 # - SMESH.SMESH_subMesh.GetNodesId()
1324 # - SMESH.SMESH_subMesh.GetSubShape()
1325 # - SMESH.SMESH_subMesh.GetFather()
1326 # - SMESH.SMESH_subMesh.GetId()
1327 # @note A sub-mesh is implicitly created when a sub-shape is specified at
1328 # creating an algorithm, for example: <code>algo1D = mesh.Segment(geom=Edge_1) </code>
1329 # creates a sub-mesh on @c Edge_1 and assign Wire Discretization algorithm to it.
1330 # The created sub-mesh can be retrieved from the algorithm:
1331 # <code>submesh = algo1D.GetSubMesh()</code>
1332 # @ingroup l2_submeshes
1333 def GetSubMesh(self, geom, name):
1334 AssureGeomPublished( self, geom, name )
1335 submesh = self.mesh.GetSubMesh( geom, name )
1338 ## Return the shape associated to the mesh
1339 # @return a GEOM_Object
1340 # @ingroup l2_construct
1344 ## Associate the given shape to the mesh (entails the recreation of the mesh)
1345 # @param geom the shape to be meshed (GEOM_Object)
1346 # @ingroup l2_construct
1347 def SetShape(self, geom):
1348 self.mesh = self.smeshpyD.CreateMesh(geom)
1350 ## Load mesh from the study after opening the study
1354 ## Return true if the hypotheses are defined well
1355 # @param theSubObject a sub-shape of a mesh shape
1356 # @return True or False
1357 # @ingroup l2_construct
1358 def IsReadyToCompute(self, theSubObject):
1359 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1361 ## Return errors of hypotheses definition.
1362 # The list of errors is empty if everything is OK.
1363 # @param theSubObject a sub-shape of a mesh shape
1364 # @return a list of errors
1365 # @ingroup l2_construct
1366 def GetAlgoState(self, theSubObject):
1367 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1369 ## Return a geometrical object on which the given element was built.
1370 # The returned geometrical object, if not nil, is either found in the
1371 # study or published by this method with the given name
1372 # @param theElementID the id of the mesh element
1373 # @param theGeomName the user-defined name of the geometrical object
1374 # @return GEOM::GEOM_Object instance
1375 # @ingroup l1_meshinfo
1376 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1377 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1379 ## Return the mesh dimension depending on the dimension of the underlying shape
1380 # or, if the mesh is not based on any shape, basing on deimension of elements
1381 # @return mesh dimension as an integer value [0,3]
1382 # @ingroup l1_meshinfo
1383 def MeshDimension(self):
1384 if self.mesh.HasShapeToMesh():
1385 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1386 if len( shells ) > 0 :
1388 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1390 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1395 if self.NbVolumes() > 0: return 3
1396 if self.NbFaces() > 0: return 2
1397 if self.NbEdges() > 0: return 1
1400 ## Evaluate size of prospective mesh on a shape
1401 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1402 # To know predicted number of e.g. edges, inquire it this way
1403 # Evaluate()[ EnumToLong( Entity_Edge )]
1404 # @ingroup l2_construct
1405 def Evaluate(self, geom=0):
1406 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1408 geom = self.mesh.GetShapeToMesh()
1411 return self.smeshpyD.Evaluate(self.mesh, geom)
1414 ## Compute the mesh and return the status of the computation
1415 # @param geom geomtrical shape on which mesh data should be computed
1416 # @param discardModifs if True and the mesh has been edited since
1417 # a last total re-compute and that may prevent successful partial re-compute,
1418 # then the mesh is cleaned before Compute()
1419 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1420 # @return True or False
1421 # @ingroup l2_construct
1422 def Compute(self, geom=0, discardModifs=False, refresh=False):
1423 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1425 geom = self.mesh.GetShapeToMesh()
1430 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1432 ok = self.smeshpyD.Compute(self.mesh, geom)
1433 except SALOME.SALOME_Exception as ex:
1434 print("Mesh computation failed, exception caught:")
1435 print(" ", ex.details.text)
1438 print("Mesh computation failed, exception caught:")
1439 traceback.print_exc()
1443 # Treat compute errors
1444 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1446 for err in computeErrors:
1447 if self.mesh.HasShapeToMesh():
1448 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1450 stdErrors = ["OK", #COMPERR_OK
1451 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1452 "std::exception", #COMPERR_STD_EXCEPTION
1453 "OCC exception", #COMPERR_OCC_EXCEPTION
1454 "..", #COMPERR_SLM_EXCEPTION
1455 "Unknown exception", #COMPERR_EXCEPTION
1456 "Memory allocation problem", #COMPERR_MEMORY_PB
1457 "Algorithm failed", #COMPERR_ALGO_FAILED
1458 "Unexpected geometry", #COMPERR_BAD_SHAPE
1459 "Warning", #COMPERR_WARNING
1460 "Computation cancelled",#COMPERR_CANCELED
1461 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1463 if err.code < len(stdErrors): errText = stdErrors[err.code]
1465 errText = "code %s" % -err.code
1466 if errText: errText += ". "
1467 errText += err.comment
1468 if allReasons: allReasons += "\n"
1470 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1472 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1476 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1478 if err.isGlobalAlgo:
1486 reason = '%s %sD algorithm is missing' % (glob, dim)
1487 elif err.state == HYP_MISSING:
1488 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1489 % (glob, dim, name, dim))
1490 elif err.state == HYP_NOTCONFORM:
1491 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1492 elif err.state == HYP_BAD_PARAMETER:
1493 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1494 % ( glob, dim, name ))
1495 elif err.state == HYP_BAD_GEOMETRY:
1496 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1497 'geometry' % ( glob, dim, name ))
1498 elif err.state == HYP_HIDDEN_ALGO:
1499 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1500 'algorithm of upper dimension generating %sD mesh'
1501 % ( glob, dim, name, glob, dim ))
1503 reason = ("For unknown reason. "
1504 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1506 if allReasons: allReasons += "\n"
1507 allReasons += "- " + reason
1509 if not ok or allReasons != "":
1510 msg = '"' + GetName(self.mesh) + '"'
1511 if ok: msg += " has been computed with warnings"
1512 else: msg += " has not been computed"
1513 if allReasons != "": msg += ":"
1518 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1519 if not isinstance( refresh, list): # not a call from subMesh.Compute()
1520 smeshgui = salome.ImportComponentGUI("SMESH")
1521 smeshgui.Init(self.mesh.GetStudyId())
1522 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1523 if refresh: salome.sg.updateObjBrowser(True)
1527 ## Return a list of error messages (SMESH.ComputeError) of the last Compute()
1528 # @ingroup l2_construct
1529 def GetComputeErrors(self, shape=0 ):
1531 shape = self.mesh.GetShapeToMesh()
1532 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1534 ## Return a name of a sub-shape by its ID
1535 # @param subShapeID a unique ID of a sub-shape
1536 # @return a string describing the sub-shape; possible variants:
1537 # - "Face_12" (published sub-shape)
1538 # - FACE #3 (not published sub-shape)
1539 # - sub-shape #3 (invalid sub-shape ID)
1540 # - #3 (error in this function)
1541 # @ingroup l1_auxiliary
1542 def GetSubShapeName(self, subShapeID ):
1543 if not self.mesh.HasShapeToMesh():
1547 mainIOR = salome.orb.object_to_string( self.GetShape() )
1548 for sname in salome.myStudyManager.GetOpenStudies():
1549 s = salome.myStudyManager.GetStudyByName(sname)
1551 mainSO = s.FindObjectIOR(mainIOR)
1552 if not mainSO: continue
1554 shapeText = '"%s"' % mainSO.GetName()
1555 subIt = s.NewChildIterator(mainSO)
1557 subSO = subIt.Value()
1559 obj = subSO.GetObject()
1560 if not obj: continue
1561 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1564 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1567 if ids == subShapeID:
1568 shapeText = '"%s"' % subSO.GetName()
1571 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1573 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1575 shapeText = 'sub-shape #%s' % (subShapeID)
1577 shapeText = "#%s" % (subShapeID)
1580 ## Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1581 # error of an algorithm
1582 # @param publish if @c True, the returned groups will be published in the study
1583 # @return a list of GEOM groups each named after a failed algorithm
1584 # @ingroup l2_construct
1585 def GetFailedShapes(self, publish=False):
1588 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1589 for err in computeErrors:
1590 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1591 if not shape: continue
1592 if err.algoName in algo2shapes:
1593 algo2shapes[ err.algoName ].append( shape )
1595 algo2shapes[ err.algoName ] = [ shape ]
1599 for algoName, shapes in list(algo2shapes.items()):
1601 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1602 otherTypeShapes = []
1604 group = self.geompyD.CreateGroup( self.geom, groupType )
1605 for shape in shapes:
1606 if shape.GetShapeType() == shapes[0].GetShapeType():
1607 sameTypeShapes.append( shape )
1609 otherTypeShapes.append( shape )
1610 self.geompyD.UnionList( group, sameTypeShapes )
1612 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1614 group.SetName( algoName )
1615 groups.append( group )
1616 shapes = otherTypeShapes
1619 for group in groups:
1620 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1623 ## Return sub-mesh objects list in meshing order
1624 # @return list of lists of sub-meshes
1625 # @ingroup l2_construct
1626 def GetMeshOrder(self):
1627 return self.mesh.GetMeshOrder()
1629 ## Set order in which concurrent sub-meshes should be meshed
1630 # @param submeshes list of lists of sub-meshes
1631 # @ingroup l2_construct
1632 def SetMeshOrder(self, submeshes):
1633 return self.mesh.SetMeshOrder(submeshes)
1635 ## Remove all nodes and elements generated on geometry. Imported elements remain.
1636 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1637 # @ingroup l2_construct
1638 def Clear(self, refresh=False):
1640 if ( salome.sg.hasDesktop() and
1641 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1642 smeshgui = salome.ImportComponentGUI("SMESH")
1643 smeshgui.Init(self.mesh.GetStudyId())
1644 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1645 if refresh: salome.sg.updateObjBrowser(True)
1647 ## Remove all nodes and elements of indicated shape
1648 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1649 # @param geomId the ID of a sub-shape to remove elements on
1650 # @ingroup l2_submeshes
1651 def ClearSubMesh(self, geomId, refresh=False):
1652 self.mesh.ClearSubMesh(geomId)
1653 if salome.sg.hasDesktop():
1654 smeshgui = salome.ImportComponentGUI("SMESH")
1655 smeshgui.Init(self.mesh.GetStudyId())
1656 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1657 if refresh: salome.sg.updateObjBrowser(True)
1659 ## Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1660 # @param fineness [0.0,1.0] defines mesh fineness
1661 # @return True or False
1662 # @ingroup l3_algos_basic
1663 def AutomaticTetrahedralization(self, fineness=0):
1664 dim = self.MeshDimension()
1666 self.RemoveGlobalHypotheses()
1667 self.Segment().AutomaticLength(fineness)
1669 self.Triangle().LengthFromEdges()
1674 return self.Compute()
1676 ## Compute an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1677 # @param fineness [0.0, 1.0] defines mesh fineness
1678 # @return True or False
1679 # @ingroup l3_algos_basic
1680 def AutomaticHexahedralization(self, fineness=0):
1681 dim = self.MeshDimension()
1682 # assign the hypotheses
1683 self.RemoveGlobalHypotheses()
1684 self.Segment().AutomaticLength(fineness)
1691 return self.Compute()
1693 ## Assign a hypothesis
1694 # @param hyp a hypothesis to assign
1695 # @param geom a subhape of mesh geometry
1696 # @return SMESH.Hypothesis_Status
1697 # @ingroup l2_editing
1698 def AddHypothesis(self, hyp, geom=0):
1699 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1700 hyp, geom = geom, hyp
1701 if isinstance( hyp, Mesh_Algorithm ):
1702 hyp = hyp.GetAlgorithm()
1707 geom = self.mesh.GetShapeToMesh()
1710 if self.mesh.HasShapeToMesh():
1711 hyp_type = hyp.GetName()
1712 lib_name = hyp.GetLibName()
1713 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1714 # if checkAll and geom:
1715 # checkAll = geom.GetType() == 37
1717 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1719 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1720 status = self.mesh.AddHypothesis(geom, hyp)
1722 status = HYP_BAD_GEOMETRY,""
1723 hyp_name = GetName( hyp )
1726 geom_name = geom.GetName()
1727 isAlgo = hyp._narrow( SMESH_Algo )
1728 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1731 ## Return True if an algorithm of hypothesis is assigned to a given shape
1732 # @param hyp a hypothesis to check
1733 # @param geom a subhape of mesh geometry
1734 # @return True of False
1735 # @ingroup l2_editing
1736 def IsUsedHypothesis(self, hyp, geom):
1737 if not hyp: # or not geom
1739 if isinstance( hyp, Mesh_Algorithm ):
1740 hyp = hyp.GetAlgorithm()
1742 hyps = self.GetHypothesisList(geom)
1744 if h.GetId() == hyp.GetId():
1748 ## Unassign a hypothesis
1749 # @param hyp a hypothesis to unassign
1750 # @param geom a sub-shape of mesh geometry
1751 # @return SMESH.Hypothesis_Status
1752 # @ingroup l2_editing
1753 def RemoveHypothesis(self, hyp, geom=0):
1756 if isinstance( hyp, Mesh_Algorithm ):
1757 hyp = hyp.GetAlgorithm()
1763 if self.IsUsedHypothesis( hyp, shape ):
1764 return self.mesh.RemoveHypothesis( shape, hyp )
1765 hypName = GetName( hyp )
1766 geoName = GetName( shape )
1767 print("WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName ))
1770 ## Get the list of hypotheses added on a geometry
1771 # @param geom a sub-shape of mesh geometry
1772 # @return the sequence of SMESH_Hypothesis
1773 # @ingroup l2_editing
1774 def GetHypothesisList(self, geom):
1775 return self.mesh.GetHypothesisList( geom )
1777 ## Remove all global hypotheses
1778 # @ingroup l2_editing
1779 def RemoveGlobalHypotheses(self):
1780 current_hyps = self.mesh.GetHypothesisList( self.geom )
1781 for hyp in current_hyps:
1782 self.mesh.RemoveHypothesis( self.geom, hyp )
1786 ## Export the mesh in a file in MED format
1787 ## allowing to overwrite the file if it exists or add the exported data to its contents
1788 # @param f is the file name
1789 # @param auto_groups boolean parameter for creating/not creating
1790 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1791 # the typical use is auto_groups=False.
1792 # @param version MED format version (MED_V2_1 or MED_V2_2,
1793 # the latter meaning any current version). The parameter is
1794 # obsolete since MED_V2_1 is no longer supported.
1795 # @param overwrite boolean parameter for overwriting/not overwriting the file
1796 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1797 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1798 # - 1D if all mesh nodes lie on OX coordinate axis, or
1799 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1800 # - 3D in the rest cases.<br>
1801 # If @a autoDimension is @c False, the space dimension is always 3.
1802 # @param fields list of GEOM fields defined on the shape to mesh.
1803 # @param geomAssocFields each character of this string means a need to export a
1804 # corresponding field; correspondence between fields and characters is following:
1805 # - 'v' stands for "_vertices _" field;
1806 # - 'e' stands for "_edges _" field;
1807 # - 'f' stands for "_faces _" field;
1808 # - 's' stands for "_solids _" field.
1809 # @ingroup l2_impexp
1810 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1811 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1812 if meshPart or fields or geomAssocFields:
1813 unRegister = genObjUnRegister()
1814 if isinstance( meshPart, list ):
1815 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1816 unRegister.set( meshPart )
1817 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1818 fields, geomAssocFields)
1820 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1822 ## Export the mesh in a file in SAUV format
1823 # @param f is the file name
1824 # @param auto_groups boolean parameter for creating/not creating
1825 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1826 # the typical use is auto_groups=false.
1827 # @ingroup l2_impexp
1828 def ExportSAUV(self, f, auto_groups=0):
1829 self.mesh.ExportSAUV(f, auto_groups)
1831 ## Export the mesh in a file in DAT format
1832 # @param f the file name
1833 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1834 # @ingroup l2_impexp
1835 def ExportDAT(self, f, meshPart=None):
1837 unRegister = genObjUnRegister()
1838 if isinstance( meshPart, list ):
1839 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1840 unRegister.set( meshPart )
1841 self.mesh.ExportPartToDAT( meshPart, f )
1843 self.mesh.ExportDAT(f)
1845 ## Export the mesh in a file in UNV format
1846 # @param f the file name
1847 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1848 # @ingroup l2_impexp
1849 def ExportUNV(self, f, meshPart=None):
1851 unRegister = genObjUnRegister()
1852 if isinstance( meshPart, list ):
1853 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1854 unRegister.set( meshPart )
1855 self.mesh.ExportPartToUNV( meshPart, f )
1857 self.mesh.ExportUNV(f)
1859 ## Export the mesh in a file in STL format
1860 # @param f the file name
1861 # @param ascii defines the file encoding
1862 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1863 # @ingroup l2_impexp
1864 def ExportSTL(self, f, ascii=1, meshPart=None):
1866 unRegister = genObjUnRegister()
1867 if isinstance( meshPart, list ):
1868 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1869 unRegister.set( meshPart )
1870 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1872 self.mesh.ExportSTL(f, ascii)
1874 ## Export the mesh in a file in CGNS format
1875 # @param f is the file name
1876 # @param overwrite boolean parameter for overwriting/not overwriting the file
1877 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1878 # @ingroup l2_impexp
1879 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1880 unRegister = genObjUnRegister()
1881 if isinstance( meshPart, list ):
1882 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1883 unRegister.set( meshPart )
1884 if isinstance( meshPart, Mesh ):
1885 meshPart = meshPart.mesh
1887 meshPart = self.mesh
1888 self.mesh.ExportCGNS(meshPart, f, overwrite)
1890 ## Export the mesh in a file in GMF format.
1891 # GMF files must have .mesh extension for the ASCII format and .meshb for
1892 # the bynary format. Other extensions are not allowed.
1893 # @param f is the file name
1894 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1895 # @ingroup l2_impexp
1896 def ExportGMF(self, f, meshPart=None):
1897 unRegister = genObjUnRegister()
1898 if isinstance( meshPart, list ):
1899 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1900 unRegister.set( meshPart )
1901 if isinstance( meshPart, Mesh ):
1902 meshPart = meshPart.mesh
1904 meshPart = self.mesh
1905 self.mesh.ExportGMF(meshPart, f, True)
1907 ## Deprecated, used only for compatibility! Please, use ExportMED() method instead.
1908 # Export the mesh in a file in MED format
1909 # allowing to overwrite the file if it exists or add the exported data to its contents
1910 # @param f the file name
1911 # @param version MED format version (MED_V2_1 or MED_V2_2,
1912 # the latter meaning any current version). The parameter is
1913 # obsolete since MED_V2_1 is no longer supported.
1914 # @param opt boolean parameter for creating/not creating
1915 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1916 # @param overwrite boolean parameter for overwriting/not overwriting the file
1917 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1918 # - 1D if all mesh nodes lie on OX coordinate axis, or
1919 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1920 # - 3D in the rest cases.<br>
1921 # If @a autoDimension is @c False, the space dimension is always 3.
1922 # @ingroup l2_impexp
1923 def ExportToMED(self, f, version=MED_V2_2, opt=0, overwrite=1, autoDimension=True):
1924 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1926 # Operations with groups:
1927 # ----------------------
1929 ## Create an empty mesh group
1930 # @param elementType the type of elements in the group; either of
1931 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1932 # @param name the name of the mesh group
1933 # @return SMESH_Group
1934 # @ingroup l2_grps_create
1935 def CreateEmptyGroup(self, elementType, name):
1936 return self.mesh.CreateGroup(elementType, name)
1938 ## Create a mesh group based on the geometric object \a grp
1939 # and gives a \a name, \n if this parameter is not defined
1940 # the name is the same as the geometric group name \n
1941 # Note: Works like GroupOnGeom().
1942 # @param grp a geometric group, a vertex, an edge, a face or a solid
1943 # @param name the name of the mesh group
1944 # @return SMESH_GroupOnGeom
1945 # @ingroup l2_grps_create
1946 def Group(self, grp, name=""):
1947 return self.GroupOnGeom(grp, name)
1949 ## Create a mesh group based on the geometrical object \a grp
1950 # and gives a \a name, \n if this parameter is not defined
1951 # the name is the same as the geometrical group name
1952 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1953 # @param name the name of the mesh group
1954 # @param typ the type of elements in the group; either of
1955 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
1956 # automatically detected by the type of the geometry
1957 # @return SMESH_GroupOnGeom
1958 # @ingroup l2_grps_create
1959 def GroupOnGeom(self, grp, name="", typ=None):
1960 AssureGeomPublished( self, grp, name )
1962 name = grp.GetName()
1964 typ = self._groupTypeFromShape( grp )
1965 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1967 ## Pivate method to get a type of group on geometry
1968 def _groupTypeFromShape( self, shape ):
1969 tgeo = str(shape.GetShapeType())
1970 if tgeo == "VERTEX":
1972 elif tgeo == "EDGE":
1974 elif tgeo == "FACE" or tgeo == "SHELL":
1976 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1978 elif tgeo == "COMPOUND":
1979 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1981 raise ValueError("_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape))
1982 return self._groupTypeFromShape( sub[0] )
1984 raise ValueError("_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape))
1987 ## Create a mesh group with given \a name based on the \a filter which
1988 ## is a special type of group dynamically updating it's contents during
1989 ## mesh modification
1990 # @param typ the type of elements in the group; either of
1991 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1992 # @param name the name of the mesh group
1993 # @param filter the filter defining group contents
1994 # @return SMESH_GroupOnFilter
1995 # @ingroup l2_grps_create
1996 def GroupOnFilter(self, typ, name, filter):
1997 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1999 ## Create a mesh group by the given ids of elements
2000 # @param groupName the name of the mesh group
2001 # @param elementType the type of elements in the group; either of
2002 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2003 # @param elemIDs either the list of ids, group, sub-mesh, or filter
2004 # @return SMESH_Group
2005 # @ingroup l2_grps_create
2006 def MakeGroupByIds(self, groupName, elementType, elemIDs):
2007 group = self.mesh.CreateGroup(elementType, groupName)
2008 if hasattr( elemIDs, "GetIDs" ):
2009 if hasattr( elemIDs, "SetMesh" ):
2010 elemIDs.SetMesh( self.GetMesh() )
2011 group.AddFrom( elemIDs )
2016 ## Create a mesh group by the given conditions
2017 # @param groupName the name of the mesh group
2018 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2019 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
2020 # Type SMESH.FunctorType._items in the Python Console to see all values.
2021 # Note that the items starting from FT_LessThan are not suitable for CritType.
2022 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
2023 # @param Threshold the threshold value (range of ids as string, shape, numeric)
2024 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2025 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2026 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2027 # @return SMESH_GroupOnFilter
2028 # @ingroup l2_grps_create
2032 CritType=FT_Undefined,
2035 UnaryOp=FT_Undefined,
2037 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2038 group = self.MakeGroupByCriterion(groupName, aCriterion)
2041 ## Create a mesh group by the given criterion
2042 # @param groupName the name of the mesh group
2043 # @param Criterion the instance of Criterion class
2044 # @return SMESH_GroupOnFilter
2045 # @ingroup l2_grps_create
2046 def MakeGroupByCriterion(self, groupName, Criterion):
2047 return self.MakeGroupByCriteria( groupName, [Criterion] )
2049 ## Create a mesh group by the given criteria (list of criteria)
2050 # @param groupName the name of the mesh group
2051 # @param theCriteria the list of criteria
2052 # @param binOp binary operator used when binary operator of criteria is undefined
2053 # @return SMESH_GroupOnFilter
2054 # @ingroup l2_grps_create
2055 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2056 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2057 group = self.MakeGroupByFilter(groupName, aFilter)
2060 ## Create a mesh group by the given filter
2061 # @param groupName the name of the mesh group
2062 # @param theFilter the instance of Filter class
2063 # @return SMESH_GroupOnFilter
2064 # @ingroup l2_grps_create
2065 def MakeGroupByFilter(self, groupName, theFilter):
2066 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2067 #theFilter.SetMesh( self.mesh )
2068 #group.AddFrom( theFilter )
2069 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2073 # @ingroup l2_grps_delete
2074 def RemoveGroup(self, group):
2075 self.mesh.RemoveGroup(group)
2077 ## Remove a group with its contents
2078 # @ingroup l2_grps_delete
2079 def RemoveGroupWithContents(self, group):
2080 self.mesh.RemoveGroupWithContents(group)
2082 ## Get the list of groups existing in the mesh in the order
2083 # of creation (starting from the oldest one)
2084 # @param elemType type of elements the groups contain; either of
2085 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2086 # by default groups of elements of all types are returned
2087 # @return a sequence of SMESH_GroupBase
2088 # @ingroup l2_grps_create
2089 def GetGroups(self, elemType = SMESH.ALL):
2090 groups = self.mesh.GetGroups()
2091 if elemType == SMESH.ALL:
2095 if g.GetType() == elemType:
2096 typedGroups.append( g )
2101 ## Get the number of groups existing in the mesh
2102 # @return the quantity of groups as an integer value
2103 # @ingroup l2_grps_create
2105 return self.mesh.NbGroups()
2107 ## Get the list of names of groups existing in the mesh
2108 # @return list of strings
2109 # @ingroup l2_grps_create
2110 def GetGroupNames(self):
2111 groups = self.GetGroups()
2113 for group in groups:
2114 names.append(group.GetName())
2117 ## Find groups by name and type
2118 # @param name name of the group of interest
2119 # @param elemType type of elements the groups contain; either of
2120 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2121 # by default one group of any type of elements is returned
2122 # if elemType == SMESH.ALL then all groups of any type are returned
2123 # @return a list of SMESH_GroupBase's
2124 # @ingroup l2_grps_create
2125 def GetGroupByName(self, name, elemType = None):
2127 for group in self.GetGroups():
2128 if group.GetName() == name:
2129 if elemType is None:
2131 if ( elemType == SMESH.ALL or
2132 group.GetType() == elemType ):
2133 groups.append( group )
2136 ## Produce a union of two groups.
2137 # A new group is created. All mesh elements that are
2138 # present in the initial groups are added to the new one
2139 # @return an instance of SMESH_Group
2140 # @ingroup l2_grps_operon
2141 def UnionGroups(self, group1, group2, name):
2142 return self.mesh.UnionGroups(group1, group2, name)
2144 ## Produce a union list of groups.
2145 # New group is created. All mesh elements that are present in
2146 # initial groups are added to the new one
2147 # @return an instance of SMESH_Group
2148 # @ingroup l2_grps_operon
2149 def UnionListOfGroups(self, groups, name):
2150 return self.mesh.UnionListOfGroups(groups, name)
2152 ## Prodice an intersection of two groups.
2153 # A new group is created. All mesh elements that are common
2154 # for the two initial groups are added to the new one.
2155 # @return an instance of SMESH_Group
2156 # @ingroup l2_grps_operon
2157 def IntersectGroups(self, group1, group2, name):
2158 return self.mesh.IntersectGroups(group1, group2, name)
2160 ## Produce an intersection of groups.
2161 # New group is created. All mesh elements that are present in all
2162 # initial groups simultaneously are added to the new one
2163 # @return an instance of SMESH_Group
2164 # @ingroup l2_grps_operon
2165 def IntersectListOfGroups(self, groups, name):
2166 return self.mesh.IntersectListOfGroups(groups, name)
2168 ## Produce a cut of two groups.
2169 # A new group is created. All mesh elements that are present in
2170 # the main group but are not present in the tool group are added to the new one
2171 # @return an instance of SMESH_Group
2172 # @ingroup l2_grps_operon
2173 def CutGroups(self, main_group, tool_group, name):
2174 return self.mesh.CutGroups(main_group, tool_group, name)
2176 ## Produce a cut of groups.
2177 # A new group is created. All mesh elements that are present in main groups
2178 # but do not present in tool groups are added to the new one
2179 # @return an instance of SMESH_Group
2180 # @ingroup l2_grps_operon
2181 def CutListOfGroups(self, main_groups, tool_groups, name):
2182 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2185 # Create a standalone group of entities basing on nodes of other groups.
2186 # \param groups - list of reference groups, sub-meshes or filters, of any type.
2187 # \param elemType - a type of elements to include to the new group; either of
2188 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2189 # \param name - a name of the new group.
2190 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2191 # basing on number of element nodes common with reference \a groups.
2192 # Meaning of possible values are:
2193 # - SMESH.ALL_NODES - include if all nodes are common,
2194 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2195 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2196 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2197 # \param underlyingOnly - if \c True (default), an element is included to the
2198 # new group provided that it is based on nodes of an element of \a groups;
2199 # in this case the reference \a groups are supposed to be of higher dimension
2200 # than \a elemType, which can be useful for example to get all faces lying on
2201 # volumes of the reference \a groups.
2202 # @return an instance of SMESH_Group
2203 # @ingroup l2_grps_operon
2204 def CreateDimGroup(self, groups, elemType, name,
2205 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2206 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2208 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2211 ## Convert group on geom into standalone group
2212 # @ingroup l2_grps_operon
2213 def ConvertToStandalone(self, group):
2214 return self.mesh.ConvertToStandalone(group)
2216 # Get some info about mesh:
2217 # ------------------------
2219 ## Return the log of nodes and elements added or removed
2220 # since the previous clear of the log.
2221 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2222 # @return list of log_block structures:
2227 # @ingroup l1_auxiliary
2228 def GetLog(self, clearAfterGet):
2229 return self.mesh.GetLog(clearAfterGet)
2231 ## Clear the log of nodes and elements added or removed since the previous
2232 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2233 # @ingroup l1_auxiliary
2235 self.mesh.ClearLog()
2237 ## Toggle auto color mode on the object.
2238 # @param theAutoColor the flag which toggles auto color mode.
2240 # If switched on, a default color of a new group in Create Group dialog is chosen randomly.
2241 # @ingroup l1_grouping
2242 def SetAutoColor(self, theAutoColor):
2243 self.mesh.SetAutoColor(theAutoColor)
2245 ## Get flag of object auto color mode.
2246 # @return True or False
2247 # @ingroup l1_grouping
2248 def GetAutoColor(self):
2249 return self.mesh.GetAutoColor()
2251 ## Get the internal ID
2252 # @return integer value, which is the internal Id of the mesh
2253 # @ingroup l1_auxiliary
2255 return self.mesh.GetId()
2258 # @return integer value, which is the study Id of the mesh
2259 # @ingroup l1_auxiliary
2260 def GetStudyId(self):
2261 return self.mesh.GetStudyId()
2263 ## Check the group names for duplications.
2264 # Consider the maximum group name length stored in MED file.
2265 # @return True or False
2266 # @ingroup l1_grouping
2267 def HasDuplicatedGroupNamesMED(self):
2268 return self.mesh.HasDuplicatedGroupNamesMED()
2270 ## Obtain the mesh editor tool
2271 # @return an instance of SMESH_MeshEditor
2272 # @ingroup l1_modifying
2273 def GetMeshEditor(self):
2276 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2277 # can be passed as argument to a method accepting mesh, group or sub-mesh
2278 # @param ids list of IDs
2279 # @param elemType type of elements; this parameter is used to distinguish
2280 # IDs of nodes from IDs of elements; by default ids are treated as
2281 # IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2282 # @return an instance of SMESH_IDSource
2283 # @warning call UnRegister() for the returned object as soon as it is no more useful:
2284 # idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2285 # mesh.DoSomething( idSrc )
2286 # idSrc.UnRegister()
2287 # @ingroup l1_auxiliary
2288 def GetIDSource(self, ids, elemType = SMESH.ALL):
2289 if isinstance( ids, int ):
2291 return self.editor.MakeIDSource(ids, elemType)
2294 # Get informations about mesh contents:
2295 # ------------------------------------
2297 ## Get the mesh stattistic
2298 # @return dictionary type element - count of elements
2299 # @ingroup l1_meshinfo
2300 def GetMeshInfo(self, obj = None):
2301 if not obj: obj = self.mesh
2302 return self.smeshpyD.GetMeshInfo(obj)
2304 ## Return the number of nodes in the mesh
2305 # @return an integer value
2306 # @ingroup l1_meshinfo
2308 return self.mesh.NbNodes()
2310 ## Return the number of elements in the mesh
2311 # @return an integer value
2312 # @ingroup l1_meshinfo
2313 def NbElements(self):
2314 return self.mesh.NbElements()
2316 ## Return the number of 0d elements in the mesh
2317 # @return an integer value
2318 # @ingroup l1_meshinfo
2319 def Nb0DElements(self):
2320 return self.mesh.Nb0DElements()
2322 ## Return the number of ball discrete elements in the mesh
2323 # @return an integer value
2324 # @ingroup l1_meshinfo
2326 return self.mesh.NbBalls()
2328 ## Return the number of edges in the mesh
2329 # @return an integer value
2330 # @ingroup l1_meshinfo
2332 return self.mesh.NbEdges()
2334 ## Return the number of edges with the given order in the mesh
2335 # @param elementOrder the order of elements:
2336 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2337 # @return an integer value
2338 # @ingroup l1_meshinfo
2339 def NbEdgesOfOrder(self, elementOrder):
2340 return self.mesh.NbEdgesOfOrder(elementOrder)
2342 ## Return the number of faces in the mesh
2343 # @return an integer value
2344 # @ingroup l1_meshinfo
2346 return self.mesh.NbFaces()
2348 ## Return the number of faces with the given order in the mesh
2349 # @param elementOrder the order of elements:
2350 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2351 # @return an integer value
2352 # @ingroup l1_meshinfo
2353 def NbFacesOfOrder(self, elementOrder):
2354 return self.mesh.NbFacesOfOrder(elementOrder)
2356 ## Return the number of triangles in the mesh
2357 # @return an integer value
2358 # @ingroup l1_meshinfo
2359 def NbTriangles(self):
2360 return self.mesh.NbTriangles()
2362 ## Return the number of triangles with the given order in the mesh
2363 # @param elementOrder is the order of elements:
2364 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2365 # @return an integer value
2366 # @ingroup l1_meshinfo
2367 def NbTrianglesOfOrder(self, elementOrder):
2368 return self.mesh.NbTrianglesOfOrder(elementOrder)
2370 ## Return the number of biquadratic triangles in the mesh
2371 # @return an integer value
2372 # @ingroup l1_meshinfo
2373 def NbBiQuadTriangles(self):
2374 return self.mesh.NbBiQuadTriangles()
2376 ## Return the number of quadrangles in the mesh
2377 # @return an integer value
2378 # @ingroup l1_meshinfo
2379 def NbQuadrangles(self):
2380 return self.mesh.NbQuadrangles()
2382 ## Return the number of quadrangles with the given order in the mesh
2383 # @param elementOrder the order of elements:
2384 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2385 # @return an integer value
2386 # @ingroup l1_meshinfo
2387 def NbQuadranglesOfOrder(self, elementOrder):
2388 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2390 ## Return the number of biquadratic quadrangles in the mesh
2391 # @return an integer value
2392 # @ingroup l1_meshinfo
2393 def NbBiQuadQuadrangles(self):
2394 return self.mesh.NbBiQuadQuadrangles()
2396 ## Return the number of polygons of given order in the mesh
2397 # @param elementOrder the order of elements:
2398 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2399 # @return an integer value
2400 # @ingroup l1_meshinfo
2401 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2402 return self.mesh.NbPolygonsOfOrder(elementOrder)
2404 ## Return the number of volumes in the mesh
2405 # @return an integer value
2406 # @ingroup l1_meshinfo
2407 def NbVolumes(self):
2408 return self.mesh.NbVolumes()
2410 ## Return the number of volumes with the given order in the mesh
2411 # @param elementOrder the order of elements:
2412 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2413 # @return an integer value
2414 # @ingroup l1_meshinfo
2415 def NbVolumesOfOrder(self, elementOrder):
2416 return self.mesh.NbVolumesOfOrder(elementOrder)
2418 ## Return the number of tetrahedrons in the mesh
2419 # @return an integer value
2420 # @ingroup l1_meshinfo
2422 return self.mesh.NbTetras()
2424 ## Return the number of tetrahedrons with the given order in the mesh
2425 # @param elementOrder the order of elements:
2426 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2427 # @return an integer value
2428 # @ingroup l1_meshinfo
2429 def NbTetrasOfOrder(self, elementOrder):
2430 return self.mesh.NbTetrasOfOrder(elementOrder)
2432 ## Return the number of hexahedrons in the mesh
2433 # @return an integer value
2434 # @ingroup l1_meshinfo
2436 return self.mesh.NbHexas()
2438 ## Return the number of hexahedrons with the given order in the mesh
2439 # @param elementOrder the order of elements:
2440 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2441 # @return an integer value
2442 # @ingroup l1_meshinfo
2443 def NbHexasOfOrder(self, elementOrder):
2444 return self.mesh.NbHexasOfOrder(elementOrder)
2446 ## Return the number of triquadratic hexahedrons in the mesh
2447 # @return an integer value
2448 # @ingroup l1_meshinfo
2449 def NbTriQuadraticHexas(self):
2450 return self.mesh.NbTriQuadraticHexas()
2452 ## Return the number of pyramids in the mesh
2453 # @return an integer value
2454 # @ingroup l1_meshinfo
2455 def NbPyramids(self):
2456 return self.mesh.NbPyramids()
2458 ## Return the number of pyramids 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 NbPyramidsOfOrder(self, elementOrder):
2464 return self.mesh.NbPyramidsOfOrder(elementOrder)
2466 ## Return the number of prisms in the mesh
2467 # @return an integer value
2468 # @ingroup l1_meshinfo
2470 return self.mesh.NbPrisms()
2472 ## Return the number of prisms with the given order in the mesh
2473 # @param elementOrder 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 NbPrismsOfOrder(self, elementOrder):
2478 return self.mesh.NbPrismsOfOrder(elementOrder)
2480 ## Return the number of hexagonal prisms in the mesh
2481 # @return an integer value
2482 # @ingroup l1_meshinfo
2483 def NbHexagonalPrisms(self):
2484 return self.mesh.NbHexagonalPrisms()
2486 ## Return the number of polyhedrons in the mesh
2487 # @return an integer value
2488 # @ingroup l1_meshinfo
2489 def NbPolyhedrons(self):
2490 return self.mesh.NbPolyhedrons()
2492 ## Return the number of submeshes in the mesh
2493 # @return an integer value
2494 # @ingroup l1_meshinfo
2495 def NbSubMesh(self):
2496 return self.mesh.NbSubMesh()
2498 ## Return the list of mesh elements IDs
2499 # @return the list of integer values
2500 # @ingroup l1_meshinfo
2501 def GetElementsId(self):
2502 return self.mesh.GetElementsId()
2504 ## Return the list of IDs of mesh elements with the given type
2505 # @param elementType the required type of elements, either of
2506 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2507 # @return list of integer values
2508 # @ingroup l1_meshinfo
2509 def GetElementsByType(self, elementType):
2510 return self.mesh.GetElementsByType(elementType)
2512 ## Return the list of mesh nodes IDs
2513 # @return the list of integer values
2514 # @ingroup l1_meshinfo
2515 def GetNodesId(self):
2516 return self.mesh.GetNodesId()
2518 # Get the information about mesh elements:
2519 # ------------------------------------
2521 ## Return the type of mesh element
2522 # @return the value from SMESH::ElementType enumeration
2523 # Type SMESH.ElementType._items in the Python Console to see all possible values.
2524 # @ingroup l1_meshinfo
2525 def GetElementType(self, id, iselem=True):
2526 return self.mesh.GetElementType(id, iselem)
2528 ## Return the geometric type of mesh element
2529 # @return the value from SMESH::EntityType enumeration
2530 # Type SMESH.EntityType._items in the Python Console to see all possible values.
2531 # @ingroup l1_meshinfo
2532 def GetElementGeomType(self, id):
2533 return self.mesh.GetElementGeomType(id)
2535 ## Return the shape type of mesh element
2536 # @return the value from SMESH::GeometryType enumeration.
2537 # Type SMESH.GeometryType._items in the Python Console to see all possible values.
2538 # @ingroup l1_meshinfo
2539 def GetElementShape(self, id):
2540 return self.mesh.GetElementShape(id)
2542 ## Return the list of submesh elements IDs
2543 # @param Shape a geom object(sub-shape)
2544 # Shape must be the sub-shape of a ShapeToMesh()
2545 # @return the list of integer values
2546 # @ingroup l1_meshinfo
2547 def GetSubMeshElementsId(self, Shape):
2548 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2549 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2552 return self.mesh.GetSubMeshElementsId(ShapeID)
2554 ## Return the list of submesh nodes IDs
2555 # @param Shape a geom object(sub-shape)
2556 # Shape must be the sub-shape of a ShapeToMesh()
2557 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2558 # @return the list of integer values
2559 # @ingroup l1_meshinfo
2560 def GetSubMeshNodesId(self, Shape, all):
2561 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2562 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2565 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2567 ## Return type of elements on given shape
2568 # @param Shape a geom object(sub-shape)
2569 # Shape must be a sub-shape of a ShapeToMesh()
2570 # @return element type
2571 # @ingroup l1_meshinfo
2572 def GetSubMeshElementType(self, Shape):
2573 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2574 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2577 return self.mesh.GetSubMeshElementType(ShapeID)
2579 ## Get the mesh description
2580 # @return string value
2581 # @ingroup l1_meshinfo
2583 return self.mesh.Dump()
2586 # Get the information about nodes and elements of a mesh by its IDs:
2587 # -----------------------------------------------------------
2589 ## Get XYZ coordinates of a node
2590 # \n If there is no nodes for the given ID - return an empty list
2591 # @return a list of double precision values
2592 # @ingroup l1_meshinfo
2593 def GetNodeXYZ(self, id):
2594 return self.mesh.GetNodeXYZ(id)
2596 ## Return list of IDs of inverse elements for the given node
2597 # \n If there is no node for the given ID - return an empty list
2598 # @return a list of integer values
2599 # @ingroup l1_meshinfo
2600 def GetNodeInverseElements(self, id):
2601 return self.mesh.GetNodeInverseElements(id)
2603 ## Return the position of a node on the shape
2604 # @return SMESH::NodePosition
2605 # @ingroup l1_meshinfo
2606 def GetNodePosition(self,NodeID):
2607 return self.mesh.GetNodePosition(NodeID)
2609 ## Return the position of an element on the shape
2610 # @return SMESH::ElementPosition
2611 # @ingroup l1_meshinfo
2612 def GetElementPosition(self,ElemID):
2613 return self.mesh.GetElementPosition(ElemID)
2615 ## Return the ID of the shape, on which the given node was generated.
2616 # @return an integer value > 0 or -1 if there is no node for the given
2617 # ID or the node is not assigned to any geometry
2618 # @ingroup l1_meshinfo
2619 def GetShapeID(self, id):
2620 return self.mesh.GetShapeID(id)
2622 ## Return the ID of the shape, on which the given element was generated.
2623 # @return an integer value > 0 or -1 if there is no element for the given
2624 # ID or the element is not assigned to any geometry
2625 # @ingroup l1_meshinfo
2626 def GetShapeIDForElem(self,id):
2627 return self.mesh.GetShapeIDForElem(id)
2629 ## Return the number of nodes of the given element
2630 # @return an integer value > 0 or -1 if there is no element for the given ID
2631 # @ingroup l1_meshinfo
2632 def GetElemNbNodes(self, id):
2633 return self.mesh.GetElemNbNodes(id)
2635 ## Return the node ID the given (zero based) index for the given element
2636 # \n If there is no element for the given ID - return -1
2637 # \n If there is no node for the given index - return -2
2638 # @return an integer value
2639 # @ingroup l1_meshinfo
2640 def GetElemNode(self, id, index):
2641 return self.mesh.GetElemNode(id, index)
2643 ## Return the IDs of nodes of the given element
2644 # @return a list of integer values
2645 # @ingroup l1_meshinfo
2646 def GetElemNodes(self, id):
2647 return self.mesh.GetElemNodes(id)
2649 ## Return true if the given node is the medium node in the given quadratic element
2650 # @ingroup l1_meshinfo
2651 def IsMediumNode(self, elementID, nodeID):
2652 return self.mesh.IsMediumNode(elementID, nodeID)
2654 ## Return true if the given node is the medium node in one of quadratic elements
2655 # @param nodeID ID of the node
2656 # @param elementType the type of elements to check a state of the node, either of
2657 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2658 # @ingroup l1_meshinfo
2659 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2660 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2662 ## Return the number of edges for the given element
2663 # @ingroup l1_meshinfo
2664 def ElemNbEdges(self, id):
2665 return self.mesh.ElemNbEdges(id)
2667 ## Return the number of faces for the given element
2668 # @ingroup l1_meshinfo
2669 def ElemNbFaces(self, id):
2670 return self.mesh.ElemNbFaces(id)
2672 ## Return nodes of given face (counted from zero) for given volumic element.
2673 # @ingroup l1_meshinfo
2674 def GetElemFaceNodes(self,elemId, faceIndex):
2675 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2677 ## Return three components of normal of given mesh face
2678 # (or an empty array in KO case)
2679 # @ingroup l1_meshinfo
2680 def GetFaceNormal(self, faceId, normalized=False):
2681 return self.mesh.GetFaceNormal(faceId,normalized)
2683 ## Return an element based on all given nodes.
2684 # @ingroup l1_meshinfo
2685 def FindElementByNodes(self,nodes):
2686 return self.mesh.FindElementByNodes(nodes)
2688 ## Return true if the given element is a polygon
2689 # @ingroup l1_meshinfo
2690 def IsPoly(self, id):
2691 return self.mesh.IsPoly(id)
2693 ## Return true if the given element is quadratic
2694 # @ingroup l1_meshinfo
2695 def IsQuadratic(self, id):
2696 return self.mesh.IsQuadratic(id)
2698 ## Return diameter of a ball discrete element or zero in case of an invalid \a id
2699 # @ingroup l1_meshinfo
2700 def GetBallDiameter(self, id):
2701 return self.mesh.GetBallDiameter(id)
2703 ## Return XYZ coordinates of the barycenter of the given element
2704 # \n If there is no element for the given ID - return an empty list
2705 # @return a list of three double values
2706 # @ingroup l1_meshinfo
2707 def BaryCenter(self, id):
2708 return self.mesh.BaryCenter(id)
2710 ## Pass mesh elements through the given filter and return IDs of fitting elements
2711 # @param theFilter SMESH_Filter
2712 # @return a list of ids
2713 # @ingroup l1_controls
2714 def GetIdsFromFilter(self, theFilter):
2715 theFilter.SetMesh( self.mesh )
2716 return theFilter.GetIDs()
2718 # Get mesh measurements information:
2719 # ------------------------------------
2721 ## Verify whether a 2D mesh element has free edges (edges connected to one face only)\n
2722 # Return a list of special structures (borders).
2723 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2724 # @ingroup l1_measurements
2725 def GetFreeBorders(self):
2726 aFilterMgr = self.smeshpyD.CreateFilterManager()
2727 aPredicate = aFilterMgr.CreateFreeEdges()
2728 aPredicate.SetMesh(self.mesh)
2729 aBorders = aPredicate.GetBorders()
2730 aFilterMgr.UnRegister()
2733 ## Get minimum distance between two nodes, elements or distance to the origin
2734 # @param id1 first node/element id
2735 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2736 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2737 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2738 # @return minimum distance value
2739 # @sa GetMinDistance()
2740 # @ingroup l1_measurements
2741 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2742 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2743 return aMeasure.value
2745 ## Get measure structure specifying minimum distance data between two objects
2746 # @param id1 first node/element id
2747 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2748 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2749 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2750 # @return Measure structure
2752 # @ingroup l1_measurements
2753 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2755 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2757 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2760 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2762 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2767 aMeasurements = self.smeshpyD.CreateMeasurements()
2768 aMeasure = aMeasurements.MinDistance(id1, id2)
2769 genObjUnRegister([aMeasurements,id1, id2])
2772 ## Get bounding box of the specified object(s)
2773 # @param objects single source object or list of source objects or list of nodes/elements IDs
2774 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2775 # @c False specifies that @a objects are nodes
2776 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2777 # @sa GetBoundingBox()
2778 # @ingroup l1_measurements
2779 def BoundingBox(self, objects=None, isElem=False):
2780 result = self.GetBoundingBox(objects, isElem)
2784 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2787 ## Get measure structure specifying bounding box data of the specified object(s)
2788 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2789 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2790 # @c False specifies that @a objects are nodes
2791 # @return Measure structure
2793 # @ingroup l1_measurements
2794 def GetBoundingBox(self, IDs=None, isElem=False):
2797 elif isinstance(IDs, tuple):
2799 if not isinstance(IDs, list):
2801 if len(IDs) > 0 and isinstance(IDs[0], int):
2804 unRegister = genObjUnRegister()
2806 if isinstance(o, Mesh):
2807 srclist.append(o.mesh)
2808 elif hasattr(o, "_narrow"):
2809 src = o._narrow(SMESH.SMESH_IDSource)
2810 if src: srclist.append(src)
2812 elif isinstance(o, list):
2814 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2816 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2817 unRegister.set( srclist[-1] )
2820 aMeasurements = self.smeshpyD.CreateMeasurements()
2821 unRegister.set( aMeasurements )
2822 aMeasure = aMeasurements.BoundingBox(srclist)
2825 # Mesh edition (SMESH_MeshEditor functionality):
2826 # ---------------------------------------------
2828 ## Remove the elements from the mesh by ids
2829 # @param IDsOfElements is a list of ids of elements to remove
2830 # @return True or False
2831 # @ingroup l2_modif_del
2832 def RemoveElements(self, IDsOfElements):
2833 return self.editor.RemoveElements(IDsOfElements)
2835 ## Remove nodes from mesh by ids
2836 # @param IDsOfNodes is a list of ids of nodes to remove
2837 # @return True or False
2838 # @ingroup l2_modif_del
2839 def RemoveNodes(self, IDsOfNodes):
2840 return self.editor.RemoveNodes(IDsOfNodes)
2842 ## Remove all orphan (free) nodes from mesh
2843 # @return number of the removed nodes
2844 # @ingroup l2_modif_del
2845 def RemoveOrphanNodes(self):
2846 return self.editor.RemoveOrphanNodes()
2848 ## Add a node to the mesh by coordinates
2849 # @return Id of the new node
2850 # @ingroup l2_modif_add
2851 def AddNode(self, x, y, z):
2852 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2853 if hasVars: self.mesh.SetParameters(Parameters)
2854 return self.editor.AddNode( x, y, z)
2856 ## Create a 0D element on a node with given number.
2857 # @param IDOfNode the ID of node for creation of the element.
2858 # @param DuplicateElements to add one more 0D element to a node or not
2859 # @return the Id of the new 0D element
2860 # @ingroup l2_modif_add
2861 def Add0DElement( self, IDOfNode, DuplicateElements=True ):
2862 return self.editor.Add0DElement( IDOfNode, DuplicateElements )
2864 ## Create 0D elements on all nodes of the given elements except those
2865 # nodes on which a 0D element already exists.
2866 # @param theObject an object on whose nodes 0D elements will be created.
2867 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2868 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2869 # @param theGroupName optional name of a group to add 0D elements created
2870 # and/or found on nodes of \a theObject.
2871 # @param DuplicateElements to add one more 0D element to a node or not
2872 # @return an object (a new group or a temporary SMESH_IDSource) holding
2873 # IDs of new and/or found 0D elements. IDs of 0D elements
2874 # can be retrieved from the returned object by calling GetIDs()
2875 # @ingroup l2_modif_add
2876 def Add0DElementsToAllNodes(self, theObject, theGroupName="", DuplicateElements=False):
2877 unRegister = genObjUnRegister()
2878 if isinstance( theObject, Mesh ):
2879 theObject = theObject.GetMesh()
2880 elif isinstance( theObject, list ):
2881 theObject = self.GetIDSource( theObject, SMESH.ALL )
2882 unRegister.set( theObject )
2883 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName, DuplicateElements )
2885 ## Create a ball element on a node with given ID.
2886 # @param IDOfNode the ID of node for creation of the element.
2887 # @param diameter the bal diameter.
2888 # @return the Id of the new ball element
2889 # @ingroup l2_modif_add
2890 def AddBall(self, IDOfNode, diameter):
2891 return self.editor.AddBall( IDOfNode, diameter )
2893 ## Create a linear or quadratic edge (this is determined
2894 # by the number of given nodes).
2895 # @param IDsOfNodes the list of node IDs for creation of the element.
2896 # The order of nodes in this list should correspond to the description
2897 # of MED. \n This description is located by the following link:
2898 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2899 # @return the Id of the new edge
2900 # @ingroup l2_modif_add
2901 def AddEdge(self, IDsOfNodes):
2902 return self.editor.AddEdge(IDsOfNodes)
2904 ## Create a linear or quadratic face (this is determined
2905 # by the number of given nodes).
2906 # @param IDsOfNodes the list of node IDs for creation of the element.
2907 # The order of nodes in this list should correspond to the description
2908 # of MED. \n This description is located by the following link:
2909 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2910 # @return the Id of the new face
2911 # @ingroup l2_modif_add
2912 def AddFace(self, IDsOfNodes):
2913 return self.editor.AddFace(IDsOfNodes)
2915 ## Add a polygonal face to the mesh by the list of node IDs
2916 # @param IdsOfNodes the list of node IDs for creation of the element.
2917 # @return the Id of the new face
2918 # @ingroup l2_modif_add
2919 def AddPolygonalFace(self, IdsOfNodes):
2920 return self.editor.AddPolygonalFace(IdsOfNodes)
2922 ## Add a quadratic polygonal face to the mesh by the list of node IDs
2923 # @param IdsOfNodes the list of node IDs for creation of the element;
2924 # corner nodes follow first.
2925 # @return the Id of the new face
2926 # @ingroup l2_modif_add
2927 def AddQuadPolygonalFace(self, IdsOfNodes):
2928 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
2930 ## Create both simple and quadratic volume (this is determined
2931 # by the number of given nodes).
2932 # @param IDsOfNodes the list of node IDs for creation of the element.
2933 # The order of nodes in this list should correspond to the description
2934 # of MED. \n This description is located by the following link:
2935 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2936 # @return the Id of the new volumic element
2937 # @ingroup l2_modif_add
2938 def AddVolume(self, IDsOfNodes):
2939 return self.editor.AddVolume(IDsOfNodes)
2941 ## Create a volume of many faces, giving nodes for each face.
2942 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2943 # @param Quantities the list of integer values, Quantities[i]
2944 # gives the quantity of nodes in face number i.
2945 # @return the Id of the new volumic element
2946 # @ingroup l2_modif_add
2947 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2948 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2950 ## Create a volume of many faces, giving the IDs of the existing faces.
2951 # @param IdsOfFaces the list of face IDs for volume creation.
2953 # Note: The created volume will refer only to the nodes
2954 # of the given faces, not to the faces themselves.
2955 # @return the Id of the new volumic element
2956 # @ingroup l2_modif_add
2957 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2958 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2961 ## @brief Binds a node to a vertex
2962 # @param NodeID a node ID
2963 # @param Vertex a vertex or vertex ID
2964 # @return True if succeed else raises an exception
2965 # @ingroup l2_modif_add
2966 def SetNodeOnVertex(self, NodeID, Vertex):
2967 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2968 VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
2972 self.editor.SetNodeOnVertex(NodeID, VertexID)
2973 except SALOME.SALOME_Exception as inst:
2974 raise ValueError(inst.details.text)
2978 ## @brief Stores the node position on an edge
2979 # @param NodeID a node ID
2980 # @param Edge an edge or edge ID
2981 # @param paramOnEdge a parameter on the edge where the node is located
2982 # @return True if succeed else raises an exception
2983 # @ingroup l2_modif_add
2984 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2985 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2986 EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
2990 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2991 except SALOME.SALOME_Exception as inst:
2992 raise ValueError(inst.details.text)
2995 ## @brief Stores node position on a face
2996 # @param NodeID a node ID
2997 # @param Face a face or face ID
2998 # @param u U parameter on the face where the node is located
2999 # @param v V parameter on the face where the node is located
3000 # @return True if succeed else raises an exception
3001 # @ingroup l2_modif_add
3002 def SetNodeOnFace(self, NodeID, Face, u, v):
3003 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
3004 FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
3008 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
3009 except SALOME.SALOME_Exception as inst:
3010 raise ValueError(inst.details.text)
3013 ## @brief Binds a node to a solid
3014 # @param NodeID a node ID
3015 # @param Solid a solid or solid ID
3016 # @return True if succeed else raises an exception
3017 # @ingroup l2_modif_add
3018 def SetNodeInVolume(self, NodeID, Solid):
3019 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
3020 SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
3024 self.editor.SetNodeInVolume(NodeID, SolidID)
3025 except SALOME.SALOME_Exception as inst:
3026 raise ValueError(inst.details.text)
3029 ## @brief Bind an element to a shape
3030 # @param ElementID an element ID
3031 # @param Shape a shape or shape ID
3032 # @return True if succeed else raises an exception
3033 # @ingroup l2_modif_add
3034 def SetMeshElementOnShape(self, ElementID, Shape):
3035 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
3036 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3040 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
3041 except SALOME.SALOME_Exception as inst:
3042 raise ValueError(inst.details.text)
3046 ## Move the node with the given id
3047 # @param NodeID the id of the node
3048 # @param x a new X coordinate
3049 # @param y a new Y coordinate
3050 # @param z a new Z coordinate
3051 # @return True if succeed else False
3052 # @ingroup l2_modif_edit
3053 def MoveNode(self, NodeID, x, y, z):
3054 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3055 if hasVars: self.mesh.SetParameters(Parameters)
3056 return self.editor.MoveNode(NodeID, x, y, z)
3058 ## Find the node closest to a point and moves it to a point location
3059 # @param x the X coordinate of a point
3060 # @param y the Y coordinate of a point
3061 # @param z the Z coordinate of a point
3062 # @param NodeID if specified (>0), the node with this ID is moved,
3063 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
3064 # @return the ID of a node
3065 # @ingroup l2_modif_edit
3066 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3067 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3068 if hasVars: self.mesh.SetParameters(Parameters)
3069 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3071 ## Find the node closest to a point
3072 # @param x the X coordinate of a point
3073 # @param y the Y coordinate of a point
3074 # @param z the Z coordinate of a point
3075 # @return the ID of a node
3076 # @ingroup l1_meshinfo
3077 def FindNodeClosestTo(self, x, y, z):
3078 #preview = self.mesh.GetMeshEditPreviewer()
3079 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3080 return self.editor.FindNodeClosestTo(x, y, z)
3082 ## Find the elements where a point lays IN or ON
3083 # @param x the X coordinate of a point
3084 # @param y the Y coordinate of a point
3085 # @param z the Z coordinate of a point
3086 # @param elementType type of elements to find; either of
3087 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3088 # means elements of any type excluding nodes, discrete and 0D elements.
3089 # @param meshPart a part of mesh (group, sub-mesh) to search within
3090 # @return list of IDs of found elements
3091 # @ingroup l1_meshinfo
3092 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3094 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
3096 return self.editor.FindElementsByPoint(x, y, z, elementType)
3098 ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
3099 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
3100 # UNKNOWN state means that either mesh is wrong or the analysis fails.
3101 # @ingroup l1_meshinfo
3102 def GetPointState(self, x, y, z):
3103 return self.editor.GetPointState(x, y, z)
3105 ## Find the node closest to a point and moves it to a point location
3106 # @param x the X coordinate of a point
3107 # @param y the Y coordinate of a point
3108 # @param z the Z coordinate of a point
3109 # @return the ID of a moved node
3110 # @ingroup l2_modif_edit
3111 def MeshToPassThroughAPoint(self, x, y, z):
3112 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3114 ## Replace two neighbour triangles sharing Node1-Node2 link
3115 # with the triangles built on the same 4 nodes but having other common link.
3116 # @param NodeID1 the ID of the first node
3117 # @param NodeID2 the ID of the second node
3118 # @return false if proper faces were not found
3119 # @ingroup l2_modif_cutquadr
3120 def InverseDiag(self, NodeID1, NodeID2):
3121 return self.editor.InverseDiag(NodeID1, NodeID2)
3123 ## Replace two neighbour triangles sharing Node1-Node2 link
3124 # with a quadrangle built on the same 4 nodes.
3125 # @param NodeID1 the ID of the first node
3126 # @param NodeID2 the ID of the second node
3127 # @return false if proper faces were not found
3128 # @ingroup l2_modif_unitetri
3129 def DeleteDiag(self, NodeID1, NodeID2):
3130 return self.editor.DeleteDiag(NodeID1, NodeID2)
3132 ## Reorient elements by ids
3133 # @param IDsOfElements if undefined reorients all mesh elements
3134 # @return True if succeed else False
3135 # @ingroup l2_modif_changori
3136 def Reorient(self, IDsOfElements=None):
3137 if IDsOfElements == None:
3138 IDsOfElements = self.GetElementsId()
3139 return self.editor.Reorient(IDsOfElements)
3141 ## Reorient all elements of the object
3142 # @param theObject mesh, submesh or group
3143 # @return True if succeed else False
3144 # @ingroup l2_modif_changori
3145 def ReorientObject(self, theObject):
3146 if ( isinstance( theObject, Mesh )):
3147 theObject = theObject.GetMesh()
3148 return self.editor.ReorientObject(theObject)
3150 ## Reorient faces contained in \a the2DObject.
3151 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3152 # @param theDirection is a desired direction of normal of \a theFace.
3153 # It can be either a GEOM vector or a list of coordinates [x,y,z].
3154 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3155 # compared with theDirection. It can be either ID of face or a point
3156 # by which the face will be found. The point can be given as either
3157 # a GEOM vertex or a list of point coordinates.
3158 # @return number of reoriented faces
3159 # @ingroup l2_modif_changori
3160 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3161 unRegister = genObjUnRegister()
3163 if isinstance( the2DObject, Mesh ):
3164 the2DObject = the2DObject.GetMesh()
3165 if isinstance( the2DObject, list ):
3166 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3167 unRegister.set( the2DObject )
3168 # check theDirection
3169 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3170 theDirection = self.smeshpyD.GetDirStruct( theDirection )
3171 if isinstance( theDirection, list ):
3172 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
3173 # prepare theFace and thePoint
3174 theFace = theFaceOrPoint
3175 thePoint = PointStruct(0,0,0)
3176 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3177 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3179 if isinstance( theFaceOrPoint, list ):
3180 thePoint = PointStruct( *theFaceOrPoint )
3182 if isinstance( theFaceOrPoint, PointStruct ):
3183 thePoint = theFaceOrPoint
3185 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3187 ## Reorient faces according to adjacent volumes.
3188 # @param the2DObject is a mesh, sub-mesh, group or list of
3189 # either IDs of faces or face groups.
3190 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3191 # @param theOutsideNormal to orient faces to have their normals
3192 # pointing either \a outside or \a inside the adjacent volumes.
3193 # @return number of reoriented faces.
3194 # @ingroup l2_modif_changori
3195 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3196 unRegister = genObjUnRegister()
3198 if not isinstance( the2DObject, list ):
3199 the2DObject = [ the2DObject ]
3200 elif the2DObject and isinstance( the2DObject[0], int ):
3201 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3202 unRegister.set( the2DObject )
3203 the2DObject = [ the2DObject ]
3204 for i,obj2D in enumerate( the2DObject ):
3205 if isinstance( obj2D, Mesh ):
3206 the2DObject[i] = obj2D.GetMesh()
3207 if isinstance( obj2D, list ):
3208 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3209 unRegister.set( the2DObject[i] )
3211 if isinstance( the3DObject, Mesh ):
3212 the3DObject = the3DObject.GetMesh()
3213 if isinstance( the3DObject, list ):
3214 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3215 unRegister.set( the3DObject )
3216 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3218 ## Fuse the neighbouring triangles into quadrangles.
3219 # @param IDsOfElements The triangles to be fused.
3220 # @param theCriterion a numerical functor, in terms of enum SMESH.FunctorType, used to
3221 # applied to possible quadrangles to choose a neighbour to fuse with.
3222 # Type SMESH.FunctorType._items in the Python Console to see all items.
3223 # Note that not all items correspond to numerical functors.
3224 # @param MaxAngle is the maximum angle between element normals at which the fusion
3225 # is still performed; theMaxAngle is mesured in radians.
3226 # Also it could be a name of variable which defines angle in degrees.
3227 # @return TRUE in case of success, FALSE otherwise.
3228 # @ingroup l2_modif_unitetri
3229 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3230 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3231 self.mesh.SetParameters(Parameters)
3232 if not IDsOfElements:
3233 IDsOfElements = self.GetElementsId()
3234 Functor = self.smeshpyD.GetFunctor(theCriterion)
3235 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3237 ## Fuse the neighbouring triangles of the object into quadrangles
3238 # @param theObject is mesh, submesh or group
3239 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType,
3240 # applied to possible quadrangles to choose a neighbour to fuse with.
3241 # Type SMESH.FunctorType._items in the Python Console to see all items.
3242 # Note that not all items correspond to numerical functors.
3243 # @param MaxAngle a max angle between element normals at which the fusion
3244 # is still performed; theMaxAngle is mesured in radians.
3245 # @return TRUE in case of success, FALSE otherwise.
3246 # @ingroup l2_modif_unitetri
3247 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3248 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3249 self.mesh.SetParameters(Parameters)
3250 if isinstance( theObject, Mesh ):
3251 theObject = theObject.GetMesh()
3252 Functor = self.smeshpyD.GetFunctor(theCriterion)
3253 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3255 ## Split quadrangles into triangles.
3256 # @param IDsOfElements the faces to be splitted.
3257 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3258 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3259 # value, then quadrangles will be split by the smallest diagonal.
3260 # Type SMESH.FunctorType._items in the Python Console to see all items.
3261 # Note that not all items correspond to numerical functors.
3262 # @return TRUE in case of success, FALSE otherwise.
3263 # @ingroup l2_modif_cutquadr
3264 def QuadToTri (self, IDsOfElements, theCriterion = None):
3265 if IDsOfElements == []:
3266 IDsOfElements = self.GetElementsId()
3267 if theCriterion is None:
3268 theCriterion = FT_MaxElementLength2D
3269 Functor = self.smeshpyD.GetFunctor(theCriterion)
3270 return self.editor.QuadToTri(IDsOfElements, Functor)
3272 ## Split quadrangles into triangles.
3273 # @param theObject the object from which the list of elements is taken,
3274 # this is mesh, submesh or group
3275 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3276 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3277 # value, then quadrangles will be split by the smallest diagonal.
3278 # Type SMESH.FunctorType._items in the Python Console to see all items.
3279 # Note that not all items correspond to numerical functors.
3280 # @return TRUE in case of success, FALSE otherwise.
3281 # @ingroup l2_modif_cutquadr
3282 def QuadToTriObject (self, theObject, theCriterion = None):
3283 if ( isinstance( theObject, Mesh )):
3284 theObject = theObject.GetMesh()
3285 if theCriterion is None:
3286 theCriterion = FT_MaxElementLength2D
3287 Functor = self.smeshpyD.GetFunctor(theCriterion)
3288 return self.editor.QuadToTriObject(theObject, Functor)
3290 ## Split each of given quadrangles into 4 triangles. A node is added at the center of
3292 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3293 # group or a list of face IDs. By default all quadrangles are split
3294 # @ingroup l2_modif_cutquadr
3295 def QuadTo4Tri (self, theElements=[]):
3296 unRegister = genObjUnRegister()
3297 if isinstance( theElements, Mesh ):
3298 theElements = theElements.mesh
3299 elif not theElements:
3300 theElements = self.mesh
3301 elif isinstance( theElements, list ):
3302 theElements = self.GetIDSource( theElements, SMESH.FACE )
3303 unRegister.set( theElements )
3304 return self.editor.QuadTo4Tri( theElements )
3306 ## Split quadrangles into triangles.
3307 # @param IDsOfElements the faces to be splitted
3308 # @param Diag13 is used to choose a diagonal for splitting.
3309 # @return TRUE in case of success, FALSE otherwise.
3310 # @ingroup l2_modif_cutquadr
3311 def SplitQuad (self, IDsOfElements, Diag13):
3312 if IDsOfElements == []:
3313 IDsOfElements = self.GetElementsId()
3314 return self.editor.SplitQuad(IDsOfElements, Diag13)
3316 ## Split quadrangles into triangles.
3317 # @param theObject the object from which the list of elements is taken,
3318 # this is mesh, submesh or group
3319 # @param Diag13 is used to choose a diagonal for splitting.
3320 # @return TRUE in case of success, FALSE otherwise.
3321 # @ingroup l2_modif_cutquadr
3322 def SplitQuadObject (self, theObject, Diag13):
3323 if ( isinstance( theObject, Mesh )):
3324 theObject = theObject.GetMesh()
3325 return self.editor.SplitQuadObject(theObject, Diag13)
3327 ## Find a better splitting of the given quadrangle.
3328 # @param IDOfQuad the ID of the quadrangle to be splitted.
3329 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3330 # choose a diagonal for splitting.
3331 # Type SMESH.FunctorType._items in the Python Console to see all items.
3332 # Note that not all items correspond to numerical functors.
3333 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3334 # diagonal is better, 0 if error occurs.
3335 # @ingroup l2_modif_cutquadr
3336 def BestSplit (self, IDOfQuad, theCriterion):
3337 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3339 ## Split volumic elements into tetrahedrons
3340 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3341 # @param method flags passing splitting method:
3342 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3343 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3344 # @ingroup l2_modif_cutquadr
3345 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3346 unRegister = genObjUnRegister()
3347 if isinstance( elems, Mesh ):
3348 elems = elems.GetMesh()
3349 if ( isinstance( elems, list )):
3350 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3351 unRegister.set( elems )
3352 self.editor.SplitVolumesIntoTetra(elems, method)
3355 ## Split bi-quadratic elements into linear ones without creation of additional nodes:
3356 # - bi-quadratic triangle will be split into 3 linear quadrangles;
3357 # - bi-quadratic quadrangle will be split into 4 linear quadrangles;
3358 # - tri-quadratic hexahedron will be split into 8 linear hexahedra.
3359 # Quadratic elements of lower dimension adjacent to the split bi-quadratic element
3360 # will be split in order to keep the mesh conformal.
3361 # @param elems - elements to split: sub-meshes, groups, filters or element IDs;
3362 # if None (default), all bi-quadratic elements will be split
3363 # @ingroup l2_modif_cutquadr
3364 def SplitBiQuadraticIntoLinear(self, elems=None):
3365 unRegister = genObjUnRegister()
3366 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
3367 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
3368 unRegister.set( elems )
3370 elems = [ self.GetMesh() ]
3371 if isinstance( elems, Mesh ):
3372 elems = [ elems.GetMesh() ]
3373 if not isinstance( elems, list ):
3375 self.editor.SplitBiQuadraticIntoLinear( elems )
3377 ## Split hexahedra into prisms
3378 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3379 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3380 # gives a normal vector defining facets to split into triangles.
3381 # @a startHexPoint can be either a triple of coordinates or a vertex.
3382 # @param facetNormal a normal to a facet to split into triangles of a
3383 # hexahedron found by @a startHexPoint.
3384 # @a facetNormal can be either a triple of coordinates or an edge.
3385 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3386 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3387 # @param allDomains if @c False, only hexahedra adjacent to one closest
3388 # to @a startHexPoint are split, else @a startHexPoint
3389 # is used to find the facet to split in all domains present in @a elems.
3390 # @ingroup l2_modif_cutquadr
3391 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3392 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3394 unRegister = genObjUnRegister()
3395 if isinstance( elems, Mesh ):
3396 elems = elems.GetMesh()
3397 if ( isinstance( elems, list )):
3398 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3399 unRegister.set( elems )
3402 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3403 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3404 elif isinstance( startHexPoint, list ):
3405 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3408 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3409 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3410 elif isinstance( facetNormal, list ):
3411 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3414 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3416 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3418 ## Split quadrangle faces near triangular facets of volumes
3420 # @ingroup l2_modif_cutquadr
3421 def SplitQuadsNearTriangularFacets(self):
3422 faces_array = self.GetElementsByType(SMESH.FACE)
3423 for face_id in faces_array:
3424 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3425 quad_nodes = self.mesh.GetElemNodes(face_id)
3426 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3427 isVolumeFound = False
3428 for node1_elem in node1_elems:
3429 if not isVolumeFound:
3430 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3431 nb_nodes = self.GetElemNbNodes(node1_elem)
3432 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3433 volume_elem = node1_elem
3434 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3435 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3436 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3437 isVolumeFound = True
3438 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3439 self.SplitQuad([face_id], False) # diagonal 2-4
3440 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3441 isVolumeFound = True
3442 self.SplitQuad([face_id], True) # diagonal 1-3
3443 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3444 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3445 isVolumeFound = True
3446 self.SplitQuad([face_id], True) # diagonal 1-3
3448 ## @brief Splits hexahedrons into tetrahedrons.
3450 # This operation uses pattern mapping functionality for splitting.
3451 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3452 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3453 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3454 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3455 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3456 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3457 # @return TRUE in case of success, FALSE otherwise.
3458 # @ingroup l2_modif_cutquadr
3459 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3460 # Pattern: 5.---------.6
3465 # (0,0,1) 4.---------.7 * |
3472 # (0,0,0) 0.---------.3
3473 pattern_tetra = "!!! Nb of points: \n 8 \n\
3483 !!! Indices of points of 6 tetras: \n\
3491 pattern = self.smeshpyD.GetPattern()
3492 isDone = pattern.LoadFromFile(pattern_tetra)
3494 print('Pattern.LoadFromFile :', pattern.GetErrorCode())
3497 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3498 isDone = pattern.MakeMesh(self.mesh, False, False)
3499 if not isDone: print('Pattern.MakeMesh :', pattern.GetErrorCode())
3501 # split quafrangle faces near triangular facets of volumes
3502 self.SplitQuadsNearTriangularFacets()
3506 ## @brief Split hexahedrons into prisms.
3508 # Uses the pattern mapping functionality for splitting.
3509 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3510 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3511 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3512 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3513 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3514 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3515 # @return TRUE in case of success, FALSE otherwise.
3516 # @ingroup l2_modif_cutquadr
3517 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3518 # Pattern: 5.---------.6
3523 # (0,0,1) 4.---------.7 |
3530 # (0,0,0) 0.---------.3
3531 pattern_prism = "!!! Nb of points: \n 8 \n\
3541 !!! Indices of points of 2 prisms: \n\
3545 pattern = self.smeshpyD.GetPattern()
3546 isDone = pattern.LoadFromFile(pattern_prism)
3548 print('Pattern.LoadFromFile :', pattern.GetErrorCode())
3551 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3552 isDone = pattern.MakeMesh(self.mesh, False, False)
3553 if not isDone: print('Pattern.MakeMesh :', pattern.GetErrorCode())
3555 # Split quafrangle faces near triangular facets of volumes
3556 self.SplitQuadsNearTriangularFacets()
3561 # @param IDsOfElements the list if ids of elements to smooth
3562 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3563 # Note that nodes built on edges and boundary nodes are always fixed.
3564 # @param MaxNbOfIterations the maximum number of iterations
3565 # @param MaxAspectRatio varies in range [1.0, inf]
3566 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3567 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3568 # @return TRUE in case of success, FALSE otherwise.
3569 # @ingroup l2_modif_smooth
3570 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3571 MaxNbOfIterations, MaxAspectRatio, Method):
3572 if IDsOfElements == []:
3573 IDsOfElements = self.GetElementsId()
3574 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3575 self.mesh.SetParameters(Parameters)
3576 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3577 MaxNbOfIterations, MaxAspectRatio, Method)
3579 ## Smooth elements which belong to the given object
3580 # @param theObject the object to smooth
3581 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3582 # Note that nodes built on edges and boundary nodes are always fixed.
3583 # @param MaxNbOfIterations the maximum number of iterations
3584 # @param MaxAspectRatio varies in range [1.0, inf]
3585 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3586 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3587 # @return TRUE in case of success, FALSE otherwise.
3588 # @ingroup l2_modif_smooth
3589 def SmoothObject(self, theObject, IDsOfFixedNodes,
3590 MaxNbOfIterations, MaxAspectRatio, Method):
3591 if ( isinstance( theObject, Mesh )):
3592 theObject = theObject.GetMesh()
3593 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3594 MaxNbOfIterations, MaxAspectRatio, Method)
3596 ## Parametrically smooth the given elements
3597 # @param IDsOfElements the list if ids of elements to smooth
3598 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3599 # Note that nodes built on edges and boundary nodes are always fixed.
3600 # @param MaxNbOfIterations the maximum number of iterations
3601 # @param MaxAspectRatio varies in range [1.0, inf]
3602 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3603 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3604 # @return TRUE in case of success, FALSE otherwise.
3605 # @ingroup l2_modif_smooth
3606 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3607 MaxNbOfIterations, MaxAspectRatio, Method):
3608 if IDsOfElements == []:
3609 IDsOfElements = self.GetElementsId()
3610 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3611 self.mesh.SetParameters(Parameters)
3612 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3613 MaxNbOfIterations, MaxAspectRatio, Method)
3615 ## Parametrically smooth the elements which belong to the given object
3616 # @param theObject the object to smooth
3617 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3618 # Note that nodes built on edges and boundary nodes are always fixed.
3619 # @param MaxNbOfIterations the maximum number of iterations
3620 # @param MaxAspectRatio varies in range [1.0, inf]
3621 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3622 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3623 # @return TRUE in case of success, FALSE otherwise.
3624 # @ingroup l2_modif_smooth
3625 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3626 MaxNbOfIterations, MaxAspectRatio, Method):
3627 if ( isinstance( theObject, Mesh )):
3628 theObject = theObject.GetMesh()
3629 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3630 MaxNbOfIterations, MaxAspectRatio, Method)
3632 ## Convert the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3633 # them with quadratic with the same id.
3634 # @param theForce3d new node creation method:
3635 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3636 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3637 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3638 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3639 # @return SMESH.ComputeError which can hold a warning
3640 # @ingroup l2_modif_tofromqu
3641 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3642 if isinstance( theSubMesh, Mesh ):
3643 theSubMesh = theSubMesh.mesh
3645 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3648 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3650 self.editor.ConvertToQuadratic(theForce3d)
3651 error = self.editor.GetLastError()
3652 if error and error.comment:
3653 print(error.comment)
3656 ## Convert the mesh from quadratic to ordinary,
3657 # deletes old quadratic elements, \n replacing
3658 # them with ordinary mesh elements with the same id.
3659 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3660 # @ingroup l2_modif_tofromqu
3661 def ConvertFromQuadratic(self, theSubMesh=None):
3663 self.editor.ConvertFromQuadraticObject(theSubMesh)
3665 return self.editor.ConvertFromQuadratic()
3667 ## Create 2D mesh as skin on boundary faces of a 3D mesh
3668 # @return TRUE if operation has been completed successfully, FALSE otherwise
3669 # @ingroup l2_modif_add
3670 def Make2DMeshFrom3D(self):
3671 return self.editor.Make2DMeshFrom3D()
3673 ## Create missing boundary elements
3674 # @param elements - elements whose boundary is to be checked:
3675 # mesh, group, sub-mesh or list of elements
3676 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3677 # @param dimension - defines type of boundary elements to create, either of
3678 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3679 # SMESH.BND_1DFROM3D create mesh edges on all borders of free facets of 3D cells
3680 # @param groupName - a name of group to store created boundary elements in,
3681 # "" means not to create the group
3682 # @param meshName - a name of new mesh to store created boundary elements in,
3683 # "" means not to create the new mesh
3684 # @param toCopyElements - if true, the checked elements will be copied into
3685 # the new mesh else only boundary elements will be copied into the new mesh
3686 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3687 # boundary elements will be copied into the new mesh
3688 # @return tuple (mesh, group) where boundary elements were added to
3689 # @ingroup l2_modif_add
3690 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3691 toCopyElements=False, toCopyExistingBondary=False):
3692 unRegister = genObjUnRegister()
3693 if isinstance( elements, Mesh ):
3694 elements = elements.GetMesh()
3695 if ( isinstance( elements, list )):
3696 elemType = SMESH.ALL
3697 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3698 elements = self.editor.MakeIDSource(elements, elemType)
3699 unRegister.set( elements )
3700 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3701 toCopyElements,toCopyExistingBondary)
3702 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3706 # @brief Create missing boundary elements around either the whole mesh or
3707 # groups of elements
3708 # @param dimension - defines type of boundary elements to create, either of
3709 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3710 # @param groupName - a name of group to store all boundary elements in,
3711 # "" means not to create the group
3712 # @param meshName - a name of a new mesh, which is a copy of the initial
3713 # mesh + created boundary elements; "" means not to create the new mesh
3714 # @param toCopyAll - if true, the whole initial mesh will be copied into
3715 # the new mesh else only boundary elements will be copied into the new mesh
3716 # @param groups - groups of elements to make boundary around
3717 # @retval tuple( long, mesh, groups )
3718 # long - number of added boundary elements
3719 # mesh - the mesh where elements were added to
3720 # group - the group of boundary elements or None
3722 # @ingroup l2_modif_add
3723 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3724 toCopyAll=False, groups=[]):
3725 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3727 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3728 return nb, mesh, group
3730 ## Renumber mesh nodes (Obsolete, does nothing)
3731 # @ingroup l2_modif_renumber
3732 def RenumberNodes(self):
3733 self.editor.RenumberNodes()
3735 ## Renumber mesh elements (Obsole, does nothing)
3736 # @ingroup l2_modif_renumber
3737 def RenumberElements(self):
3738 self.editor.RenumberElements()
3740 ## Private method converting \a arg into a list of SMESH_IdSource's
3741 def _getIdSourceList(self, arg, idType, unRegister):
3742 if arg and isinstance( arg, list ):
3743 if isinstance( arg[0], int ):
3744 arg = self.GetIDSource( arg, idType )
3745 unRegister.set( arg )
3746 elif isinstance( arg[0], Mesh ):
3747 arg[0] = arg[0].GetMesh()
3748 elif isinstance( arg, Mesh ):
3750 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3754 ## Generate new elements by rotation of the given elements and nodes around the axis
3755 # @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3756 # @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3757 # @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3758 # @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3759 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3760 # which defines angle in degrees
3761 # @param NbOfSteps the number of steps
3762 # @param Tolerance tolerance
3763 # @param MakeGroups forces the generation of new groups from existing ones
3764 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3765 # of all steps, else - size of each step
3766 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3767 # @ingroup l2_modif_extrurev
3768 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3769 MakeGroups=False, TotalAngle=False):
3770 unRegister = genObjUnRegister()
3771 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3772 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3773 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3775 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3776 Axis = self.smeshpyD.GetAxisStruct( Axis )
3777 if isinstance( Axis, list ):
3778 Axis = SMESH.AxisStruct( *Axis )
3780 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3781 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3782 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3783 self.mesh.SetParameters(Parameters)
3784 if TotalAngle and NbOfSteps:
3785 AngleInRadians /= NbOfSteps
3786 return self.editor.RotationSweepObjects( nodes, edges, faces,
3787 Axis, AngleInRadians,
3788 NbOfSteps, Tolerance, MakeGroups)
3790 ## Generate new elements by rotation of the elements around the axis
3791 # @param IDsOfElements the list of ids of elements to sweep
3792 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3793 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3794 # @param NbOfSteps the number of steps
3795 # @param Tolerance tolerance
3796 # @param MakeGroups forces the generation of new groups from existing ones
3797 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3798 # of all steps, else - size of each step
3799 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3800 # @ingroup l2_modif_extrurev
3801 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3802 MakeGroups=False, TotalAngle=False):
3803 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3804 AngleInRadians, NbOfSteps, Tolerance,
3805 MakeGroups, TotalAngle)
3807 ## Generate new elements by rotation of the elements of object around the axis
3808 # @param theObject object which elements should be sweeped.
3809 # It can be a mesh, a sub mesh or a group.
3810 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3811 # @param AngleInRadians the angle of Rotation
3812 # @param NbOfSteps number of steps
3813 # @param Tolerance tolerance
3814 # @param MakeGroups forces the generation of new groups from existing ones
3815 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3816 # of all steps, else - size of each step
3817 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3818 # @ingroup l2_modif_extrurev
3819 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3820 MakeGroups=False, TotalAngle=False):
3821 return self.RotationSweepObjects( [], theObject, theObject, Axis,
3822 AngleInRadians, NbOfSteps, Tolerance,
3823 MakeGroups, TotalAngle )
3825 ## Generate new elements by rotation of the elements of object around the axis
3826 # @param theObject object which elements should be sweeped.
3827 # It can be a mesh, a sub mesh or a group.
3828 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3829 # @param AngleInRadians the angle of Rotation
3830 # @param NbOfSteps number of steps
3831 # @param Tolerance tolerance
3832 # @param MakeGroups forces the generation of new groups from existing ones
3833 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3834 # of all steps, else - size of each step
3835 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3836 # @ingroup l2_modif_extrurev
3837 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3838 MakeGroups=False, TotalAngle=False):
3839 return self.RotationSweepObjects([],theObject,[], Axis,
3840 AngleInRadians, NbOfSteps, Tolerance,
3841 MakeGroups, TotalAngle)
3843 ## Generate new elements by rotation of the elements of object around the axis
3844 # @param theObject object which elements should be sweeped.
3845 # It can be a mesh, a sub mesh or a group.
3846 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3847 # @param AngleInRadians the angle of Rotation
3848 # @param NbOfSteps number of steps
3849 # @param Tolerance tolerance
3850 # @param MakeGroups forces the generation of new groups from existing ones
3851 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3852 # of all steps, else - size of each step
3853 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3854 # @ingroup l2_modif_extrurev
3855 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3856 MakeGroups=False, TotalAngle=False):
3857 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3858 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3860 ## Generate new elements by extrusion of the given elements and nodes
3861 # @param nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3862 # @param edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3863 # @param faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3864 # @param StepVector vector or DirStruct or 3 vector components, defining
3865 # the direction and value of extrusion for one step (the total extrusion
3866 # length will be NbOfSteps * ||StepVector||)
3867 # @param NbOfSteps the number of steps
3868 # @param MakeGroups forces the generation of new groups from existing ones
3869 # @param scaleFactors optional scale factors to apply during extrusion
3870 # @param linearVariation if @c True, scaleFactors are spread over all @a scaleFactors,
3871 # else scaleFactors[i] is applied to nodes at the i-th extrusion step
3872 # @param basePoint optional scaling center; if not provided, a gravity center of
3873 # nodes and elements being extruded is used as the scaling center.
3875 # - a list of tree components of the point or
3878 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3879 # @ingroup l2_modif_extrurev
3880 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False,
3881 scaleFactors=[], linearVariation=False, basePoint=[] ):
3882 unRegister = genObjUnRegister()
3883 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3884 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3885 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3887 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3888 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3889 if isinstance( StepVector, list ):
3890 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3892 if isinstance( basePoint, int):
3893 xyz = self.GetNodeXYZ( basePoint )
3895 raise RuntimeError("Invalid node ID: %s" % basePoint)
3897 if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
3898 basePoint = self.geompyD.PointCoordinates( basePoint )
3900 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3901 Parameters = StepVector.PS.parameters + var_separator + Parameters
3902 self.mesh.SetParameters(Parameters)
3904 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
3905 StepVector, NbOfSteps,
3906 scaleFactors, linearVariation, basePoint,
3910 ## Generate new elements by extrusion of the elements with given ids
3911 # @param IDsOfElements the list of ids of elements or nodes for extrusion
3912 # @param StepVector vector or DirStruct or 3 vector components, defining
3913 # the direction and value of extrusion for one step (the total extrusion
3914 # length will be NbOfSteps * ||StepVector||)
3915 # @param NbOfSteps the number of steps
3916 # @param MakeGroups forces the generation of new groups from existing ones
3917 # @param IsNodes is True if elements with given ids are nodes
3918 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3919 # @ingroup l2_modif_extrurev
3920 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3922 if IsNodes: n = IDsOfElements
3923 else : e,f, = IDsOfElements,IDsOfElements
3924 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3926 ## Generate new elements by extrusion along the normal to a discretized surface or wire
3927 # @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh.
3928 # Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
3929 # @param StepSize length of one extrusion step (the total extrusion
3930 # length will be \a NbOfSteps * \a StepSize ).
3931 # @param NbOfSteps number of extrusion steps.
3932 # @param ByAverageNormal if True each node is translated by \a StepSize
3933 # along the average of the normal vectors to the faces sharing the node;
3934 # else each node is translated along the same average normal till
3935 # intersection with the plane got by translation of the face sharing
3936 # the node along its own normal by \a StepSize.
3937 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3938 # for every node of \a Elements.
3939 # @param MakeGroups forces generation of new groups from existing ones.
3940 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
3941 # is not yet implemented. This parameter is used if \a Elements contains
3942 # both faces and edges, i.e. \a Elements is a Mesh.
3943 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
3944 # empty list otherwise.
3945 # @ingroup l2_modif_extrurev
3946 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
3947 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
3948 unRegister = genObjUnRegister()
3949 if isinstance( Elements, Mesh ):
3950 Elements = [ Elements.GetMesh() ]
3951 if isinstance( Elements, list ):
3953 raise RuntimeError("Elements empty!")
3954 if isinstance( Elements[0], int ):
3955 Elements = self.GetIDSource( Elements, SMESH.ALL )
3956 unRegister.set( Elements )
3957 if not isinstance( Elements, list ):
3958 Elements = [ Elements ]
3959 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
3960 self.mesh.SetParameters(Parameters)
3961 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
3962 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
3964 ## Generate new elements by extrusion of the elements or nodes which belong to the object
3965 # @param theObject the object whose elements or nodes should be processed.
3966 # It can be a mesh, a sub-mesh or a group.
3967 # @param StepVector vector or DirStruct or 3 vector components, defining
3968 # the direction and value of extrusion for one step (the total extrusion
3969 # length will be NbOfSteps * ||StepVector||)
3970 # @param NbOfSteps the number of steps
3971 # @param MakeGroups forces the generation of new groups from existing ones
3972 # @param IsNodes is True if elements to extrude are nodes
3973 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3974 # @ingroup l2_modif_extrurev
3975 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3977 if IsNodes: n = theObject
3978 else : e,f, = theObject,theObject
3979 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3981 ## Generate new elements by extrusion of edges which belong to the object
3982 # @param theObject object whose 1D elements should be processed.
3983 # It can be a mesh, a sub-mesh or a group.
3984 # @param StepVector vector or DirStruct or 3 vector components, defining
3985 # the direction and value of extrusion for one step (the total extrusion
3986 # length will be NbOfSteps * ||StepVector||)
3987 # @param NbOfSteps the number of steps
3988 # @param MakeGroups to generate new groups from existing ones
3989 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3990 # @ingroup l2_modif_extrurev
3991 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3992 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
3994 ## Generate new elements by extrusion of faces which belong to the object
3995 # @param theObject object whose 2D elements should be processed.
3996 # It can be a mesh, a sub-mesh or a group.
3997 # @param StepVector vector or DirStruct or 3 vector components, defining
3998 # the direction and value of extrusion for one step (the total extrusion
3999 # length will be NbOfSteps * ||StepVector||)
4000 # @param NbOfSteps the number of steps
4001 # @param MakeGroups forces the generation of new groups from existing ones
4002 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4003 # @ingroup l2_modif_extrurev
4004 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
4005 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
4007 ## Generate new elements by extrusion of the elements with given ids
4008 # @param IDsOfElements is ids of elements
4009 # @param StepVector vector or DirStruct or 3 vector components, defining
4010 # the direction and value of extrusion for one step (the total extrusion
4011 # length will be NbOfSteps * ||StepVector||)
4012 # @param NbOfSteps the number of steps
4013 # @param ExtrFlags sets flags for extrusion
4014 # @param SewTolerance uses for comparing locations of nodes if flag
4015 # EXTRUSION_FLAG_SEW is set
4016 # @param MakeGroups forces the generation of new groups from existing ones
4017 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4018 # @ingroup l2_modif_extrurev
4019 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
4020 ExtrFlags, SewTolerance, MakeGroups=False):
4021 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
4022 StepVector = self.smeshpyD.GetDirStruct(StepVector)
4023 if isinstance( StepVector, list ):
4024 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
4025 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
4026 ExtrFlags, SewTolerance, MakeGroups)
4028 ## Generate new elements by extrusion of the given elements and nodes along the path.
4029 # The path of extrusion must be a meshed edge.
4030 # @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
4031 # @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
4032 # @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
4033 # @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4034 # @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
4035 # contains not only path segments, else it can be None
4036 # @param NodeStart the first or the last node on the path. Defines the direction of extrusion
4037 # @param HasAngles allows the shape to be rotated around the path
4038 # to get the resulting mesh in a helical fashion
4039 # @param Angles list of angles
4040 # @param LinearVariation forces the computation of rotation angles as linear
4041 # variation of the given Angles along path steps
4042 # @param HasRefPoint allows using the reference point
4043 # @param RefPoint the point around which the shape is rotated (the mass center of the
4044 # shape by default). The User can specify any point as the Reference Point.
4045 # @param MakeGroups forces the generation of new groups from existing ones
4046 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
4047 # @ingroup l2_modif_extrurev
4048 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
4049 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
4050 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
4051 unRegister = genObjUnRegister()
4052 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
4053 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
4054 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
4056 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
4057 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4058 if isinstance( RefPoint, list ):
4059 if not RefPoint: RefPoint = [0,0,0]
4060 RefPoint = SMESH.PointStruct( *RefPoint )
4061 if isinstance( PathMesh, Mesh ):
4062 PathMesh = PathMesh.GetMesh()
4063 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4064 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4065 self.mesh.SetParameters(Parameters)
4066 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
4067 PathMesh, PathShape, NodeStart,
4068 HasAngles, Angles, LinearVariation,
4069 HasRefPoint, RefPoint, MakeGroups)
4071 ## Generate new elements by extrusion of the given elements
4072 # The path of extrusion must be a meshed edge.
4073 # @param Base mesh or group, or sub-mesh, or list of ids of elements for extrusion
4074 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4075 # @param NodeStart the start node from Path. Defines the direction of extrusion
4076 # @param HasAngles allows the shape to be rotated around the path
4077 # to get the resulting mesh in a helical fashion
4078 # @param Angles list of angles in radians
4079 # @param LinearVariation forces the computation of rotation angles as linear
4080 # variation of the given Angles along path steps
4081 # @param HasRefPoint allows using the reference point
4082 # @param RefPoint the point around which the elements are rotated (the mass
4083 # center of the elements by default).
4084 # The User can specify any point as the Reference Point.
4085 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
4086 # @param MakeGroups forces the generation of new groups from existing ones
4087 # @param ElemType type of elements for extrusion (if param Base is a mesh)
4088 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4089 # only SMESH::Extrusion_Error otherwise
4090 # @ingroup l2_modif_extrurev
4091 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
4092 HasAngles=False, Angles=[], LinearVariation=False,
4093 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
4094 ElemType=SMESH.FACE):
4096 if ElemType == SMESH.NODE: n = Base
4097 if ElemType == SMESH.EDGE: e = Base
4098 if ElemType == SMESH.FACE: f = Base
4099 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
4100 HasAngles, Angles, LinearVariation,
4101 HasRefPoint, RefPoint, MakeGroups)
4102 if MakeGroups: return gr,er
4105 ## Generate new elements by extrusion of the given elements
4106 # The path of extrusion must be a meshed edge.
4107 # @param IDsOfElements ids of elements
4108 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
4109 # @param PathShape shape(edge) defines the sub-mesh for the path
4110 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4111 # @param HasAngles allows the shape to be rotated around the path
4112 # to get the resulting mesh in a helical fashion
4113 # @param Angles list of angles in radians
4114 # @param HasRefPoint allows using the reference point
4115 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4116 # The User can specify any point as the Reference Point.
4117 # @param MakeGroups forces the generation of new groups from existing ones
4118 # @param LinearVariation forces the computation of rotation angles as linear
4119 # variation of the given Angles along path steps
4120 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4121 # only SMESH::Extrusion_Error otherwise
4122 # @ingroup l2_modif_extrurev
4123 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
4124 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4125 MakeGroups=False, LinearVariation=False):
4126 n,e,f = [],IDsOfElements,IDsOfElements
4127 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
4128 NodeStart, HasAngles, Angles,
4130 HasRefPoint, RefPoint, MakeGroups)
4131 if MakeGroups: return gr,er
4134 ## Generate new elements by extrusion of the elements which belong to the object
4135 # The path of extrusion must be a meshed edge.
4136 # @param theObject the object whose elements should be processed.
4137 # It can be a mesh, a sub-mesh or a group.
4138 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4139 # @param PathShape shape(edge) defines the sub-mesh for the path
4140 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4141 # @param HasAngles allows the shape to be rotated around the path
4142 # to get the resulting mesh in a helical fashion
4143 # @param Angles list of angles
4144 # @param HasRefPoint allows using the reference point
4145 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4146 # The User can specify any point as the Reference Point.
4147 # @param MakeGroups forces the generation of new groups from existing ones
4148 # @param LinearVariation forces the computation of rotation angles as linear
4149 # variation of the given Angles along path steps
4150 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4151 # only SMESH::Extrusion_Error otherwise
4152 # @ingroup l2_modif_extrurev
4153 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4154 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4155 MakeGroups=False, LinearVariation=False):
4156 n,e,f = [],theObject,theObject
4157 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4158 HasAngles, Angles, LinearVariation,
4159 HasRefPoint, RefPoint, MakeGroups)
4160 if MakeGroups: return gr,er
4163 ## Generate new elements by extrusion of mesh segments which belong to the object
4164 # The path of extrusion must be a meshed edge.
4165 # @param theObject the object whose 1D elements should be processed.
4166 # It can be a mesh, a sub-mesh or a group.
4167 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4168 # @param PathShape shape(edge) defines the sub-mesh for the path
4169 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4170 # @param HasAngles allows the shape to be rotated around the path
4171 # to get the resulting mesh in a helical fashion
4172 # @param Angles list of angles
4173 # @param HasRefPoint allows using the reference point
4174 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4175 # The User can specify any point as the Reference Point.
4176 # @param MakeGroups forces the generation of new groups from existing ones
4177 # @param LinearVariation forces the computation of rotation angles as linear
4178 # variation of the given Angles along path steps
4179 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4180 # only SMESH::Extrusion_Error otherwise
4181 # @ingroup l2_modif_extrurev
4182 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4183 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4184 MakeGroups=False, LinearVariation=False):
4185 n,e,f = [],theObject,[]
4186 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4187 HasAngles, Angles, LinearVariation,
4188 HasRefPoint, RefPoint, MakeGroups)
4189 if MakeGroups: return gr,er
4192 ## Generate new elements by extrusion of faces which belong to the object
4193 # The path of extrusion must be a meshed edge.
4194 # @param theObject the object whose 2D elements should be processed.
4195 # It can be a mesh, a sub-mesh or a group.
4196 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4197 # @param PathShape shape(edge) defines the sub-mesh for the path
4198 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4199 # @param HasAngles allows the shape to be rotated around the path
4200 # to get the resulting mesh in a helical fashion
4201 # @param Angles list of angles
4202 # @param HasRefPoint allows using the reference point
4203 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4204 # The User can specify any point as the Reference Point.
4205 # @param MakeGroups forces the generation of new groups from existing ones
4206 # @param LinearVariation forces the computation of rotation angles as linear
4207 # variation of the given Angles along path steps
4208 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4209 # only SMESH::Extrusion_Error otherwise
4210 # @ingroup l2_modif_extrurev
4211 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4212 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4213 MakeGroups=False, LinearVariation=False):
4214 n,e,f = [],[],theObject
4215 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4216 HasAngles, Angles, LinearVariation,
4217 HasRefPoint, RefPoint, MakeGroups)
4218 if MakeGroups: return gr,er
4221 ## Create a symmetrical copy of mesh elements
4222 # @param IDsOfElements list of elements ids
4223 # @param Mirror is AxisStruct or geom object(point, line, plane)
4224 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4225 # If the Mirror is a geom object this parameter is unnecessary
4226 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4227 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4228 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4229 # @ingroup l2_modif_trsf
4230 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4231 if IDsOfElements == []:
4232 IDsOfElements = self.GetElementsId()
4233 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4234 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4235 theMirrorType = Mirror._mirrorType
4237 self.mesh.SetParameters(Mirror.parameters)
4238 if Copy and MakeGroups:
4239 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4240 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4243 ## Create a new mesh by a symmetrical copy of mesh elements
4244 # @param IDsOfElements the list of elements ids
4245 # @param Mirror is AxisStruct or geom object (point, line, plane)
4246 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4247 # If the Mirror is a geom object this parameter is unnecessary
4248 # @param MakeGroups to generate new groups from existing ones
4249 # @param NewMeshName a name of the new mesh to create
4250 # @return instance of Mesh class
4251 # @ingroup l2_modif_trsf
4252 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4253 if IDsOfElements == []:
4254 IDsOfElements = self.GetElementsId()
4255 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4256 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4257 theMirrorType = Mirror._mirrorType
4259 self.mesh.SetParameters(Mirror.parameters)
4260 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4261 MakeGroups, NewMeshName)
4262 return Mesh(self.smeshpyD,self.geompyD,mesh)
4264 ## Create a symmetrical copy of the object
4265 # @param theObject mesh, submesh or group
4266 # @param Mirror AxisStruct or geom object (point, line, plane)
4267 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4268 # If the Mirror is a geom object this parameter is unnecessary
4269 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4270 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4271 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4272 # @ingroup l2_modif_trsf
4273 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4274 if ( isinstance( theObject, Mesh )):
4275 theObject = theObject.GetMesh()
4276 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4277 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4278 theMirrorType = Mirror._mirrorType
4280 self.mesh.SetParameters(Mirror.parameters)
4281 if Copy and MakeGroups:
4282 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4283 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4286 ## Create a new mesh by a symmetrical copy of the object
4287 # @param theObject mesh, submesh or group
4288 # @param Mirror AxisStruct or geom object (point, line, plane)
4289 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4290 # If the Mirror is a geom object this parameter is unnecessary
4291 # @param MakeGroups forces the generation of new groups from existing ones
4292 # @param NewMeshName the name of the new mesh to create
4293 # @return instance of Mesh class
4294 # @ingroup l2_modif_trsf
4295 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4296 if ( isinstance( theObject, Mesh )):
4297 theObject = theObject.GetMesh()
4298 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4299 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4300 theMirrorType = Mirror._mirrorType
4302 self.mesh.SetParameters(Mirror.parameters)
4303 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4304 MakeGroups, NewMeshName)
4305 return Mesh( self.smeshpyD,self.geompyD,mesh )
4307 ## Translate the elements
4308 # @param IDsOfElements list of elements ids
4309 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4310 # @param Copy allows copying the translated elements
4311 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4312 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4313 # @ingroup l2_modif_trsf
4314 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4315 if IDsOfElements == []:
4316 IDsOfElements = self.GetElementsId()
4317 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4318 Vector = self.smeshpyD.GetDirStruct(Vector)
4319 if isinstance( Vector, list ):
4320 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4321 self.mesh.SetParameters(Vector.PS.parameters)
4322 if Copy and MakeGroups:
4323 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4324 self.editor.Translate(IDsOfElements, Vector, Copy)
4327 ## Create a new mesh of translated elements
4328 # @param IDsOfElements list of elements ids
4329 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4330 # @param MakeGroups forces the generation of new groups from existing ones
4331 # @param NewMeshName the name of the newly created mesh
4332 # @return instance of Mesh class
4333 # @ingroup l2_modif_trsf
4334 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4335 if IDsOfElements == []:
4336 IDsOfElements = self.GetElementsId()
4337 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4338 Vector = self.smeshpyD.GetDirStruct(Vector)
4339 if isinstance( Vector, list ):
4340 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4341 self.mesh.SetParameters(Vector.PS.parameters)
4342 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4343 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4345 ## Translate the object
4346 # @param theObject the object to translate (mesh, submesh, or group)
4347 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4348 # @param Copy allows copying the translated elements
4349 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4350 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4351 # @ingroup l2_modif_trsf
4352 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4353 if ( isinstance( theObject, Mesh )):
4354 theObject = theObject.GetMesh()
4355 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4356 Vector = self.smeshpyD.GetDirStruct(Vector)
4357 if isinstance( Vector, list ):
4358 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4359 self.mesh.SetParameters(Vector.PS.parameters)
4360 if Copy and MakeGroups:
4361 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4362 self.editor.TranslateObject(theObject, Vector, Copy)
4365 ## Create a new mesh from the translated object
4366 # @param theObject the object to translate (mesh, submesh, or group)
4367 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4368 # @param MakeGroups forces the generation of new groups from existing ones
4369 # @param NewMeshName the name of the newly created mesh
4370 # @return instance of Mesh class
4371 # @ingroup l2_modif_trsf
4372 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4373 if isinstance( theObject, Mesh ):
4374 theObject = theObject.GetMesh()
4375 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4376 Vector = self.smeshpyD.GetDirStruct(Vector)
4377 if isinstance( Vector, list ):
4378 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4379 self.mesh.SetParameters(Vector.PS.parameters)
4380 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4381 return Mesh( self.smeshpyD, self.geompyD, mesh )
4386 # @param theObject - the object to translate (mesh, submesh, or group)
4387 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4388 # @param theScaleFact - list of 1-3 scale factors for axises
4389 # @param Copy - allows copying the translated elements
4390 # @param MakeGroups - forces the generation of new groups from existing
4392 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4393 # empty list otherwise
4394 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4395 unRegister = genObjUnRegister()
4396 if ( isinstance( theObject, Mesh )):
4397 theObject = theObject.GetMesh()
4398 if ( isinstance( theObject, list )):
4399 theObject = self.GetIDSource(theObject, SMESH.ALL)
4400 unRegister.set( theObject )
4401 if ( isinstance( thePoint, list )):
4402 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4403 if ( isinstance( theScaleFact, float )):
4404 theScaleFact = [theScaleFact]
4405 if ( isinstance( theScaleFact, int )):
4406 theScaleFact = [ float(theScaleFact)]
4408 self.mesh.SetParameters(thePoint.parameters)
4410 if Copy and MakeGroups:
4411 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4412 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4415 ## Create a new mesh from the translated object
4416 # @param theObject - the object to translate (mesh, submesh, or group)
4417 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4418 # @param theScaleFact - list of 1-3 scale factors for axises
4419 # @param MakeGroups - forces the generation of new groups from existing ones
4420 # @param NewMeshName - the name of the newly created mesh
4421 # @return instance of Mesh class
4422 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4423 unRegister = genObjUnRegister()
4424 if (isinstance(theObject, Mesh)):
4425 theObject = theObject.GetMesh()
4426 if ( isinstance( theObject, list )):
4427 theObject = self.GetIDSource(theObject,SMESH.ALL)
4428 unRegister.set( theObject )
4429 if ( isinstance( thePoint, list )):
4430 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4431 if ( isinstance( theScaleFact, float )):
4432 theScaleFact = [theScaleFact]
4433 if ( isinstance( theScaleFact, int )):
4434 theScaleFact = [ float(theScaleFact)]
4436 self.mesh.SetParameters(thePoint.parameters)
4437 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4438 MakeGroups, NewMeshName)
4439 return Mesh( self.smeshpyD, self.geompyD, mesh )
4443 ## Rotate the elements
4444 # @param IDsOfElements list of elements ids
4445 # @param Axis the axis of rotation (AxisStruct or geom line)
4446 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4447 # @param Copy allows copying the rotated 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 Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4452 if IDsOfElements == []:
4453 IDsOfElements = self.GetElementsId()
4454 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4455 Axis = self.smeshpyD.GetAxisStruct(Axis)
4456 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4457 Parameters = Axis.parameters + var_separator + Parameters
4458 self.mesh.SetParameters(Parameters)
4459 if Copy and MakeGroups:
4460 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4461 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4464 ## Create a new mesh of rotated elements
4465 # @param IDsOfElements list of element ids
4466 # @param Axis the axis of rotation (AxisStruct or geom line)
4467 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4468 # @param MakeGroups forces the generation of new groups from existing ones
4469 # @param NewMeshName the name of the newly created mesh
4470 # @return instance of Mesh class
4471 # @ingroup l2_modif_trsf
4472 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4473 if IDsOfElements == []:
4474 IDsOfElements = self.GetElementsId()
4475 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4476 Axis = self.smeshpyD.GetAxisStruct(Axis)
4477 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4478 Parameters = Axis.parameters + var_separator + Parameters
4479 self.mesh.SetParameters(Parameters)
4480 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4481 MakeGroups, NewMeshName)
4482 return Mesh( self.smeshpyD, self.geompyD, mesh )
4484 ## Rotate the object
4485 # @param theObject the object to rotate( mesh, submesh, or group)
4486 # @param Axis the axis of rotation (AxisStruct or geom line)
4487 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4488 # @param Copy allows copying the rotated elements
4489 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4490 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4491 # @ingroup l2_modif_trsf
4492 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4493 if (isinstance(theObject, Mesh)):
4494 theObject = theObject.GetMesh()
4495 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4496 Axis = self.smeshpyD.GetAxisStruct(Axis)
4497 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4498 Parameters = Axis.parameters + ":" + Parameters
4499 self.mesh.SetParameters(Parameters)
4500 if Copy and MakeGroups:
4501 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4502 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4505 ## Create a new mesh from the rotated object
4506 # @param theObject the object to rotate (mesh, submesh, or group)
4507 # @param Axis the axis of rotation (AxisStruct or geom line)
4508 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4509 # @param MakeGroups forces the generation of new groups from existing ones
4510 # @param NewMeshName the name of the newly created mesh
4511 # @return instance of Mesh class
4512 # @ingroup l2_modif_trsf
4513 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4514 if (isinstance( theObject, Mesh )):
4515 theObject = theObject.GetMesh()
4516 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4517 Axis = self.smeshpyD.GetAxisStruct(Axis)
4518 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4519 Parameters = Axis.parameters + ":" + Parameters
4520 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4521 MakeGroups, NewMeshName)
4522 self.mesh.SetParameters(Parameters)
4523 return Mesh( self.smeshpyD, self.geompyD, mesh )
4525 ## Find groups of adjacent nodes within Tolerance.
4526 # @param Tolerance the value of tolerance
4527 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4528 # corner and medium nodes in separate groups thus preventing
4529 # their further merge.
4530 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4531 # @ingroup l2_modif_trsf
4532 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
4533 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
4535 ## Find groups of ajacent nodes within Tolerance.
4536 # @param Tolerance the value of tolerance
4537 # @param SubMeshOrGroup SubMesh, Group or Filter
4538 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4539 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4540 # corner and medium nodes in separate groups thus preventing
4541 # their further merge.
4542 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4543 # @ingroup l2_modif_trsf
4544 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
4545 exceptNodes=[], SeparateCornerAndMediumNodes=False):
4546 unRegister = genObjUnRegister()
4547 if (isinstance( SubMeshOrGroup, Mesh )):
4548 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4549 if not isinstance( exceptNodes, list ):
4550 exceptNodes = [ exceptNodes ]
4551 if exceptNodes and isinstance( exceptNodes[0], int ):
4552 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
4553 unRegister.set( exceptNodes )
4554 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
4555 exceptNodes, SeparateCornerAndMediumNodes)
4558 # @param GroupsOfNodes a list of groups of nodes IDs for merging
4559 # (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
4560 # by nodes 1 and 25 correspondingly in all elements and groups
4561 # @param NodesToKeep nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
4562 # If @a NodesToKeep does not include a node to keep for some group to merge,
4563 # then the first node in the group is kept.
4564 # @ingroup l2_modif_trsf
4565 def MergeNodes (self, GroupsOfNodes, NodesToKeep=[]):
4566 # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
4567 self.editor.MergeNodes(GroupsOfNodes,NodesToKeep)
4569 ## Find the elements built on the same nodes.
4570 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4571 # @return the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
4572 # @ingroup l2_modif_trsf
4573 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4574 if not MeshOrSubMeshOrGroup:
4575 MeshOrSubMeshOrGroup=self.mesh
4576 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4577 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4578 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4580 ## Merge elements in each given group.
4581 # @param GroupsOfElementsID a list of groups of elements IDs for merging
4582 # (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
4583 # replaced by elements 1 and 25 in all groups)
4584 # @ingroup l2_modif_trsf
4585 def MergeElements(self, GroupsOfElementsID):
4586 self.editor.MergeElements(GroupsOfElementsID)
4588 ## Leave one element and remove all other elements built on the same nodes.
4589 # @ingroup l2_modif_trsf
4590 def MergeEqualElements(self):
4591 self.editor.MergeEqualElements()
4593 ## Return groups of FreeBorder's coincident within the given tolerance.
4594 # @param tolerance the tolerance. If the tolerance <= 0.0 then one tenth of an average
4595 # size of elements adjacent to free borders being compared is used.
4596 # @return SMESH.CoincidentFreeBorders structure
4597 # @ingroup l2_modif_trsf
4598 def FindCoincidentFreeBorders (self, tolerance=0.):
4599 return self.editor.FindCoincidentFreeBorders( tolerance )
4601 ## Sew FreeBorder's of each group
4602 # @param freeBorders either a SMESH.CoincidentFreeBorders structure or a list of lists
4603 # where each enclosed list contains node IDs of a group of coincident free
4604 # borders such that each consequent triple of IDs within a group describes
4605 # a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
4606 # last node of a border.
4607 # For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
4608 # groups of coincident free borders, each group including two borders.
4609 # @param createPolygons if @c True faces adjacent to free borders are converted to
4610 # polygons if a node of opposite border falls on a face edge, else such
4611 # faces are split into several ones.
4612 # @param createPolyhedra if @c True volumes adjacent to free borders are converted to
4613 # polyhedra if a node of opposite border falls on a volume edge, else such
4614 # volumes, if any, remain intact and the mesh becomes non-conformal.
4615 # @return a number of successfully sewed groups
4616 # @ingroup l2_modif_trsf
4617 def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
4618 if freeBorders and isinstance( freeBorders, list ):
4619 # construct SMESH.CoincidentFreeBorders
4620 if isinstance( freeBorders[0], int ):
4621 freeBorders = [freeBorders]
4623 coincidentGroups = []
4624 for nodeList in freeBorders:
4625 if not nodeList or len( nodeList ) % 3:
4626 raise ValueError("Wrong number of nodes in this group: %s" % nodeList)
4629 group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
4630 borders.append( SMESH.FreeBorder( nodeList[:3] ))
4631 nodeList = nodeList[3:]
4633 coincidentGroups.append( group )
4635 freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
4637 return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
4640 # @return SMESH::Sew_Error
4641 # @ingroup l2_modif_trsf
4642 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4643 FirstNodeID2, SecondNodeID2, LastNodeID2,
4644 CreatePolygons, CreatePolyedrs):
4645 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4646 FirstNodeID2, SecondNodeID2, LastNodeID2,
4647 CreatePolygons, CreatePolyedrs)
4649 ## Sew conform free borders
4650 # @return SMESH::Sew_Error
4651 # @ingroup l2_modif_trsf
4652 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4653 FirstNodeID2, SecondNodeID2):
4654 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4655 FirstNodeID2, SecondNodeID2)
4657 ## Sew border to side
4658 # @return SMESH::Sew_Error
4659 # @ingroup l2_modif_trsf
4660 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4661 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4662 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4663 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4665 ## Sew two sides of a mesh. The nodes belonging to Side1 are
4666 # merged with the nodes of elements of Side2.
4667 # The number of elements in theSide1 and in theSide2 must be
4668 # equal and they should have similar nodal connectivity.
4669 # The nodes to merge should belong to side borders and
4670 # the first node should be linked to the second.
4671 # @return SMESH::Sew_Error
4672 # @ingroup l2_modif_trsf
4673 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4674 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4675 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4676 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4677 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4678 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4680 ## Set new nodes for the given element.
4681 # @param ide the element id
4682 # @param newIDs nodes ids
4683 # @return If the number of nodes does not correspond to the type of element - return false
4684 # @ingroup l2_modif_edit
4685 def ChangeElemNodes(self, ide, newIDs):
4686 return self.editor.ChangeElemNodes(ide, newIDs)
4688 ## If during the last operation of MeshEditor some nodes were
4689 # created, this method return the list of their IDs, \n
4690 # if new nodes were not created - return empty list
4691 # @return the list of integer values (can be empty)
4692 # @ingroup l2_modif_add
4693 def GetLastCreatedNodes(self):
4694 return self.editor.GetLastCreatedNodes()
4696 ## If during the last operation of MeshEditor some elements were
4697 # created this method return the list of their IDs, \n
4698 # if new elements were not created - return empty list
4699 # @return the list of integer values (can be empty)
4700 # @ingroup l2_modif_add
4701 def GetLastCreatedElems(self):
4702 return self.editor.GetLastCreatedElems()
4704 ## Forget what nodes and elements were created by the last mesh edition operation
4705 # @ingroup l2_modif_add
4706 def ClearLastCreated(self):
4707 self.editor.ClearLastCreated()
4709 ## Create duplicates of given elements, i.e. create new elements based on the
4710 # same nodes as the given ones.
4711 # @param theElements - container of elements to duplicate. It can be a Mesh,
4712 # sub-mesh, group, filter or a list of element IDs. If \a theElements is
4713 # a Mesh, elements of highest dimension are duplicated
4714 # @param theGroupName - a name of group to contain the generated elements.
4715 # If a group with such a name already exists, the new elements
4716 # are added to the existng group, else a new group is created.
4717 # If \a theGroupName is empty, new elements are not added
4719 # @return a group where the new elements are added. None if theGroupName == "".
4720 # @ingroup l2_modif_duplicat
4721 def DoubleElements(self, theElements, theGroupName=""):
4722 unRegister = genObjUnRegister()
4723 if isinstance( theElements, Mesh ):
4724 theElements = theElements.mesh
4725 elif isinstance( theElements, list ):
4726 theElements = self.GetIDSource( theElements, SMESH.ALL )
4727 unRegister.set( theElements )
4728 return self.editor.DoubleElements(theElements, theGroupName)
4730 ## Create a hole in a mesh by doubling the nodes of some particular elements
4731 # @param theNodes identifiers of nodes to be doubled
4732 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4733 # nodes. If list of element identifiers is empty then nodes are doubled but
4734 # they not assigned to elements
4735 # @return TRUE if operation has been completed successfully, FALSE otherwise
4736 # @ingroup l2_modif_duplicat
4737 def DoubleNodes(self, theNodes, theModifiedElems):
4738 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4740 ## Create a hole in a mesh by doubling the nodes of some particular elements
4741 # This method provided for convenience works as DoubleNodes() described above.
4742 # @param theNodeId identifiers of node to be doubled
4743 # @param theModifiedElems identifiers of elements to be updated
4744 # @return TRUE if operation has been completed successfully, FALSE otherwise
4745 # @ingroup l2_modif_duplicat
4746 def DoubleNode(self, theNodeId, theModifiedElems):
4747 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4749 ## Create a hole in a mesh by doubling the nodes of some particular elements
4750 # This method provided for convenience works as DoubleNodes() described above.
4751 # @param theNodes group of nodes to be doubled
4752 # @param theModifiedElems group of elements to be updated.
4753 # @param theMakeGroup forces the generation of a group containing new nodes.
4754 # @return TRUE or a created group if operation has been completed successfully,
4755 # FALSE or None otherwise
4756 # @ingroup l2_modif_duplicat
4757 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4759 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4760 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4762 ## Create a hole in a mesh by doubling the nodes of some particular elements
4763 # This method provided for convenience works as DoubleNodes() described above.
4764 # @param theNodes list of groups of nodes to be doubled
4765 # @param theModifiedElems list of groups of elements to be updated.
4766 # @param theMakeGroup forces the generation of a group containing new nodes.
4767 # @return TRUE if operation has been completed successfully, FALSE otherwise
4768 # @ingroup l2_modif_duplicat
4769 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4771 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4772 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4774 ## Create a hole in a mesh by doubling the nodes of some particular elements
4775 # @param theElems - the list of elements (edges or faces) to be replicated
4776 # The nodes for duplication could be found from these elements
4777 # @param theNodesNot - list of nodes to NOT replicate
4778 # @param theAffectedElems - the list of elements (cells and edges) to which the
4779 # replicated nodes should be associated to.
4780 # @return TRUE if operation has been completed successfully, FALSE otherwise
4781 # @ingroup l2_modif_duplicat
4782 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4783 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4785 ## Create a hole in a mesh by doubling the nodes of some particular elements
4786 # @param theElems - the list of elements (edges or faces) to be replicated
4787 # The nodes for duplication could be found from these elements
4788 # @param theNodesNot - list of nodes to NOT replicate
4789 # @param theShape - shape to detect affected elements (element which geometric center
4790 # located on or inside shape).
4791 # The replicated nodes should be associated to affected elements.
4792 # @return TRUE if operation has been completed successfully, FALSE otherwise
4793 # @ingroup l2_modif_duplicat
4794 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4795 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4797 ## Create a hole in a mesh by doubling the nodes of some particular elements
4798 # This method provided for convenience works as DoubleNodes() described above.
4799 # @param theElems - group of of elements (edges or faces) to be replicated
4800 # @param theNodesNot - group of nodes not to replicated
4801 # @param theAffectedElems - group of elements to which the replicated nodes
4802 # should be associated to.
4803 # @param theMakeGroup forces the generation of a group containing new elements.
4804 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4805 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4806 # FALSE or None otherwise
4807 # @ingroup l2_modif_duplicat
4808 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4809 theMakeGroup=False, theMakeNodeGroup=False):
4810 if theMakeGroup or theMakeNodeGroup:
4811 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4813 theMakeGroup, theMakeNodeGroup)
4814 if theMakeGroup and theMakeNodeGroup:
4817 return twoGroups[ int(theMakeNodeGroup) ]
4818 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4820 ## Create a hole in a mesh by doubling the nodes of some particular elements
4821 # This method provided for convenience works as DoubleNodes() described above.
4822 # @param theElems - group of of elements (edges or faces) to be replicated
4823 # @param theNodesNot - group of nodes not to replicated
4824 # @param theShape - shape to detect affected elements (element which geometric center
4825 # located on or inside shape).
4826 # The replicated nodes should be associated to affected elements.
4827 # @ingroup l2_modif_duplicat
4828 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4829 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4831 ## Create a hole in a mesh by doubling the nodes of some particular elements
4832 # This method provided for convenience works as DoubleNodes() described above.
4833 # @param theElems - list of groups of elements (edges or faces) to be replicated
4834 # @param theNodesNot - list of groups of nodes not to replicated
4835 # @param theAffectedElems - group of elements to which the replicated nodes
4836 # should be associated to.
4837 # @param theMakeGroup forces the generation of a group containing new elements.
4838 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4839 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4840 # FALSE or None otherwise
4841 # @ingroup l2_modif_duplicat
4842 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4843 theMakeGroup=False, theMakeNodeGroup=False):
4844 if theMakeGroup or theMakeNodeGroup:
4845 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4847 theMakeGroup, theMakeNodeGroup)
4848 if theMakeGroup and theMakeNodeGroup:
4851 return twoGroups[ int(theMakeNodeGroup) ]
4852 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4854 ## Create a hole in a mesh by doubling the nodes of some particular elements
4855 # This method provided for convenience works as DoubleNodes() described above.
4856 # @param theElems - list of groups of elements (edges or faces) to be replicated
4857 # @param theNodesNot - list of groups of nodes not to replicated
4858 # @param theShape - shape to detect affected elements (element which geometric center
4859 # located on or inside shape).
4860 # The replicated nodes should be associated to affected elements.
4861 # @return TRUE if operation has been completed successfully, FALSE otherwise
4862 # @ingroup l2_modif_duplicat
4863 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4864 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4866 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4867 # This method is the first step of DoubleNodeElemGroupsInRegion.
4868 # @param theElems - list of groups of elements (edges or faces) to be replicated
4869 # @param theNodesNot - list of groups of nodes not to replicated
4870 # @param theShape - shape to detect affected elements (element which geometric center
4871 # located on or inside shape).
4872 # The replicated nodes should be associated to affected elements.
4873 # @return groups of affected elements
4874 # @ingroup l2_modif_duplicat
4875 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4876 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4878 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4879 # The list of groups must describe a partition of the mesh volumes.
4880 # The nodes of the internal faces at the boundaries of the groups are doubled.
4881 # In option, the internal faces are replaced by flat elements.
4882 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4883 # @param theDomains - list of groups of volumes
4884 # @param createJointElems - if TRUE, create the elements
4885 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4886 # the boundary between \a theDomains and the rest mesh
4887 # @return TRUE if operation has been completed successfully, FALSE otherwise
4888 # @ingroup l2_modif_duplicat
4889 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4890 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4892 ## Double nodes on some external faces and create flat elements.
4893 # Flat elements are mainly used by some types of mechanic calculations.
4895 # Each group of the list must be constituted of faces.
4896 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4897 # @param theGroupsOfFaces - list of groups of faces
4898 # @return TRUE if operation has been completed successfully, FALSE otherwise
4899 # @ingroup l2_modif_duplicat
4900 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4901 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4903 ## identify all the elements around a geom shape, get the faces delimiting the hole
4905 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4906 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4908 def _getFunctor(self, funcType ):
4909 fn = self.functors[ funcType._v ]
4911 fn = self.smeshpyD.GetFunctor(funcType)
4912 fn.SetMesh(self.mesh)
4913 self.functors[ funcType._v ] = fn
4916 ## Return value of a functor for a given element
4917 # @param funcType an item of SMESH.FunctorType enum
4918 # Type "SMESH.FunctorType._items" in the Python Console to see all items.
4919 # @param elemId element or node ID
4920 # @param isElem @a elemId is ID of element or node
4921 # @return the functor value or zero in case of invalid arguments
4922 # @ingroup l1_measurements
4923 def FunctorValue(self, funcType, elemId, isElem=True):
4924 fn = self._getFunctor( funcType )
4925 if fn.GetElementType() == self.GetElementType(elemId, isElem):
4926 val = fn.GetValue(elemId)
4931 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4932 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4933 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4934 # @ingroup l1_measurements
4935 def GetLength(self, elemId=None):
4938 length = self.smeshpyD.GetLength(self)
4940 length = self.FunctorValue(SMESH.FT_Length, elemId)
4943 ## Get area of 2D element or sum of areas of all 2D mesh elements
4944 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4945 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4946 # @ingroup l1_measurements
4947 def GetArea(self, elemId=None):
4950 area = self.smeshpyD.GetArea(self)
4952 area = self.FunctorValue(SMESH.FT_Area, elemId)
4955 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4956 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4957 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4958 # @ingroup l1_measurements
4959 def GetVolume(self, elemId=None):
4962 volume = self.smeshpyD.GetVolume(self)
4964 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
4967 ## Get maximum element length.
4968 # @param elemId mesh element ID
4969 # @return element's maximum length value
4970 # @ingroup l1_measurements
4971 def GetMaxElementLength(self, elemId):
4972 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4973 ftype = SMESH.FT_MaxElementLength3D
4975 ftype = SMESH.FT_MaxElementLength2D
4976 return self.FunctorValue(ftype, elemId)
4978 ## Get aspect ratio of 2D or 3D element.
4979 # @param elemId mesh element ID
4980 # @return element's aspect ratio value
4981 # @ingroup l1_measurements
4982 def GetAspectRatio(self, elemId):
4983 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4984 ftype = SMESH.FT_AspectRatio3D
4986 ftype = SMESH.FT_AspectRatio
4987 return self.FunctorValue(ftype, elemId)
4989 ## Get warping angle of 2D element.
4990 # @param elemId mesh element ID
4991 # @return element's warping angle value
4992 # @ingroup l1_measurements
4993 def GetWarping(self, elemId):
4994 return self.FunctorValue(SMESH.FT_Warping, elemId)
4996 ## Get minimum angle of 2D element.
4997 # @param elemId mesh element ID
4998 # @return element's minimum angle value
4999 # @ingroup l1_measurements
5000 def GetMinimumAngle(self, elemId):
5001 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
5003 ## Get taper of 2D element.
5004 # @param elemId mesh element ID
5005 # @return element's taper value
5006 # @ingroup l1_measurements
5007 def GetTaper(self, elemId):
5008 return self.FunctorValue(SMESH.FT_Taper, elemId)
5010 ## Get skew of 2D element.
5011 # @param elemId mesh element ID
5012 # @return element's skew value
5013 # @ingroup l1_measurements
5014 def GetSkew(self, elemId):
5015 return self.FunctorValue(SMESH.FT_Skew, elemId)
5017 ## Return minimal and maximal value of a given functor.
5018 # @param funType a functor type, an item of SMESH.FunctorType enum
5019 # (one of SMESH.FunctorType._items)
5020 # @param meshPart a part of mesh (group, sub-mesh) to treat
5021 # @return tuple (min,max)
5022 # @ingroup l1_measurements
5023 def GetMinMax(self, funType, meshPart=None):
5024 unRegister = genObjUnRegister()
5025 if isinstance( meshPart, list ):
5026 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
5027 unRegister.set( meshPart )
5028 if isinstance( meshPart, Mesh ):
5029 meshPart = meshPart.mesh
5030 fun = self._getFunctor( funType )
5033 if hasattr( meshPart, "SetMesh" ):
5034 meshPart.SetMesh( self.mesh ) # set mesh to filter
5035 hist = fun.GetLocalHistogram( 1, False, meshPart )
5037 hist = fun.GetHistogram( 1, False )
5039 return hist[0].min, hist[0].max
5042 pass # end of Mesh class
5045 ## Private class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
5046 # with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
5048 class meshProxy(SMESH._objref_SMESH_Mesh):
5050 SMESH._objref_SMESH_Mesh.__init__(self)
5051 def __deepcopy__(self, memo=None):
5052 new = self.__class__()
5054 def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
5055 if len( args ) == 3:
5056 args += SMESH.ALL_NODES, True
5057 return SMESH._objref_SMESH_Mesh.CreateDimGroup( self, *args )
5059 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
5062 ## Private class wrapping SMESH.SMESH_SubMesh in order to add Compute()
5064 class submeshProxy(SMESH._objref_SMESH_subMesh):
5066 SMESH._objref_SMESH_subMesh.__init__(self)
5068 def __deepcopy__(self, memo=None):
5069 new = self.__class__()
5072 ## Compute the sub-mesh and return the status of the computation
5073 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
5074 # @return True or False
5076 # This is a method of SMESH.SMESH_submesh that can be obtained via Mesh.GetSubMesh() or
5077 # @ref smesh_algorithm.Mesh_Algorithm.GetSubMesh() "Mesh_Algorithm.GetSubMesh()".
5078 # @ingroup l2_submeshes
5079 def Compute(self,refresh=False):
5081 self.mesh = Mesh( smeshBuilder(), None, self.GetMesh())
5083 ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
5085 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
5086 smeshgui = salome.ImportComponentGUI("SMESH")
5087 smeshgui.Init(self.mesh.GetStudyId())
5088 smeshgui.SetMeshIcon( salome.ObjectToID( self ), ok, (self.GetNumberOfElements()==0) )
5089 if refresh: salome.sg.updateObjBrowser(True)
5094 omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy)
5097 ## Private class used to compensate change of CORBA API of SMESH_MeshEditor for backward
5098 # compatibility with old dump scripts which call SMESH_MeshEditor directly and not via
5101 class meshEditor(SMESH._objref_SMESH_MeshEditor):
5103 SMESH._objref_SMESH_MeshEditor.__init__(self)
5105 def __getattr__(self, name ): # method called if an attribute not found
5106 if not self.mesh: # look for name() method in Mesh class
5107 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
5108 if hasattr( self.mesh, name ):
5109 return getattr( self.mesh, name )
5110 if name == "ExtrusionAlongPathObjX":
5111 return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
5112 print("meshEditor: attribute '%s' NOT FOUND" % name)
5114 def __deepcopy__(self, memo=None):
5115 new = self.__class__()
5117 def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
5118 if len( args ) == 1: args += False,
5119 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
5120 def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
5121 if len( args ) == 2: args += False,
5122 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
5123 def MergeNodes(self,*args): # a 2nd arg added (NodesToKeep)
5124 if len( args ) == 1:
5125 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [] )
5126 NodesToKeep = args[1]
5127 unRegister = genObjUnRegister()
5129 if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
5130 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
5131 if not isinstance( NodesToKeep, list ):
5132 NodesToKeep = [ NodesToKeep ]
5133 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep )
5135 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
5137 ## Private class wrapping SMESH.SMESH_Pattern CORBA class in order to treat Notebook
5138 # variables in some methods
5140 class Pattern(SMESH._objref_SMESH_Pattern):
5142 def LoadFromFile(self, patternTextOrFile ):
5143 text = patternTextOrFile
5144 if os.path.exists( text ):
5145 text = open( patternTextOrFile ).read()
5147 return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
5149 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
5150 decrFun = lambda i: i-1
5151 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
5152 theMesh.SetParameters(Parameters)
5153 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
5155 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
5156 decrFun = lambda i: i-1
5157 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
5158 theMesh.SetParameters(Parameters)
5159 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
5161 def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
5162 if isinstance( mesh, Mesh ):
5163 mesh = mesh.GetMesh()
5164 return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
5166 # Registering the new proxy for Pattern
5167 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
5169 ## Private class used to bind methods creating algorithms to the class Mesh
5174 self.defaultAlgoType = ""
5175 self.algoTypeToClass = {}
5177 # Store a python class of algorithm
5178 def add(self, algoClass):
5179 if type( algoClass ).__name__ == 'classobj' and \
5180 hasattr( algoClass, "algoType"):
5181 self.algoTypeToClass[ algoClass.algoType ] = algoClass
5182 if not self.defaultAlgoType and \
5183 hasattr( algoClass, "isDefault") and algoClass.isDefault:
5184 self.defaultAlgoType = algoClass.algoType
5185 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
5187 # Create a copy of self and assign mesh to the copy
5188 def copy(self, mesh):
5189 other = algoCreator()
5190 other.defaultAlgoType = self.defaultAlgoType
5191 other.algoTypeToClass = self.algoTypeToClass
5195 # Create an instance of algorithm
5196 def __call__(self,algo="",geom=0,*args):
5197 algoType = self.defaultAlgoType
5198 for arg in args + (algo,geom):
5199 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
5201 if isinstance( arg, str ) and arg:
5203 if not algoType and self.algoTypeToClass:
5204 algoType = list(self.algoTypeToClass.keys())[0]
5205 if algoType in self.algoTypeToClass:
5206 #print "Create algo",algoType
5207 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
5208 raise RuntimeError("No class found for algo type %s" % algoType)
5211 ## Private class used to substitute and store variable parameters of hypotheses.
5213 class hypMethodWrapper:
5214 def __init__(self, hyp, method):
5216 self.method = method
5217 #print "REBIND:", method.__name__
5220 # call a method of hypothesis with calling SetVarParameter() before
5221 def __call__(self,*args):
5223 return self.method( self.hyp, *args ) # hypothesis method with no args
5225 #print "MethWrapper.__call__",self.method.__name__, args
5227 parsed = ParseParameters(*args) # replace variables with their values
5228 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
5229 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
5230 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
5231 # maybe there is a replaced string arg which is not variable
5232 result = self.method( self.hyp, *args )
5233 except ValueError as detail: # raised by ParseParameters()
5235 result = self.method( self.hyp, *args )
5236 except omniORB.CORBA.BAD_PARAM:
5237 raise ValueError(detail) # wrong variable name
5242 ## A helper class that calls UnRegister() of SALOME.GenericObj'es stored in it
5244 class genObjUnRegister:
5246 def __init__(self, genObj=None):
5247 self.genObjList = []
5251 def set(self, genObj):
5252 "Store one or a list of of SALOME.GenericObj'es"
5253 if isinstance( genObj, list ):
5254 self.genObjList.extend( genObj )
5256 self.genObjList.append( genObj )
5260 for genObj in self.genObjList:
5261 if genObj and hasattr( genObj, "UnRegister" ):
5265 ## Bind methods creating mesher plug-ins to the Mesh class
5267 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
5269 #print "pluginName: ", pluginName
5270 pluginBuilderName = pluginName + "Builder"
5272 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
5273 except Exception as e:
5274 from salome_utils import verbose
5275 if verbose(): print("Exception while loading %s: %s" % ( pluginBuilderName, e ))
5277 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5278 plugin = eval( pluginBuilderName )
5279 #print " plugin:" , str(plugin)
5281 # add methods creating algorithms to Mesh
5282 for k in dir( plugin ):
5283 if k[0] == '_': continue
5284 algo = getattr( plugin, k )
5285 #print " algo:", str(algo)
5286 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
5287 #print " meshMethod:" , str(algo.meshMethod)
5288 if not hasattr( Mesh, algo.meshMethod ):
5289 setattr( Mesh, algo.meshMethod, algoCreator() )
5291 getattr( Mesh, algo.meshMethod ).add( algo )