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
94 ## Private class used to workaround a problem that sometimes isinstance(m, Mesh) returns False
97 def __instancecheck__(cls, inst):
98 """Implement isinstance(inst, cls)."""
99 return any(cls.__subclasscheck__(c)
100 for c in {type(inst), inst.__class__})
102 def __subclasscheck__(cls, sub):
103 """Implement issubclass(sub, cls)."""
104 return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
106 ## @addtogroup l1_auxiliary
109 ## Convert an angle from degrees to radians
110 def DegreesToRadians(AngleInDegrees):
112 return AngleInDegrees * pi / 180.0
114 import salome_notebook
115 notebook = salome_notebook.notebook
116 # Salome notebook variable separator
119 ## Return list of variable values from salome notebook.
120 # The last argument, if is callable, is used to modify values got from notebook
121 def ParseParameters(*args):
126 if args and callable( args[-1] ):
127 args, varModifFun = args[:-1], args[-1]
128 for parameter in args:
130 Parameters += str(parameter) + var_separator
132 if isinstance(parameter,str):
133 # check if there is an inexistent variable name
134 if not notebook.isVariable(parameter):
135 raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
136 parameter = notebook.get(parameter)
139 parameter = varModifFun(parameter)
142 Result.append(parameter)
145 Parameters = Parameters[:-1]
146 Result.append( Parameters )
147 Result.append( hasVariables )
150 ## Parse parameters while converting variables to radians
151 def ParseAngles(*args):
152 return ParseParameters( *( args + (DegreesToRadians, )))
154 ## Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
155 # Parameters are stored in PointStruct.parameters attribute
156 def __initPointStruct(point,*args):
157 point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
159 SMESH.PointStruct.__init__ = __initPointStruct
161 ## Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
162 # Parameters are stored in AxisStruct.parameters attribute
163 def __initAxisStruct(ax,*args):
166 "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(object, 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] = 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
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
375 #print "--------------- smeshbuilder __init__ ---", created
378 SMESH._objref_SMESH_Gen.__init__(self)
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
789 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
790 elif CritType == FT_ConnectedElements:
791 # Check the Threshold
792 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
793 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
794 if not aCriterion.ThresholdID:
795 name = aThreshold.GetName()
797 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
798 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
799 elif isinstance(aThreshold, int): # node id
800 aCriterion.Threshold = aThreshold
801 elif isinstance(aThreshold, list): # 3 point coordinates
802 if len( aThreshold ) < 3:
803 raise ValueError, "too few point coordinates, must be 3"
804 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
805 elif isinstance(aThreshold, str):
806 if aThreshold.isdigit():
807 aCriterion.Threshold = aThreshold # node id
809 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
812 "The Threshold should either a VERTEX, or a node ID, "\
813 "or a list of point coordinates and not '%s'"%aThreshold
814 elif CritType == FT_ElemGeomType:
815 # Check the Threshold
817 aCriterion.Threshold = self.EnumToLong(aThreshold)
818 assert( aThreshold in SMESH.GeometryType._items )
820 if isinstance(aThreshold, int):
821 aCriterion.Threshold = aThreshold
823 raise TypeError, "The Threshold should be an integer or SMESH.GeometryType."
826 elif CritType == FT_EntityType:
827 # Check the Threshold
829 aCriterion.Threshold = self.EnumToLong(aThreshold)
830 assert( aThreshold in SMESH.EntityType._items )
832 if isinstance(aThreshold, int):
833 aCriterion.Threshold = aThreshold
835 raise TypeError, "The Threshold should be an integer or SMESH.EntityType."
839 elif CritType == FT_GroupColor:
840 # Check the Threshold
842 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
844 raise TypeError, "The threshold value should be of SALOMEDS.Color type"
846 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
847 FT_LinearOrQuadratic, FT_BadOrientedVolume,
848 FT_BareBorderFace, FT_BareBorderVolume,
849 FT_OverConstrainedFace, FT_OverConstrainedVolume,
850 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
851 # At this point the Threshold is unnecessary
852 if aThreshold == FT_LogicalNOT:
853 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
854 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
855 aCriterion.BinaryOp = aThreshold
859 aThreshold = float(aThreshold)
860 aCriterion.Threshold = aThreshold
862 raise TypeError, "The Threshold should be a number."
865 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
866 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
868 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
869 aCriterion.BinaryOp = self.EnumToLong(Threshold)
871 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
872 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
874 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
875 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
879 ## Create a filter with the given parameters
880 # @param elementType the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
881 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
882 # Type SMESH.FunctorType._items in the Python Console to see all values.
883 # Note that the items starting from FT_LessThan are not suitable for CritType.
884 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
885 # @param Threshold the threshold value (range of ids as string, shape, numeric)
886 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
887 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
888 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
889 # @param mesh the mesh to initialize the filter with
890 # @return SMESH_Filter
892 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
893 # @ingroup l1_controls
894 def GetFilter(self,elementType,
895 CritType=FT_Undefined,
898 UnaryOp=FT_Undefined,
901 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
902 aFilterMgr = self.CreateFilterManager()
903 aFilter = aFilterMgr.CreateFilter()
905 aCriteria.append(aCriterion)
906 aFilter.SetCriteria(aCriteria)
908 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
909 else : aFilter.SetMesh( mesh )
910 aFilterMgr.UnRegister()
913 ## Create a filter from criteria
914 # @param criteria a list of criteria
915 # @param binOp binary operator used when binary operator of criteria is undefined
916 # @return SMESH_Filter
918 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
919 # @ingroup l1_controls
920 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
921 for i in range( len( criteria ) - 1 ):
922 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
923 criteria[i].BinaryOp = self.EnumToLong( binOp )
924 aFilterMgr = self.CreateFilterManager()
925 aFilter = aFilterMgr.CreateFilter()
926 aFilter.SetCriteria(criteria)
927 aFilterMgr.UnRegister()
930 ## Create a numerical functor by its type
931 # @param theCriterion functor type - an item of SMESH.FunctorType enumeration.
932 # Type SMESH.FunctorType._items in the Python Console to see all items.
933 # Note that not all items correspond to numerical functors.
934 # @return SMESH_NumericalFunctor
935 # @ingroup l1_controls
936 def GetFunctor(self,theCriterion):
937 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
939 aFilterMgr = self.CreateFilterManager()
941 if theCriterion == FT_AspectRatio:
942 functor = aFilterMgr.CreateAspectRatio()
943 elif theCriterion == FT_AspectRatio3D:
944 functor = aFilterMgr.CreateAspectRatio3D()
945 elif theCriterion == FT_Warping:
946 functor = aFilterMgr.CreateWarping()
947 elif theCriterion == FT_MinimumAngle:
948 functor = aFilterMgr.CreateMinimumAngle()
949 elif theCriterion == FT_Taper:
950 functor = aFilterMgr.CreateTaper()
951 elif theCriterion == FT_Skew:
952 functor = aFilterMgr.CreateSkew()
953 elif theCriterion == FT_Area:
954 functor = aFilterMgr.CreateArea()
955 elif theCriterion == FT_Volume3D:
956 functor = aFilterMgr.CreateVolume3D()
957 elif theCriterion == FT_MaxElementLength2D:
958 functor = aFilterMgr.CreateMaxElementLength2D()
959 elif theCriterion == FT_MaxElementLength3D:
960 functor = aFilterMgr.CreateMaxElementLength3D()
961 elif theCriterion == FT_MultiConnection:
962 functor = aFilterMgr.CreateMultiConnection()
963 elif theCriterion == FT_MultiConnection2D:
964 functor = aFilterMgr.CreateMultiConnection2D()
965 elif theCriterion == FT_Length:
966 functor = aFilterMgr.CreateLength()
967 elif theCriterion == FT_Length2D:
968 functor = aFilterMgr.CreateLength2D()
969 elif theCriterion == FT_NodeConnectivityNumber:
970 functor = aFilterMgr.CreateNodeConnectivityNumber()
971 elif theCriterion == FT_BallDiameter:
972 functor = aFilterMgr.CreateBallDiameter()
974 print "Error: given parameter is not numerical functor type."
975 aFilterMgr.UnRegister()
979 # @param theHType mesh hypothesis type (string)
980 # @param theLibName mesh plug-in library name
981 # @return created hypothesis instance
982 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
983 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
985 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
988 # wrap hypothesis methods
989 #print "HYPOTHESIS", theHType
990 for meth_name in dir( hyp.__class__ ):
991 if not meth_name.startswith("Get") and \
992 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
993 method = getattr ( hyp.__class__, meth_name )
995 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
999 ## Get the mesh statistic
1000 # @return dictionary "element type" - "count of elements"
1001 # @ingroup l1_meshinfo
1002 def GetMeshInfo(self, obj):
1003 if isinstance( obj, Mesh ):
1006 if hasattr(obj, "GetMeshInfo"):
1007 values = obj.GetMeshInfo()
1008 for i in range(SMESH.Entity_Last._v):
1009 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1013 ## Get minimum distance between two objects
1015 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1016 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1018 # @param src1 first source object
1019 # @param src2 second source object
1020 # @param id1 node/element id from the first source
1021 # @param id2 node/element id from the second (or first) source
1022 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1023 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1024 # @return minimum distance value
1025 # @sa GetMinDistance()
1026 # @ingroup l1_measurements
1027 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1028 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1032 result = result.value
1035 ## Get measure structure specifying minimum distance data between two objects
1037 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1038 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1040 # @param src1 first source object
1041 # @param src2 second source object
1042 # @param id1 node/element id from the first source
1043 # @param id2 node/element id from the second (or first) source
1044 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1045 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1046 # @return Measure structure or None if input data is invalid
1048 # @ingroup l1_measurements
1049 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1050 if isinstance(src1, Mesh): src1 = src1.mesh
1051 if isinstance(src2, Mesh): src2 = src2.mesh
1052 if src2 is None and id2 != 0: src2 = src1
1053 if not hasattr(src1, "_narrow"): return None
1054 src1 = src1._narrow(SMESH.SMESH_IDSource)
1055 if not src1: return None
1056 unRegister = genObjUnRegister()
1059 e = m.GetMeshEditor()
1061 src1 = e.MakeIDSource([id1], SMESH.FACE)
1063 src1 = e.MakeIDSource([id1], SMESH.NODE)
1064 unRegister.set( src1 )
1066 if hasattr(src2, "_narrow"):
1067 src2 = src2._narrow(SMESH.SMESH_IDSource)
1068 if src2 and id2 != 0:
1070 e = m.GetMeshEditor()
1072 src2 = e.MakeIDSource([id2], SMESH.FACE)
1074 src2 = e.MakeIDSource([id2], SMESH.NODE)
1075 unRegister.set( src2 )
1078 aMeasurements = self.CreateMeasurements()
1079 unRegister.set( aMeasurements )
1080 result = aMeasurements.MinDistance(src1, src2)
1083 ## Get bounding box of the specified object(s)
1084 # @param objects single source object or list of source objects
1085 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1086 # @sa GetBoundingBox()
1087 # @ingroup l1_measurements
1088 def BoundingBox(self, objects):
1089 result = self.GetBoundingBox(objects)
1093 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1096 ## Get measure structure specifying bounding box data of the specified object(s)
1097 # @param objects single source object or list of source objects
1098 # @return Measure structure
1100 # @ingroup l1_measurements
1101 def GetBoundingBox(self, objects):
1102 if isinstance(objects, tuple):
1103 objects = list(objects)
1104 if not isinstance(objects, list):
1108 if isinstance(o, Mesh):
1109 srclist.append(o.mesh)
1110 elif hasattr(o, "_narrow"):
1111 src = o._narrow(SMESH.SMESH_IDSource)
1112 if src: srclist.append(src)
1115 aMeasurements = self.CreateMeasurements()
1116 result = aMeasurements.BoundingBox(srclist)
1117 aMeasurements.UnRegister()
1120 ## Get sum of lengths of all 1D elements in the mesh object.
1121 # @param obj mesh, submesh or group
1122 # @return sum of lengths of all 1D elements
1123 # @ingroup l1_measurements
1124 def GetLength(self, obj):
1125 if isinstance(obj, Mesh): obj = obj.mesh
1126 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1127 aMeasurements = self.CreateMeasurements()
1128 value = aMeasurements.Length(obj)
1129 aMeasurements.UnRegister()
1132 ## Get sum of areas of all 2D elements in the mesh object.
1133 # @param obj mesh, submesh or group
1134 # @return sum of areas of all 2D elements
1135 # @ingroup l1_measurements
1136 def GetArea(self, obj):
1137 if isinstance(obj, Mesh): obj = obj.mesh
1138 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1139 aMeasurements = self.CreateMeasurements()
1140 value = aMeasurements.Area(obj)
1141 aMeasurements.UnRegister()
1144 ## Get sum of volumes of all 3D elements in the mesh object.
1145 # @param obj mesh, submesh or group
1146 # @return sum of volumes of all 3D elements
1147 # @ingroup l1_measurements
1148 def GetVolume(self, obj):
1149 if isinstance(obj, Mesh): obj = obj.mesh
1150 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1151 aMeasurements = self.CreateMeasurements()
1152 value = aMeasurements.Volume(obj)
1153 aMeasurements.UnRegister()
1156 pass # end of class smeshBuilder
1159 #Registering the new proxy for SMESH_Gen
1160 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1162 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1163 # interface to create or load meshes.
1168 # salome.salome_init()
1169 # from salome.smesh import smeshBuilder
1170 # smesh = smeshBuilder.New(salome.myStudy)
1172 # @param study SALOME study, generally obtained by salome.myStudy.
1173 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1174 # @return smeshBuilder instance
1176 def New( study, instance=None):
1178 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1179 interface to create or load meshes.
1183 salome.salome_init()
1184 from salome.smesh import smeshBuilder
1185 smesh = smeshBuilder.New(salome.myStudy)
1188 study SALOME study, generally obtained by salome.myStudy.
1189 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1191 smeshBuilder instance
1199 smeshInst = smeshBuilder()
1200 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1201 smeshInst.init_smesh(study)
1205 # Public class: Mesh
1206 # ==================
1208 ## This class allows defining and managing a mesh.
1209 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1210 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1211 # new nodes and elements and by changing the existing entities), to get information
1212 # about a mesh and to export a mesh in different formats.
1214 __metaclass__ = MeshMeta
1222 # Create a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1223 # sets the GUI name of this mesh to \a name.
1224 # @param smeshpyD an instance of smeshBuilder class
1225 # @param geompyD an instance of geomBuilder class
1226 # @param obj Shape to be meshed or SMESH_Mesh object
1227 # @param name Study name of the mesh
1228 # @ingroup l2_construct
1229 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1230 self.smeshpyD=smeshpyD
1231 self.geompyD=geompyD
1236 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1239 # publish geom of mesh (issue 0021122)
1240 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1242 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1243 if studyID != geompyD.myStudyId:
1244 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1247 geo_name = name + " shape"
1249 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1250 geompyD.addToStudy( self.geom, geo_name )
1251 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1253 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1256 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1258 self.smeshpyD.SetName(self.mesh, name)
1260 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1263 self.geom = self.mesh.GetShapeToMesh()
1265 self.editor = self.mesh.GetMeshEditor()
1266 self.functors = [None] * SMESH.FT_Undefined._v
1268 # set self to algoCreator's
1269 for attrName in dir(self):
1270 attr = getattr( self, attrName )
1271 if isinstance( attr, algoCreator ):
1272 setattr( self, attrName, attr.copy( self ))
1277 ## Destructor. Clean-up resources
1280 #self.mesh.UnRegister()
1284 ## Initialize the Mesh object from an instance of SMESH_Mesh interface
1285 # @param theMesh a SMESH_Mesh object
1286 # @ingroup l2_construct
1287 def SetMesh(self, theMesh):
1288 # do not call Register() as this prevents mesh servant deletion at closing study
1289 #if self.mesh: self.mesh.UnRegister()
1292 #self.mesh.Register()
1293 self.geom = self.mesh.GetShapeToMesh()
1296 ## Return the mesh, that is an instance of SMESH_Mesh interface
1297 # @return a SMESH_Mesh object
1298 # @ingroup l2_construct
1302 ## Get the name of the mesh
1303 # @return the name of the mesh as a string
1304 # @ingroup l2_construct
1306 name = GetName(self.GetMesh())
1309 ## Set a name to the mesh
1310 # @param name a new name of the mesh
1311 # @ingroup l2_construct
1312 def SetName(self, name):
1313 self.smeshpyD.SetName(self.GetMesh(), name)
1315 ## Get a sub-mesh object associated to a \a geom geometrical object.
1316 # @param geom a geometrical object (shape)
1317 # @param name a name for the sub-mesh in the Object Browser
1318 # @return an object of type SMESH.SMESH_subMesh, representing a part of mesh,
1319 # which lies on the given shape
1321 # The sub-mesh object gives access to the IDs of nodes and elements.
1322 # The sub-mesh object has the following methods:
1323 # - SMESH.SMESH_subMesh.GetNumberOfElements()
1324 # - SMESH.SMESH_subMesh.GetNumberOfNodes( all )
1325 # - SMESH.SMESH_subMesh.GetElementsId()
1326 # - SMESH.SMESH_subMesh.GetElementsByType( ElementType )
1327 # - SMESH.SMESH_subMesh.GetNodesId()
1328 # - SMESH.SMESH_subMesh.GetSubShape()
1329 # - SMESH.SMESH_subMesh.GetFather()
1330 # - SMESH.SMESH_subMesh.GetId()
1331 # @note A sub-mesh is implicitly created when a sub-shape is specified at
1332 # creating an algorithm, for example: <code>algo1D = mesh.Segment(geom=Edge_1) </code>
1333 # creates a sub-mesh on @c Edge_1 and assign Wire Discretization algorithm to it.
1334 # The created sub-mesh can be retrieved from the algorithm:
1335 # <code>submesh = algo1D.GetSubMesh()</code>
1336 # @ingroup l2_submeshes
1337 def GetSubMesh(self, geom, name):
1338 AssureGeomPublished( self, geom, name )
1339 submesh = self.mesh.GetSubMesh( geom, name )
1342 ## Return the shape associated to the mesh
1343 # @return a GEOM_Object
1344 # @ingroup l2_construct
1348 ## Associate the given shape to the mesh (entails the recreation of the mesh)
1349 # @param geom the shape to be meshed (GEOM_Object)
1350 # @ingroup l2_construct
1351 def SetShape(self, geom):
1352 self.mesh = self.smeshpyD.CreateMesh(geom)
1354 ## Load mesh from the study after opening the study
1358 ## Return true if the hypotheses are defined well
1359 # @param theSubObject a sub-shape of a mesh shape
1360 # @return True or False
1361 # @ingroup l2_construct
1362 def IsReadyToCompute(self, theSubObject):
1363 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1365 ## Return errors of hypotheses definition.
1366 # The list of errors is empty if everything is OK.
1367 # @param theSubObject a sub-shape of a mesh shape
1368 # @return a list of errors
1369 # @ingroup l2_construct
1370 def GetAlgoState(self, theSubObject):
1371 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1373 ## Return a geometrical object on which the given element was built.
1374 # The returned geometrical object, if not nil, is either found in the
1375 # study or published by this method with the given name
1376 # @param theElementID the id of the mesh element
1377 # @param theGeomName the user-defined name of the geometrical object
1378 # @return GEOM::GEOM_Object instance
1379 # @ingroup l1_meshinfo
1380 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1381 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1383 ## Return the mesh dimension depending on the dimension of the underlying shape
1384 # or, if the mesh is not based on any shape, basing on deimension of elements
1385 # @return mesh dimension as an integer value [0,3]
1386 # @ingroup l1_meshinfo
1387 def MeshDimension(self):
1388 if self.mesh.HasShapeToMesh():
1389 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1390 if len( shells ) > 0 :
1392 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1394 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1399 if self.NbVolumes() > 0: return 3
1400 if self.NbFaces() > 0: return 2
1401 if self.NbEdges() > 0: return 1
1404 ## Evaluate size of prospective mesh on a shape
1405 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1406 # To know predicted number of e.g. edges, inquire it this way
1407 # Evaluate()[ EnumToLong( Entity_Edge )]
1408 # @ingroup l2_construct
1409 def Evaluate(self, geom=0):
1410 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1412 geom = self.mesh.GetShapeToMesh()
1415 return self.smeshpyD.Evaluate(self.mesh, geom)
1418 ## Compute the mesh and return the status of the computation
1419 # @param geom geomtrical shape on which mesh data should be computed
1420 # @param discardModifs if True and the mesh has been edited since
1421 # a last total re-compute and that may prevent successful partial re-compute,
1422 # then the mesh is cleaned before Compute()
1423 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1424 # @return True or False
1425 # @ingroup l2_construct
1426 def Compute(self, geom=0, discardModifs=False, refresh=False):
1427 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1429 geom = self.mesh.GetShapeToMesh()
1434 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1436 ok = self.smeshpyD.Compute(self.mesh, geom)
1437 except SALOME.SALOME_Exception, ex:
1438 print "Mesh computation failed, exception caught:"
1439 print " ", ex.details.text
1442 print "Mesh computation failed, exception caught:"
1443 traceback.print_exc()
1447 # Treat compute errors
1448 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1450 for err in computeErrors:
1451 if self.mesh.HasShapeToMesh():
1452 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1454 stdErrors = ["OK", #COMPERR_OK
1455 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1456 "std::exception", #COMPERR_STD_EXCEPTION
1457 "OCC exception", #COMPERR_OCC_EXCEPTION
1458 "..", #COMPERR_SLM_EXCEPTION
1459 "Unknown exception", #COMPERR_EXCEPTION
1460 "Memory allocation problem", #COMPERR_MEMORY_PB
1461 "Algorithm failed", #COMPERR_ALGO_FAILED
1462 "Unexpected geometry", #COMPERR_BAD_SHAPE
1463 "Warning", #COMPERR_WARNING
1464 "Computation cancelled",#COMPERR_CANCELED
1465 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1467 if err.code < len(stdErrors): errText = stdErrors[err.code]
1469 errText = "code %s" % -err.code
1470 if errText: errText += ". "
1471 errText += err.comment
1472 if allReasons: allReasons += "\n"
1474 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1476 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1480 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1482 if err.isGlobalAlgo:
1490 reason = '%s %sD algorithm is missing' % (glob, dim)
1491 elif err.state == HYP_MISSING:
1492 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1493 % (glob, dim, name, dim))
1494 elif err.state == HYP_NOTCONFORM:
1495 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1496 elif err.state == HYP_BAD_PARAMETER:
1497 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1498 % ( glob, dim, name ))
1499 elif err.state == HYP_BAD_GEOMETRY:
1500 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1501 'geometry' % ( glob, dim, name ))
1502 elif err.state == HYP_HIDDEN_ALGO:
1503 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1504 'algorithm of upper dimension generating %sD mesh'
1505 % ( glob, dim, name, glob, dim ))
1507 reason = ("For unknown reason. "
1508 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1510 if allReasons: allReasons += "\n"
1511 allReasons += "- " + reason
1513 if not ok or allReasons != "":
1514 msg = '"' + GetName(self.mesh) + '"'
1515 if ok: msg += " has been computed with warnings"
1516 else: msg += " has not been computed"
1517 if allReasons != "": msg += ":"
1522 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1523 if not isinstance( refresh, list): # not a call from subMesh.Compute()
1524 smeshgui = salome.ImportComponentGUI("SMESH")
1525 smeshgui.Init(self.mesh.GetStudyId())
1526 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1527 if refresh: salome.sg.updateObjBrowser(True)
1531 ## Return a list of error messages (SMESH.ComputeError) of the last Compute()
1532 # @ingroup l2_construct
1533 def GetComputeErrors(self, shape=0 ):
1535 shape = self.mesh.GetShapeToMesh()
1536 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1538 ## Return a name of a sub-shape by its ID
1539 # @param subShapeID a unique ID of a sub-shape
1540 # @return a string describing the sub-shape; possible variants:
1541 # - "Face_12" (published sub-shape)
1542 # - FACE #3 (not published sub-shape)
1543 # - sub-shape #3 (invalid sub-shape ID)
1544 # - #3 (error in this function)
1545 # @ingroup l1_auxiliary
1546 def GetSubShapeName(self, subShapeID ):
1547 if not self.mesh.HasShapeToMesh():
1551 mainIOR = salome.orb.object_to_string( self.GetShape() )
1552 for sname in salome.myStudyManager.GetOpenStudies():
1553 s = salome.myStudyManager.GetStudyByName(sname)
1555 mainSO = s.FindObjectIOR(mainIOR)
1556 if not mainSO: continue
1558 shapeText = '"%s"' % mainSO.GetName()
1559 subIt = s.NewChildIterator(mainSO)
1561 subSO = subIt.Value()
1563 obj = subSO.GetObject()
1564 if not obj: continue
1565 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1568 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1571 if ids == subShapeID:
1572 shapeText = '"%s"' % subSO.GetName()
1575 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1577 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1579 shapeText = 'sub-shape #%s' % (subShapeID)
1581 shapeText = "#%s" % (subShapeID)
1584 ## Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1585 # error of an algorithm
1586 # @param publish if @c True, the returned groups will be published in the study
1587 # @return a list of GEOM groups each named after a failed algorithm
1588 # @ingroup l2_construct
1589 def GetFailedShapes(self, publish=False):
1592 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1593 for err in computeErrors:
1594 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1595 if not shape: continue
1596 if err.algoName in algo2shapes:
1597 algo2shapes[ err.algoName ].append( shape )
1599 algo2shapes[ err.algoName ] = [ shape ]
1603 for algoName, shapes in algo2shapes.items():
1605 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1606 otherTypeShapes = []
1608 group = self.geompyD.CreateGroup( self.geom, groupType )
1609 for shape in shapes:
1610 if shape.GetShapeType() == shapes[0].GetShapeType():
1611 sameTypeShapes.append( shape )
1613 otherTypeShapes.append( shape )
1614 self.geompyD.UnionList( group, sameTypeShapes )
1616 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1618 group.SetName( algoName )
1619 groups.append( group )
1620 shapes = otherTypeShapes
1623 for group in groups:
1624 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1627 ## Return sub-mesh objects list in meshing order
1628 # @return list of lists of sub-meshes
1629 # @ingroup l2_construct
1630 def GetMeshOrder(self):
1631 return self.mesh.GetMeshOrder()
1633 ## Set order in which concurrent sub-meshes should be meshed
1634 # @param submeshes list of lists of sub-meshes
1635 # @ingroup l2_construct
1636 def SetMeshOrder(self, submeshes):
1637 return self.mesh.SetMeshOrder(submeshes)
1639 ## Remove all nodes and elements generated on geometry. Imported elements remain.
1640 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1641 # @ingroup l2_construct
1642 def Clear(self, refresh=False):
1644 if ( salome.sg.hasDesktop() and
1645 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1646 smeshgui = salome.ImportComponentGUI("SMESH")
1647 smeshgui.Init(self.mesh.GetStudyId())
1648 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1649 if refresh: salome.sg.updateObjBrowser(True)
1651 ## Remove all nodes and elements of indicated shape
1652 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1653 # @param geomId the ID of a sub-shape to remove elements on
1654 # @ingroup l2_submeshes
1655 def ClearSubMesh(self, geomId, refresh=False):
1656 self.mesh.ClearSubMesh(geomId)
1657 if salome.sg.hasDesktop():
1658 smeshgui = salome.ImportComponentGUI("SMESH")
1659 smeshgui.Init(self.mesh.GetStudyId())
1660 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1661 if refresh: salome.sg.updateObjBrowser(True)
1663 ## Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1664 # @param fineness [0.0,1.0] defines mesh fineness
1665 # @return True or False
1666 # @ingroup l3_algos_basic
1667 def AutomaticTetrahedralization(self, fineness=0):
1668 dim = self.MeshDimension()
1670 self.RemoveGlobalHypotheses()
1671 self.Segment().AutomaticLength(fineness)
1673 self.Triangle().LengthFromEdges()
1678 return self.Compute()
1680 ## Compute an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1681 # @param fineness [0.0, 1.0] defines mesh fineness
1682 # @return True or False
1683 # @ingroup l3_algos_basic
1684 def AutomaticHexahedralization(self, fineness=0):
1685 dim = self.MeshDimension()
1686 # assign the hypotheses
1687 self.RemoveGlobalHypotheses()
1688 self.Segment().AutomaticLength(fineness)
1695 return self.Compute()
1697 ## Assign a hypothesis
1698 # @param hyp a hypothesis to assign
1699 # @param geom a subhape of mesh geometry
1700 # @return SMESH.Hypothesis_Status
1701 # @ingroup l2_editing
1702 def AddHypothesis(self, hyp, geom=0):
1703 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1704 hyp, geom = geom, hyp
1705 if isinstance( hyp, Mesh_Algorithm ):
1706 hyp = hyp.GetAlgorithm()
1711 geom = self.mesh.GetShapeToMesh()
1714 if self.mesh.HasShapeToMesh():
1715 hyp_type = hyp.GetName()
1716 lib_name = hyp.GetLibName()
1717 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1718 # if checkAll and geom:
1719 # checkAll = geom.GetType() == 37
1721 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1723 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1724 status = self.mesh.AddHypothesis(geom, hyp)
1726 status = HYP_BAD_GEOMETRY,""
1727 hyp_name = GetName( hyp )
1730 geom_name = geom.GetName()
1731 isAlgo = hyp._narrow( SMESH_Algo )
1732 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1735 ## Return True if an algorithm of hypothesis is assigned to a given shape
1736 # @param hyp a hypothesis to check
1737 # @param geom a subhape of mesh geometry
1738 # @return True of False
1739 # @ingroup l2_editing
1740 def IsUsedHypothesis(self, hyp, geom):
1741 if not hyp: # or not geom
1743 if isinstance( hyp, Mesh_Algorithm ):
1744 hyp = hyp.GetAlgorithm()
1746 hyps = self.GetHypothesisList(geom)
1748 if h.GetId() == hyp.GetId():
1752 ## Unassign a hypothesis
1753 # @param hyp a hypothesis to unassign
1754 # @param geom a sub-shape of mesh geometry
1755 # @return SMESH.Hypothesis_Status
1756 # @ingroup l2_editing
1757 def RemoveHypothesis(self, hyp, geom=0):
1760 if isinstance( hyp, Mesh_Algorithm ):
1761 hyp = hyp.GetAlgorithm()
1767 if self.IsUsedHypothesis( hyp, shape ):
1768 return self.mesh.RemoveHypothesis( shape, hyp )
1769 hypName = GetName( hyp )
1770 geoName = GetName( shape )
1771 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1774 ## Get the list of hypotheses added on a geometry
1775 # @param geom a sub-shape of mesh geometry
1776 # @return the sequence of SMESH_Hypothesis
1777 # @ingroup l2_editing
1778 def GetHypothesisList(self, geom):
1779 return self.mesh.GetHypothesisList( geom )
1781 ## Remove all global hypotheses
1782 # @ingroup l2_editing
1783 def RemoveGlobalHypotheses(self):
1784 current_hyps = self.mesh.GetHypothesisList( self.geom )
1785 for hyp in current_hyps:
1786 self.mesh.RemoveHypothesis( self.geom, hyp )
1790 ## Export the mesh in a file in MED format
1791 ## allowing to overwrite the file if it exists or add the exported data to its contents
1792 # @param f is the file name
1793 # @param auto_groups boolean parameter for creating/not creating
1794 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1795 # the typical use is auto_groups=False.
1796 # @param version MED format version (MED_V2_1 or MED_V2_2,
1797 # the latter meaning any current version). The parameter is
1798 # obsolete since MED_V2_1 is no longer supported.
1799 # @param overwrite boolean parameter for overwriting/not overwriting the file
1800 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1801 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1802 # - 1D if all mesh nodes lie on OX coordinate axis, or
1803 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1804 # - 3D in the rest cases.<br>
1805 # If @a autoDimension is @c False, the space dimension is always 3.
1806 # @param fields list of GEOM fields defined on the shape to mesh.
1807 # @param geomAssocFields each character of this string means a need to export a
1808 # corresponding field; correspondence between fields and characters is following:
1809 # - 'v' stands for "_vertices _" field;
1810 # - 'e' stands for "_edges _" field;
1811 # - 'f' stands for "_faces _" field;
1812 # - 's' stands for "_solids _" field.
1813 # @ingroup l2_impexp
1814 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1815 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1816 if meshPart or fields or geomAssocFields:
1817 unRegister = genObjUnRegister()
1818 if isinstance( meshPart, list ):
1819 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1820 unRegister.set( meshPart )
1821 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1822 fields, geomAssocFields)
1824 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1826 ## Export the mesh in a file in SAUV format
1827 # @param f is the file name
1828 # @param auto_groups boolean parameter for creating/not creating
1829 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1830 # the typical use is auto_groups=false.
1831 # @ingroup l2_impexp
1832 def ExportSAUV(self, f, auto_groups=0):
1833 self.mesh.ExportSAUV(f, auto_groups)
1835 ## Export the mesh in a file in DAT format
1836 # @param f the file name
1837 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1838 # @ingroup l2_impexp
1839 def ExportDAT(self, f, meshPart=None):
1841 unRegister = genObjUnRegister()
1842 if isinstance( meshPart, list ):
1843 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1844 unRegister.set( meshPart )
1845 self.mesh.ExportPartToDAT( meshPart, f )
1847 self.mesh.ExportDAT(f)
1849 ## Export the mesh in a file in UNV format
1850 # @param f the file name
1851 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1852 # @ingroup l2_impexp
1853 def ExportUNV(self, f, meshPart=None):
1855 unRegister = genObjUnRegister()
1856 if isinstance( meshPart, list ):
1857 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1858 unRegister.set( meshPart )
1859 self.mesh.ExportPartToUNV( meshPart, f )
1861 self.mesh.ExportUNV(f)
1863 ## Export the mesh in a file in STL format
1864 # @param f the file name
1865 # @param ascii defines the file encoding
1866 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1867 # @ingroup l2_impexp
1868 def ExportSTL(self, f, ascii=1, meshPart=None):
1870 unRegister = genObjUnRegister()
1871 if isinstance( meshPart, list ):
1872 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1873 unRegister.set( meshPart )
1874 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1876 self.mesh.ExportSTL(f, ascii)
1878 ## Export the mesh in a file in CGNS format
1879 # @param f is the file name
1880 # @param overwrite boolean parameter for overwriting/not overwriting the file
1881 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1882 # @ingroup l2_impexp
1883 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1884 unRegister = genObjUnRegister()
1885 if isinstance( meshPart, list ):
1886 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1887 unRegister.set( meshPart )
1888 if isinstance( meshPart, Mesh ):
1889 meshPart = meshPart.mesh
1891 meshPart = self.mesh
1892 self.mesh.ExportCGNS(meshPart, f, overwrite)
1894 ## Export the mesh in a file in GMF format.
1895 # GMF files must have .mesh extension for the ASCII format and .meshb for
1896 # the bynary format. Other extensions are not allowed.
1897 # @param f is the file name
1898 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1899 # @ingroup l2_impexp
1900 def ExportGMF(self, f, meshPart=None):
1901 unRegister = genObjUnRegister()
1902 if isinstance( meshPart, list ):
1903 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1904 unRegister.set( meshPart )
1905 if isinstance( meshPart, Mesh ):
1906 meshPart = meshPart.mesh
1908 meshPart = self.mesh
1909 self.mesh.ExportGMF(meshPart, f, True)
1911 ## Deprecated, used only for compatibility! Please, use ExportMED() method instead.
1912 # Export the mesh in a file in MED format
1913 # allowing to overwrite the file if it exists or add the exported data to its contents
1914 # @param f the file name
1915 # @param version MED format version (MED_V2_1 or MED_V2_2,
1916 # the latter meaning any current version). The parameter is
1917 # obsolete since MED_V2_1 is no longer supported.
1918 # @param opt boolean parameter for creating/not creating
1919 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1920 # @param overwrite boolean parameter for overwriting/not overwriting the file
1921 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1922 # - 1D if all mesh nodes lie on OX coordinate axis, or
1923 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1924 # - 3D in the rest cases.<br>
1925 # If @a autoDimension is @c False, the space dimension is always 3.
1926 # @ingroup l2_impexp
1927 def ExportToMED(self, f, version=MED_V2_2, opt=0, overwrite=1, autoDimension=True):
1928 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1930 # Operations with groups:
1931 # ----------------------
1933 ## Create an empty mesh group
1934 # @param elementType the type of elements in the group; either of
1935 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1936 # @param name the name of the mesh group
1937 # @return SMESH_Group
1938 # @ingroup l2_grps_create
1939 def CreateEmptyGroup(self, elementType, name):
1940 return self.mesh.CreateGroup(elementType, name)
1942 ## Create a mesh group based on the geometric object \a grp
1943 # and gives a \a name, \n if this parameter is not defined
1944 # the name is the same as the geometric group name \n
1945 # Note: Works like GroupOnGeom().
1946 # @param grp a geometric group, a vertex, an edge, a face or a solid
1947 # @param name the name of the mesh group
1948 # @return SMESH_GroupOnGeom
1949 # @ingroup l2_grps_create
1950 def Group(self, grp, name=""):
1951 return self.GroupOnGeom(grp, name)
1953 ## Create a mesh group based on the geometrical object \a grp
1954 # and gives a \a name, \n if this parameter is not defined
1955 # the name is the same as the geometrical group name
1956 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1957 # @param name the name of the mesh group
1958 # @param typ the type of elements in the group; either of
1959 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
1960 # automatically detected by the type of the geometry
1961 # @return SMESH_GroupOnGeom
1962 # @ingroup l2_grps_create
1963 def GroupOnGeom(self, grp, name="", typ=None):
1964 AssureGeomPublished( self, grp, name )
1966 name = grp.GetName()
1968 typ = self._groupTypeFromShape( grp )
1969 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1971 ## Pivate method to get a type of group on geometry
1972 def _groupTypeFromShape( self, shape ):
1973 tgeo = str(shape.GetShapeType())
1974 if tgeo == "VERTEX":
1976 elif tgeo == "EDGE":
1978 elif tgeo == "FACE" or tgeo == "SHELL":
1980 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1982 elif tgeo == "COMPOUND":
1983 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1985 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1986 return self._groupTypeFromShape( sub[0] )
1989 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1992 ## Create a mesh group with given \a name based on the \a filter which
1993 ## is a special type of group dynamically updating it's contents during
1994 ## mesh modification
1995 # @param typ the type of elements in the group; either of
1996 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1997 # @param name the name of the mesh group
1998 # @param filter the filter defining group contents
1999 # @return SMESH_GroupOnFilter
2000 # @ingroup l2_grps_create
2001 def GroupOnFilter(self, typ, name, filter):
2002 return self.mesh.CreateGroupFromFilter(typ, name, filter)
2004 ## Create a mesh group by the given ids of elements
2005 # @param groupName the name of the mesh group
2006 # @param elementType the type of elements in the group; either of
2007 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2008 # @param elemIDs either the list of ids, group, sub-mesh, or filter
2009 # @return SMESH_Group
2010 # @ingroup l2_grps_create
2011 def MakeGroupByIds(self, groupName, elementType, elemIDs):
2012 group = self.mesh.CreateGroup(elementType, groupName)
2013 if hasattr( elemIDs, "GetIDs" ):
2014 if hasattr( elemIDs, "SetMesh" ):
2015 elemIDs.SetMesh( self.GetMesh() )
2016 group.AddFrom( elemIDs )
2021 ## Create a mesh group by the given conditions
2022 # @param groupName the name of the mesh group
2023 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2024 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
2025 # Type SMESH.FunctorType._items in the Python Console to see all values.
2026 # Note that the items starting from FT_LessThan are not suitable for CritType.
2027 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
2028 # @param Threshold the threshold value (range of ids as string, shape, numeric)
2029 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2030 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2031 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2032 # @return SMESH_GroupOnFilter
2033 # @ingroup l2_grps_create
2037 CritType=FT_Undefined,
2040 UnaryOp=FT_Undefined,
2042 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2043 group = self.MakeGroupByCriterion(groupName, aCriterion)
2046 ## Create a mesh group by the given criterion
2047 # @param groupName the name of the mesh group
2048 # @param Criterion the instance of Criterion class
2049 # @return SMESH_GroupOnFilter
2050 # @ingroup l2_grps_create
2051 def MakeGroupByCriterion(self, groupName, Criterion):
2052 return self.MakeGroupByCriteria( groupName, [Criterion] )
2054 ## Create a mesh group by the given criteria (list of criteria)
2055 # @param groupName the name of the mesh group
2056 # @param theCriteria the list of criteria
2057 # @param binOp binary operator used when binary operator of criteria is undefined
2058 # @return SMESH_GroupOnFilter
2059 # @ingroup l2_grps_create
2060 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2061 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2062 group = self.MakeGroupByFilter(groupName, aFilter)
2065 ## Create a mesh group by the given filter
2066 # @param groupName the name of the mesh group
2067 # @param theFilter the instance of Filter class
2068 # @return SMESH_GroupOnFilter
2069 # @ingroup l2_grps_create
2070 def MakeGroupByFilter(self, groupName, theFilter):
2071 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2072 #theFilter.SetMesh( self.mesh )
2073 #group.AddFrom( theFilter )
2074 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2078 # @ingroup l2_grps_delete
2079 def RemoveGroup(self, group):
2080 self.mesh.RemoveGroup(group)
2082 ## Remove a group with its contents
2083 # @ingroup l2_grps_delete
2084 def RemoveGroupWithContents(self, group):
2085 self.mesh.RemoveGroupWithContents(group)
2087 ## Get the list of groups existing in the mesh in the order
2088 # of creation (starting from the oldest one)
2089 # @param elemType type of elements the groups contain; either of
2090 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2091 # by default groups of elements of all types are returned
2092 # @return a sequence of SMESH_GroupBase
2093 # @ingroup l2_grps_create
2094 def GetGroups(self, elemType = SMESH.ALL):
2095 groups = self.mesh.GetGroups()
2096 if elemType == SMESH.ALL:
2100 if g.GetType() == elemType:
2101 typedGroups.append( g )
2106 ## Get the number of groups existing in the mesh
2107 # @return the quantity of groups as an integer value
2108 # @ingroup l2_grps_create
2110 return self.mesh.NbGroups()
2112 ## Get the list of names of groups existing in the mesh
2113 # @return list of strings
2114 # @ingroup l2_grps_create
2115 def GetGroupNames(self):
2116 groups = self.GetGroups()
2118 for group in groups:
2119 names.append(group.GetName())
2122 ## Find groups by name and type
2123 # @param name name of the group of interest
2124 # @param elemType type of elements the groups contain; either of
2125 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2126 # by default one group of any type of elements is returned
2127 # if elemType == SMESH.ALL then all groups of any type are returned
2128 # @return a list of SMESH_GroupBase's
2129 # @ingroup l2_grps_create
2130 def GetGroupByName(self, name, elemType = None):
2132 for group in self.GetGroups():
2133 if group.GetName() == name:
2134 if elemType is None:
2136 if ( elemType == SMESH.ALL or
2137 group.GetType() == elemType ):
2138 groups.append( group )
2141 ## Produce a union of two groups.
2142 # A new group is created. All mesh elements that are
2143 # present in the initial groups are added to the new one
2144 # @return an instance of SMESH_Group
2145 # @ingroup l2_grps_operon
2146 def UnionGroups(self, group1, group2, name):
2147 return self.mesh.UnionGroups(group1, group2, name)
2149 ## Produce a union list of groups.
2150 # New group is created. All mesh elements that are present in
2151 # initial groups are added to the new one
2152 # @return an instance of SMESH_Group
2153 # @ingroup l2_grps_operon
2154 def UnionListOfGroups(self, groups, name):
2155 return self.mesh.UnionListOfGroups(groups, name)
2157 ## Prodice an intersection of two groups.
2158 # A new group is created. All mesh elements that are common
2159 # for the two initial groups are added to the new one.
2160 # @return an instance of SMESH_Group
2161 # @ingroup l2_grps_operon
2162 def IntersectGroups(self, group1, group2, name):
2163 return self.mesh.IntersectGroups(group1, group2, name)
2165 ## Produce an intersection of groups.
2166 # New group is created. All mesh elements that are present in all
2167 # initial groups simultaneously are added to the new one
2168 # @return an instance of SMESH_Group
2169 # @ingroup l2_grps_operon
2170 def IntersectListOfGroups(self, groups, name):
2171 return self.mesh.IntersectListOfGroups(groups, name)
2173 ## Produce a cut of two groups.
2174 # A new group is created. All mesh elements that are present in
2175 # the main group but are not present in the tool group are added to the new one
2176 # @return an instance of SMESH_Group
2177 # @ingroup l2_grps_operon
2178 def CutGroups(self, main_group, tool_group, name):
2179 return self.mesh.CutGroups(main_group, tool_group, name)
2181 ## Produce a cut of groups.
2182 # A new group is created. All mesh elements that are present in main groups
2183 # but do not present in tool groups are added to the new one
2184 # @return an instance of SMESH_Group
2185 # @ingroup l2_grps_operon
2186 def CutListOfGroups(self, main_groups, tool_groups, name):
2187 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2190 # Create a standalone group of entities basing on nodes of other groups.
2191 # \param groups - list of reference groups, sub-meshes or filters, of any type.
2192 # \param elemType - a type of elements to include to the new group; either of
2193 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2194 # \param name - a name of the new group.
2195 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2196 # basing on number of element nodes common with reference \a groups.
2197 # Meaning of possible values are:
2198 # - SMESH.ALL_NODES - include if all nodes are common,
2199 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2200 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2201 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2202 # \param underlyingOnly - if \c True (default), an element is included to the
2203 # new group provided that it is based on nodes of an element of \a groups;
2204 # in this case the reference \a groups are supposed to be of higher dimension
2205 # than \a elemType, which can be useful for example to get all faces lying on
2206 # volumes of the reference \a groups.
2207 # @return an instance of SMESH_Group
2208 # @ingroup l2_grps_operon
2209 def CreateDimGroup(self, groups, elemType, name,
2210 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2211 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2213 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2216 ## Convert group on geom into standalone group
2217 # @ingroup l2_grps_operon
2218 def ConvertToStandalone(self, group):
2219 return self.mesh.ConvertToStandalone(group)
2221 # Get some info about mesh:
2222 # ------------------------
2224 ## Return the log of nodes and elements added or removed
2225 # since the previous clear of the log.
2226 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2227 # @return list of log_block structures:
2232 # @ingroup l1_auxiliary
2233 def GetLog(self, clearAfterGet):
2234 return self.mesh.GetLog(clearAfterGet)
2236 ## Clear the log of nodes and elements added or removed since the previous
2237 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2238 # @ingroup l1_auxiliary
2240 self.mesh.ClearLog()
2242 ## Toggle auto color mode on the object.
2243 # @param theAutoColor the flag which toggles auto color mode.
2245 # If switched on, a default color of a new group in Create Group dialog is chosen randomly.
2246 # @ingroup l1_grouping
2247 def SetAutoColor(self, theAutoColor):
2248 self.mesh.SetAutoColor(theAutoColor)
2250 ## Get flag of object auto color mode.
2251 # @return True or False
2252 # @ingroup l1_grouping
2253 def GetAutoColor(self):
2254 return self.mesh.GetAutoColor()
2256 ## Get the internal ID
2257 # @return integer value, which is the internal Id of the mesh
2258 # @ingroup l1_auxiliary
2260 return self.mesh.GetId()
2263 # @return integer value, which is the study Id of the mesh
2264 # @ingroup l1_auxiliary
2265 def GetStudyId(self):
2266 return self.mesh.GetStudyId()
2268 ## Check the group names for duplications.
2269 # Consider the maximum group name length stored in MED file.
2270 # @return True or False
2271 # @ingroup l1_grouping
2272 def HasDuplicatedGroupNamesMED(self):
2273 return self.mesh.HasDuplicatedGroupNamesMED()
2275 ## Obtain the mesh editor tool
2276 # @return an instance of SMESH_MeshEditor
2277 # @ingroup l1_modifying
2278 def GetMeshEditor(self):
2281 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2282 # can be passed as argument to a method accepting mesh, group or sub-mesh
2283 # @param ids list of IDs
2284 # @param elemType type of elements; this parameter is used to distinguish
2285 # IDs of nodes from IDs of elements; by default ids are treated as
2286 # IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2287 # @return an instance of SMESH_IDSource
2288 # @warning call UnRegister() for the returned object as soon as it is no more useful:
2289 # idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2290 # mesh.DoSomething( idSrc )
2291 # idSrc.UnRegister()
2292 # @ingroup l1_auxiliary
2293 def GetIDSource(self, ids, elemType = SMESH.ALL):
2294 if isinstance( ids, int ):
2296 return self.editor.MakeIDSource(ids, elemType)
2299 # Get informations about mesh contents:
2300 # ------------------------------------
2302 ## Get the mesh stattistic
2303 # @return dictionary type element - count of elements
2304 # @ingroup l1_meshinfo
2305 def GetMeshInfo(self, obj = None):
2306 if not obj: obj = self.mesh
2307 return self.smeshpyD.GetMeshInfo(obj)
2309 ## Return the number of nodes in the mesh
2310 # @return an integer value
2311 # @ingroup l1_meshinfo
2313 return self.mesh.NbNodes()
2315 ## Return the number of elements in the mesh
2316 # @return an integer value
2317 # @ingroup l1_meshinfo
2318 def NbElements(self):
2319 return self.mesh.NbElements()
2321 ## Return the number of 0d elements in the mesh
2322 # @return an integer value
2323 # @ingroup l1_meshinfo
2324 def Nb0DElements(self):
2325 return self.mesh.Nb0DElements()
2327 ## Return the number of ball discrete elements in the mesh
2328 # @return an integer value
2329 # @ingroup l1_meshinfo
2331 return self.mesh.NbBalls()
2333 ## Return the number of edges in the mesh
2334 # @return an integer value
2335 # @ingroup l1_meshinfo
2337 return self.mesh.NbEdges()
2339 ## Return the number of edges with the given order in the mesh
2340 # @param elementOrder the order of elements:
2341 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2342 # @return an integer value
2343 # @ingroup l1_meshinfo
2344 def NbEdgesOfOrder(self, elementOrder):
2345 return self.mesh.NbEdgesOfOrder(elementOrder)
2347 ## Return the number of faces in the mesh
2348 # @return an integer value
2349 # @ingroup l1_meshinfo
2351 return self.mesh.NbFaces()
2353 ## Return the number of faces with the given order in the mesh
2354 # @param elementOrder the order of elements:
2355 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2356 # @return an integer value
2357 # @ingroup l1_meshinfo
2358 def NbFacesOfOrder(self, elementOrder):
2359 return self.mesh.NbFacesOfOrder(elementOrder)
2361 ## Return the number of triangles in the mesh
2362 # @return an integer value
2363 # @ingroup l1_meshinfo
2364 def NbTriangles(self):
2365 return self.mesh.NbTriangles()
2367 ## Return the number of triangles with the given order in the mesh
2368 # @param elementOrder is the order of elements:
2369 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2370 # @return an integer value
2371 # @ingroup l1_meshinfo
2372 def NbTrianglesOfOrder(self, elementOrder):
2373 return self.mesh.NbTrianglesOfOrder(elementOrder)
2375 ## Return the number of biquadratic triangles in the mesh
2376 # @return an integer value
2377 # @ingroup l1_meshinfo
2378 def NbBiQuadTriangles(self):
2379 return self.mesh.NbBiQuadTriangles()
2381 ## Return the number of quadrangles in the mesh
2382 # @return an integer value
2383 # @ingroup l1_meshinfo
2384 def NbQuadrangles(self):
2385 return self.mesh.NbQuadrangles()
2387 ## Return the number of quadrangles with the given order in the mesh
2388 # @param elementOrder the order of elements:
2389 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2390 # @return an integer value
2391 # @ingroup l1_meshinfo
2392 def NbQuadranglesOfOrder(self, elementOrder):
2393 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2395 ## Return the number of biquadratic quadrangles in the mesh
2396 # @return an integer value
2397 # @ingroup l1_meshinfo
2398 def NbBiQuadQuadrangles(self):
2399 return self.mesh.NbBiQuadQuadrangles()
2401 ## Return the number of polygons of given order in the mesh
2402 # @param elementOrder the order of elements:
2403 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2404 # @return an integer value
2405 # @ingroup l1_meshinfo
2406 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2407 return self.mesh.NbPolygonsOfOrder(elementOrder)
2409 ## Return the number of volumes in the mesh
2410 # @return an integer value
2411 # @ingroup l1_meshinfo
2412 def NbVolumes(self):
2413 return self.mesh.NbVolumes()
2415 ## Return the number of volumes with the given order in the mesh
2416 # @param elementOrder the order of elements:
2417 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2418 # @return an integer value
2419 # @ingroup l1_meshinfo
2420 def NbVolumesOfOrder(self, elementOrder):
2421 return self.mesh.NbVolumesOfOrder(elementOrder)
2423 ## Return the number of tetrahedrons in the mesh
2424 # @return an integer value
2425 # @ingroup l1_meshinfo
2427 return self.mesh.NbTetras()
2429 ## Return the number of tetrahedrons with the given order in the mesh
2430 # @param elementOrder the order of elements:
2431 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2432 # @return an integer value
2433 # @ingroup l1_meshinfo
2434 def NbTetrasOfOrder(self, elementOrder):
2435 return self.mesh.NbTetrasOfOrder(elementOrder)
2437 ## Return the number of hexahedrons in the mesh
2438 # @return an integer value
2439 # @ingroup l1_meshinfo
2441 return self.mesh.NbHexas()
2443 ## Return the number of hexahedrons with the given order in the mesh
2444 # @param elementOrder the order of elements:
2445 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2446 # @return an integer value
2447 # @ingroup l1_meshinfo
2448 def NbHexasOfOrder(self, elementOrder):
2449 return self.mesh.NbHexasOfOrder(elementOrder)
2451 ## Return the number of triquadratic hexahedrons in the mesh
2452 # @return an integer value
2453 # @ingroup l1_meshinfo
2454 def NbTriQuadraticHexas(self):
2455 return self.mesh.NbTriQuadraticHexas()
2457 ## Return the number of pyramids in the mesh
2458 # @return an integer value
2459 # @ingroup l1_meshinfo
2460 def NbPyramids(self):
2461 return self.mesh.NbPyramids()
2463 ## Return the number of pyramids with the given order in the mesh
2464 # @param elementOrder the order of elements:
2465 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2466 # @return an integer value
2467 # @ingroup l1_meshinfo
2468 def NbPyramidsOfOrder(self, elementOrder):
2469 return self.mesh.NbPyramidsOfOrder(elementOrder)
2471 ## Return the number of prisms in the mesh
2472 # @return an integer value
2473 # @ingroup l1_meshinfo
2475 return self.mesh.NbPrisms()
2477 ## Return the number of prisms with the given order in the mesh
2478 # @param elementOrder the order of elements:
2479 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2480 # @return an integer value
2481 # @ingroup l1_meshinfo
2482 def NbPrismsOfOrder(self, elementOrder):
2483 return self.mesh.NbPrismsOfOrder(elementOrder)
2485 ## Return the number of hexagonal prisms in the mesh
2486 # @return an integer value
2487 # @ingroup l1_meshinfo
2488 def NbHexagonalPrisms(self):
2489 return self.mesh.NbHexagonalPrisms()
2491 ## Return the number of polyhedrons in the mesh
2492 # @return an integer value
2493 # @ingroup l1_meshinfo
2494 def NbPolyhedrons(self):
2495 return self.mesh.NbPolyhedrons()
2497 ## Return the number of submeshes in the mesh
2498 # @return an integer value
2499 # @ingroup l1_meshinfo
2500 def NbSubMesh(self):
2501 return self.mesh.NbSubMesh()
2503 ## Return the list of mesh elements IDs
2504 # @return the list of integer values
2505 # @ingroup l1_meshinfo
2506 def GetElementsId(self):
2507 return self.mesh.GetElementsId()
2509 ## Return the list of IDs of mesh elements with the given type
2510 # @param elementType the required type of elements, either of
2511 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2512 # @return list of integer values
2513 # @ingroup l1_meshinfo
2514 def GetElementsByType(self, elementType):
2515 return self.mesh.GetElementsByType(elementType)
2517 ## Return the list of mesh nodes IDs
2518 # @return the list of integer values
2519 # @ingroup l1_meshinfo
2520 def GetNodesId(self):
2521 return self.mesh.GetNodesId()
2523 # Get the information about mesh elements:
2524 # ------------------------------------
2526 ## Return the type of mesh element
2527 # @return the value from SMESH::ElementType enumeration
2528 # Type SMESH.ElementType._items in the Python Console to see all possible values.
2529 # @ingroup l1_meshinfo
2530 def GetElementType(self, id, iselem=True):
2531 return self.mesh.GetElementType(id, iselem)
2533 ## Return the geometric type of mesh element
2534 # @return the value from SMESH::EntityType enumeration
2535 # Type SMESH.EntityType._items in the Python Console to see all possible values.
2536 # @ingroup l1_meshinfo
2537 def GetElementGeomType(self, id):
2538 return self.mesh.GetElementGeomType(id)
2540 ## Return the shape type of mesh element
2541 # @return the value from SMESH::GeometryType enumeration.
2542 # Type SMESH.GeometryType._items in the Python Console to see all possible values.
2543 # @ingroup l1_meshinfo
2544 def GetElementShape(self, id):
2545 return self.mesh.GetElementShape(id)
2547 ## Return the list of submesh elements IDs
2548 # @param Shape a geom object(sub-shape)
2549 # Shape must be the sub-shape of a ShapeToMesh()
2550 # @return the list of integer values
2551 # @ingroup l1_meshinfo
2552 def GetSubMeshElementsId(self, Shape):
2553 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2554 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2557 return self.mesh.GetSubMeshElementsId(ShapeID)
2559 ## Return the list of submesh nodes IDs
2560 # @param Shape a geom object(sub-shape)
2561 # Shape must be the sub-shape of a ShapeToMesh()
2562 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2563 # @return the list of integer values
2564 # @ingroup l1_meshinfo
2565 def GetSubMeshNodesId(self, Shape, all):
2566 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2567 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2570 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2572 ## Return type of elements on given shape
2573 # @param Shape a geom object(sub-shape)
2574 # Shape must be a sub-shape of a ShapeToMesh()
2575 # @return element type
2576 # @ingroup l1_meshinfo
2577 def GetSubMeshElementType(self, Shape):
2578 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2579 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2582 return self.mesh.GetSubMeshElementType(ShapeID)
2584 ## Get the mesh description
2585 # @return string value
2586 # @ingroup l1_meshinfo
2588 return self.mesh.Dump()
2591 # Get the information about nodes and elements of a mesh by its IDs:
2592 # -----------------------------------------------------------
2594 ## Get XYZ coordinates of a node
2595 # \n If there is no nodes for the given ID - return an empty list
2596 # @return a list of double precision values
2597 # @ingroup l1_meshinfo
2598 def GetNodeXYZ(self, id):
2599 return self.mesh.GetNodeXYZ(id)
2601 ## Return list of IDs of inverse elements for the given node
2602 # \n If there is no node for the given ID - return an empty list
2603 # @return a list of integer values
2604 # @ingroup l1_meshinfo
2605 def GetNodeInverseElements(self, id):
2606 return self.mesh.GetNodeInverseElements(id)
2608 ## Return the position of a node on the shape
2609 # @return SMESH::NodePosition
2610 # @ingroup l1_meshinfo
2611 def GetNodePosition(self,NodeID):
2612 return self.mesh.GetNodePosition(NodeID)
2614 ## Return the position of an element on the shape
2615 # @return SMESH::ElementPosition
2616 # @ingroup l1_meshinfo
2617 def GetElementPosition(self,ElemID):
2618 return self.mesh.GetElementPosition(ElemID)
2620 ## Return the ID of the shape, on which the given node was generated.
2621 # @return an integer value > 0 or -1 if there is no node for the given
2622 # ID or the node is not assigned to any geometry
2623 # @ingroup l1_meshinfo
2624 def GetShapeID(self, id):
2625 return self.mesh.GetShapeID(id)
2627 ## Return the ID of the shape, on which the given element was generated.
2628 # @return an integer value > 0 or -1 if there is no element for the given
2629 # ID or the element is not assigned to any geometry
2630 # @ingroup l1_meshinfo
2631 def GetShapeIDForElem(self,id):
2632 return self.mesh.GetShapeIDForElem(id)
2634 ## Return the number of nodes of the given element
2635 # @return an integer value > 0 or -1 if there is no element for the given ID
2636 # @ingroup l1_meshinfo
2637 def GetElemNbNodes(self, id):
2638 return self.mesh.GetElemNbNodes(id)
2640 ## Return the node ID the given (zero based) index for the given element
2641 # \n If there is no element for the given ID - return -1
2642 # \n If there is no node for the given index - return -2
2643 # @return an integer value
2644 # @ingroup l1_meshinfo
2645 def GetElemNode(self, id, index):
2646 return self.mesh.GetElemNode(id, index)
2648 ## Return the IDs of nodes of the given element
2649 # @return a list of integer values
2650 # @ingroup l1_meshinfo
2651 def GetElemNodes(self, id):
2652 return self.mesh.GetElemNodes(id)
2654 ## Return true if the given node is the medium node in the given quadratic element
2655 # @ingroup l1_meshinfo
2656 def IsMediumNode(self, elementID, nodeID):
2657 return self.mesh.IsMediumNode(elementID, nodeID)
2659 ## Return true if the given node is the medium node in one of quadratic elements
2660 # @param nodeID ID of the node
2661 # @param elementType the type of elements to check a state of the node, either of
2662 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2663 # @ingroup l1_meshinfo
2664 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2665 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2667 ## Return the number of edges for the given element
2668 # @ingroup l1_meshinfo
2669 def ElemNbEdges(self, id):
2670 return self.mesh.ElemNbEdges(id)
2672 ## Return the number of faces for the given element
2673 # @ingroup l1_meshinfo
2674 def ElemNbFaces(self, id):
2675 return self.mesh.ElemNbFaces(id)
2677 ## Return nodes of given face (counted from zero) for given volumic element.
2678 # @ingroup l1_meshinfo
2679 def GetElemFaceNodes(self,elemId, faceIndex):
2680 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2682 ## Return three components of normal of given mesh face
2683 # (or an empty array in KO case)
2684 # @ingroup l1_meshinfo
2685 def GetFaceNormal(self, faceId, normalized=False):
2686 return self.mesh.GetFaceNormal(faceId,normalized)
2688 ## Return an element based on all given nodes.
2689 # @ingroup l1_meshinfo
2690 def FindElementByNodes(self,nodes):
2691 return self.mesh.FindElementByNodes(nodes)
2693 ## Return true if the given element is a polygon
2694 # @ingroup l1_meshinfo
2695 def IsPoly(self, id):
2696 return self.mesh.IsPoly(id)
2698 ## Return true if the given element is quadratic
2699 # @ingroup l1_meshinfo
2700 def IsQuadratic(self, id):
2701 return self.mesh.IsQuadratic(id)
2703 ## Return diameter of a ball discrete element or zero in case of an invalid \a id
2704 # @ingroup l1_meshinfo
2705 def GetBallDiameter(self, id):
2706 return self.mesh.GetBallDiameter(id)
2708 ## Return XYZ coordinates of the barycenter of the given element
2709 # \n If there is no element for the given ID - return an empty list
2710 # @return a list of three double values
2711 # @ingroup l1_meshinfo
2712 def BaryCenter(self, id):
2713 return self.mesh.BaryCenter(id)
2715 ## Pass mesh elements through the given filter and return IDs of fitting elements
2716 # @param theFilter SMESH_Filter
2717 # @return a list of ids
2718 # @ingroup l1_controls
2719 def GetIdsFromFilter(self, theFilter):
2720 theFilter.SetMesh( self.mesh )
2721 return theFilter.GetIDs()
2723 # Get mesh measurements information:
2724 # ------------------------------------
2726 ## Verify whether a 2D mesh element has free edges (edges connected to one face only)\n
2727 # Return a list of special structures (borders).
2728 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2729 # @ingroup l1_measurements
2730 def GetFreeBorders(self):
2731 aFilterMgr = self.smeshpyD.CreateFilterManager()
2732 aPredicate = aFilterMgr.CreateFreeEdges()
2733 aPredicate.SetMesh(self.mesh)
2734 aBorders = aPredicate.GetBorders()
2735 aFilterMgr.UnRegister()
2738 ## Get minimum distance between two nodes, elements or distance to the origin
2739 # @param id1 first node/element id
2740 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2741 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2742 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2743 # @return minimum distance value
2744 # @sa GetMinDistance()
2745 # @ingroup l1_measurements
2746 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2747 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2748 return aMeasure.value
2750 ## Get measure structure specifying minimum distance data between two objects
2751 # @param id1 first node/element id
2752 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2753 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2754 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2755 # @return Measure structure
2757 # @ingroup l1_measurements
2758 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2760 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2762 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2765 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2767 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2772 aMeasurements = self.smeshpyD.CreateMeasurements()
2773 aMeasure = aMeasurements.MinDistance(id1, id2)
2774 genObjUnRegister([aMeasurements,id1, id2])
2777 ## Get bounding box of the specified object(s)
2778 # @param objects single source object or list of source objects or list of nodes/elements IDs
2779 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2780 # @c False specifies that @a objects are nodes
2781 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2782 # @sa GetBoundingBox()
2783 # @ingroup l1_measurements
2784 def BoundingBox(self, objects=None, isElem=False):
2785 result = self.GetBoundingBox(objects, isElem)
2789 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2792 ## Get measure structure specifying bounding box data of the specified object(s)
2793 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2794 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2795 # @c False specifies that @a objects are nodes
2796 # @return Measure structure
2798 # @ingroup l1_measurements
2799 def GetBoundingBox(self, IDs=None, isElem=False):
2802 elif isinstance(IDs, tuple):
2804 if not isinstance(IDs, list):
2806 if len(IDs) > 0 and isinstance(IDs[0], int):
2809 unRegister = genObjUnRegister()
2811 if isinstance(o, Mesh):
2812 srclist.append(o.mesh)
2813 elif hasattr(o, "_narrow"):
2814 src = o._narrow(SMESH.SMESH_IDSource)
2815 if src: srclist.append(src)
2817 elif isinstance(o, list):
2819 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2821 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2822 unRegister.set( srclist[-1] )
2825 aMeasurements = self.smeshpyD.CreateMeasurements()
2826 unRegister.set( aMeasurements )
2827 aMeasure = aMeasurements.BoundingBox(srclist)
2830 # Mesh edition (SMESH_MeshEditor functionality):
2831 # ---------------------------------------------
2833 ## Remove the elements from the mesh by ids
2834 # @param IDsOfElements is a list of ids of elements to remove
2835 # @return True or False
2836 # @ingroup l2_modif_del
2837 def RemoveElements(self, IDsOfElements):
2838 return self.editor.RemoveElements(IDsOfElements)
2840 ## Remove nodes from mesh by ids
2841 # @param IDsOfNodes is a list of ids of nodes to remove
2842 # @return True or False
2843 # @ingroup l2_modif_del
2844 def RemoveNodes(self, IDsOfNodes):
2845 return self.editor.RemoveNodes(IDsOfNodes)
2847 ## Remove all orphan (free) nodes from mesh
2848 # @return number of the removed nodes
2849 # @ingroup l2_modif_del
2850 def RemoveOrphanNodes(self):
2851 return self.editor.RemoveOrphanNodes()
2853 ## Add a node to the mesh by coordinates
2854 # @return Id of the new node
2855 # @ingroup l2_modif_add
2856 def AddNode(self, x, y, z):
2857 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2858 if hasVars: self.mesh.SetParameters(Parameters)
2859 return self.editor.AddNode( x, y, z)
2861 ## Create a 0D element on a node with given number.
2862 # @param IDOfNode the ID of node for creation of the element.
2863 # @param DuplicateElements to add one more 0D element to a node or not
2864 # @return the Id of the new 0D element
2865 # @ingroup l2_modif_add
2866 def Add0DElement( self, IDOfNode, DuplicateElements=True ):
2867 return self.editor.Add0DElement( IDOfNode, DuplicateElements )
2869 ## Create 0D elements on all nodes of the given elements except those
2870 # nodes on which a 0D element already exists.
2871 # @param theObject an object on whose nodes 0D elements will be created.
2872 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2873 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2874 # @param theGroupName optional name of a group to add 0D elements created
2875 # and/or found on nodes of \a theObject.
2876 # @param DuplicateElements to add one more 0D element to a node or not
2877 # @return an object (a new group or a temporary SMESH_IDSource) holding
2878 # IDs of new and/or found 0D elements. IDs of 0D elements
2879 # can be retrieved from the returned object by calling GetIDs()
2880 # @ingroup l2_modif_add
2881 def Add0DElementsToAllNodes(self, theObject, theGroupName="", DuplicateElements=False):
2882 unRegister = genObjUnRegister()
2883 if isinstance( theObject, Mesh ):
2884 theObject = theObject.GetMesh()
2885 elif isinstance( theObject, list ):
2886 theObject = self.GetIDSource( theObject, SMESH.ALL )
2887 unRegister.set( theObject )
2888 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName, DuplicateElements )
2890 ## Create a ball element on a node with given ID.
2891 # @param IDOfNode the ID of node for creation of the element.
2892 # @param diameter the bal diameter.
2893 # @return the Id of the new ball element
2894 # @ingroup l2_modif_add
2895 def AddBall(self, IDOfNode, diameter):
2896 return self.editor.AddBall( IDOfNode, diameter )
2898 ## Create a linear or quadratic edge (this is determined
2899 # by the number of given nodes).
2900 # @param IDsOfNodes the list of node IDs for creation of the element.
2901 # The order of nodes in this list should correspond to the description
2902 # of MED. \n This description is located by the following link:
2903 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2904 # @return the Id of the new edge
2905 # @ingroup l2_modif_add
2906 def AddEdge(self, IDsOfNodes):
2907 return self.editor.AddEdge(IDsOfNodes)
2909 ## Create a linear or quadratic face (this is determined
2910 # by the number of given nodes).
2911 # @param IDsOfNodes the list of node IDs for creation of the element.
2912 # The order of nodes in this list should correspond to the description
2913 # of MED. \n This description is located by the following link:
2914 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2915 # @return the Id of the new face
2916 # @ingroup l2_modif_add
2917 def AddFace(self, IDsOfNodes):
2918 return self.editor.AddFace(IDsOfNodes)
2920 ## Add a polygonal face to the mesh by the list of node IDs
2921 # @param IdsOfNodes the list of node IDs for creation of the element.
2922 # @return the Id of the new face
2923 # @ingroup l2_modif_add
2924 def AddPolygonalFace(self, IdsOfNodes):
2925 return self.editor.AddPolygonalFace(IdsOfNodes)
2927 ## Add a quadratic polygonal face to the mesh by the list of node IDs
2928 # @param IdsOfNodes the list of node IDs for creation of the element;
2929 # corner nodes follow first.
2930 # @return the Id of the new face
2931 # @ingroup l2_modif_add
2932 def AddQuadPolygonalFace(self, IdsOfNodes):
2933 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
2935 ## Create both simple and quadratic volume (this is determined
2936 # by the number of given nodes).
2937 # @param IDsOfNodes the list of node IDs for creation of the element.
2938 # The order of nodes in this list should correspond to the description
2939 # of MED. \n This description is located by the following link:
2940 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2941 # @return the Id of the new volumic element
2942 # @ingroup l2_modif_add
2943 def AddVolume(self, IDsOfNodes):
2944 return self.editor.AddVolume(IDsOfNodes)
2946 ## Create a volume of many faces, giving nodes for each face.
2947 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2948 # @param Quantities the list of integer values, Quantities[i]
2949 # gives the quantity of nodes in face number i.
2950 # @return the Id of the new volumic element
2951 # @ingroup l2_modif_add
2952 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2953 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2955 ## Create a volume of many faces, giving the IDs of the existing faces.
2956 # @param IdsOfFaces the list of face IDs for volume creation.
2958 # Note: The created volume will refer only to the nodes
2959 # of the given faces, not to the faces themselves.
2960 # @return the Id of the new volumic element
2961 # @ingroup l2_modif_add
2962 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2963 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2966 ## @brief Binds a node to a vertex
2967 # @param NodeID a node ID
2968 # @param Vertex a vertex or vertex ID
2969 # @return True if succeed else raises an exception
2970 # @ingroup l2_modif_add
2971 def SetNodeOnVertex(self, NodeID, Vertex):
2972 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2973 VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
2977 self.editor.SetNodeOnVertex(NodeID, VertexID)
2978 except SALOME.SALOME_Exception, inst:
2979 raise ValueError, inst.details.text
2983 ## @brief Stores the node position on an edge
2984 # @param NodeID a node ID
2985 # @param Edge an edge or edge ID
2986 # @param paramOnEdge a parameter on the edge where the node is located
2987 # @return True if succeed else raises an exception
2988 # @ingroup l2_modif_add
2989 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2990 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2991 EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
2995 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2996 except SALOME.SALOME_Exception, inst:
2997 raise ValueError, inst.details.text
3000 ## @brief Stores node position on a face
3001 # @param NodeID a node ID
3002 # @param Face a face or face ID
3003 # @param u U parameter on the face where the node is located
3004 # @param v V parameter on the face where the node is located
3005 # @return True if succeed else raises an exception
3006 # @ingroup l2_modif_add
3007 def SetNodeOnFace(self, NodeID, Face, u, v):
3008 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
3009 FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
3013 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
3014 except SALOME.SALOME_Exception, inst:
3015 raise ValueError, inst.details.text
3018 ## @brief Binds a node to a solid
3019 # @param NodeID a node ID
3020 # @param Solid a solid or solid ID
3021 # @return True if succeed else raises an exception
3022 # @ingroup l2_modif_add
3023 def SetNodeInVolume(self, NodeID, Solid):
3024 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
3025 SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
3029 self.editor.SetNodeInVolume(NodeID, SolidID)
3030 except SALOME.SALOME_Exception, inst:
3031 raise ValueError, inst.details.text
3034 ## @brief Bind an element to a shape
3035 # @param ElementID an element ID
3036 # @param Shape a shape or shape ID
3037 # @return True if succeed else raises an exception
3038 # @ingroup l2_modif_add
3039 def SetMeshElementOnShape(self, ElementID, Shape):
3040 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
3041 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3045 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
3046 except SALOME.SALOME_Exception, inst:
3047 raise ValueError, inst.details.text
3051 ## Move the node with the given id
3052 # @param NodeID the id of the node
3053 # @param x a new X coordinate
3054 # @param y a new Y coordinate
3055 # @param z a new Z coordinate
3056 # @return True if succeed else False
3057 # @ingroup l2_modif_edit
3058 def MoveNode(self, NodeID, x, y, z):
3059 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3060 if hasVars: self.mesh.SetParameters(Parameters)
3061 return self.editor.MoveNode(NodeID, x, y, z)
3063 ## Find the node closest to a point and moves it to a point location
3064 # @param x the X coordinate of a point
3065 # @param y the Y coordinate of a point
3066 # @param z the Z coordinate of a point
3067 # @param NodeID if specified (>0), the node with this ID is moved,
3068 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
3069 # @return the ID of a node
3070 # @ingroup l2_modif_edit
3071 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3072 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3073 if hasVars: self.mesh.SetParameters(Parameters)
3074 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3076 ## Find the node closest to a point
3077 # @param x the X coordinate of a point
3078 # @param y the Y coordinate of a point
3079 # @param z the Z coordinate of a point
3080 # @return the ID of a node
3081 # @ingroup l1_meshinfo
3082 def FindNodeClosestTo(self, x, y, z):
3083 #preview = self.mesh.GetMeshEditPreviewer()
3084 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3085 return self.editor.FindNodeClosestTo(x, y, z)
3087 ## Find the elements where a point lays IN or ON
3088 # @param x the X coordinate of a point
3089 # @param y the Y coordinate of a point
3090 # @param z the Z coordinate of a point
3091 # @param elementType type of elements to find; either of
3092 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3093 # means elements of any type excluding nodes, discrete and 0D elements.
3094 # @param meshPart a part of mesh (group, sub-mesh) to search within
3095 # @return list of IDs of found elements
3096 # @ingroup l1_meshinfo
3097 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3099 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
3101 return self.editor.FindElementsByPoint(x, y, z, elementType)
3103 ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
3104 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
3105 # UNKNOWN state means that either mesh is wrong or the analysis fails.
3106 # @ingroup l1_meshinfo
3107 def GetPointState(self, x, y, z):
3108 return self.editor.GetPointState(x, y, z)
3110 ## Find the node closest to a point and moves it to a point location
3111 # @param x the X coordinate of a point
3112 # @param y the Y coordinate of a point
3113 # @param z the Z coordinate of a point
3114 # @return the ID of a moved node
3115 # @ingroup l2_modif_edit
3116 def MeshToPassThroughAPoint(self, x, y, z):
3117 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3119 ## Replace two neighbour triangles sharing Node1-Node2 link
3120 # with the triangles built on the same 4 nodes but having other common link.
3121 # @param NodeID1 the ID of the first node
3122 # @param NodeID2 the ID of the second node
3123 # @return false if proper faces were not found
3124 # @ingroup l2_modif_cutquadr
3125 def InverseDiag(self, NodeID1, NodeID2):
3126 return self.editor.InverseDiag(NodeID1, NodeID2)
3128 ## Replace two neighbour triangles sharing Node1-Node2 link
3129 # with a quadrangle built on the same 4 nodes.
3130 # @param NodeID1 the ID of the first node
3131 # @param NodeID2 the ID of the second node
3132 # @return false if proper faces were not found
3133 # @ingroup l2_modif_unitetri
3134 def DeleteDiag(self, NodeID1, NodeID2):
3135 return self.editor.DeleteDiag(NodeID1, NodeID2)
3137 ## Reorient elements by ids
3138 # @param IDsOfElements if undefined reorients all mesh elements
3139 # @return True if succeed else False
3140 # @ingroup l2_modif_changori
3141 def Reorient(self, IDsOfElements=None):
3142 if IDsOfElements == None:
3143 IDsOfElements = self.GetElementsId()
3144 return self.editor.Reorient(IDsOfElements)
3146 ## Reorient all elements of the object
3147 # @param theObject mesh, submesh or group
3148 # @return True if succeed else False
3149 # @ingroup l2_modif_changori
3150 def ReorientObject(self, theObject):
3151 if ( isinstance( theObject, Mesh )):
3152 theObject = theObject.GetMesh()
3153 return self.editor.ReorientObject(theObject)
3155 ## Reorient faces contained in \a the2DObject.
3156 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3157 # @param theDirection is a desired direction of normal of \a theFace.
3158 # It can be either a GEOM vector or a list of coordinates [x,y,z].
3159 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3160 # compared with theDirection. It can be either ID of face or a point
3161 # by which the face will be found. The point can be given as either
3162 # a GEOM vertex or a list of point coordinates.
3163 # @return number of reoriented faces
3164 # @ingroup l2_modif_changori
3165 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3166 unRegister = genObjUnRegister()
3168 if isinstance( the2DObject, Mesh ):
3169 the2DObject = the2DObject.GetMesh()
3170 if isinstance( the2DObject, list ):
3171 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3172 unRegister.set( the2DObject )
3173 # check theDirection
3174 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3175 theDirection = self.smeshpyD.GetDirStruct( theDirection )
3176 if isinstance( theDirection, list ):
3177 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
3178 # prepare theFace and thePoint
3179 theFace = theFaceOrPoint
3180 thePoint = PointStruct(0,0,0)
3181 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3182 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3184 if isinstance( theFaceOrPoint, list ):
3185 thePoint = PointStruct( *theFaceOrPoint )
3187 if isinstance( theFaceOrPoint, PointStruct ):
3188 thePoint = theFaceOrPoint
3190 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3192 ## Reorient faces according to adjacent volumes.
3193 # @param the2DObject is a mesh, sub-mesh, group or list of
3194 # either IDs of faces or face groups.
3195 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3196 # @param theOutsideNormal to orient faces to have their normals
3197 # pointing either \a outside or \a inside the adjacent volumes.
3198 # @return number of reoriented faces.
3199 # @ingroup l2_modif_changori
3200 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3201 unRegister = genObjUnRegister()
3203 if not isinstance( the2DObject, list ):
3204 the2DObject = [ the2DObject ]
3205 elif the2DObject and isinstance( the2DObject[0], int ):
3206 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3207 unRegister.set( the2DObject )
3208 the2DObject = [ the2DObject ]
3209 for i,obj2D in enumerate( the2DObject ):
3210 if isinstance( obj2D, Mesh ):
3211 the2DObject[i] = obj2D.GetMesh()
3212 if isinstance( obj2D, list ):
3213 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3214 unRegister.set( the2DObject[i] )
3216 if isinstance( the3DObject, Mesh ):
3217 the3DObject = the3DObject.GetMesh()
3218 if isinstance( the3DObject, list ):
3219 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3220 unRegister.set( the3DObject )
3221 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3223 ## Fuse the neighbouring triangles into quadrangles.
3224 # @param IDsOfElements The triangles to be fused.
3225 # @param theCriterion a numerical functor, in terms of enum SMESH.FunctorType, used to
3226 # applied to possible quadrangles to choose a neighbour to fuse with.
3227 # Type SMESH.FunctorType._items in the Python Console to see all items.
3228 # Note that not all items correspond to numerical functors.
3229 # @param MaxAngle is the maximum angle between element normals at which the fusion
3230 # is still performed; theMaxAngle is mesured in radians.
3231 # Also it could be a name of variable which defines angle in degrees.
3232 # @return TRUE in case of success, FALSE otherwise.
3233 # @ingroup l2_modif_unitetri
3234 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3235 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3236 self.mesh.SetParameters(Parameters)
3237 if not IDsOfElements:
3238 IDsOfElements = self.GetElementsId()
3239 Functor = self.smeshpyD.GetFunctor(theCriterion)
3240 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3242 ## Fuse the neighbouring triangles of the object into quadrangles
3243 # @param theObject is mesh, submesh or group
3244 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType,
3245 # applied to possible quadrangles to choose a neighbour to fuse with.
3246 # Type SMESH.FunctorType._items in the Python Console to see all items.
3247 # Note that not all items correspond to numerical functors.
3248 # @param MaxAngle a max angle between element normals at which the fusion
3249 # is still performed; theMaxAngle is mesured in radians.
3250 # @return TRUE in case of success, FALSE otherwise.
3251 # @ingroup l2_modif_unitetri
3252 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3253 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3254 self.mesh.SetParameters(Parameters)
3255 if isinstance( theObject, Mesh ):
3256 theObject = theObject.GetMesh()
3257 Functor = self.smeshpyD.GetFunctor(theCriterion)
3258 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3260 ## Split quadrangles into triangles.
3261 # @param IDsOfElements the faces to be splitted.
3262 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3263 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3264 # value, then quadrangles will be split by the smallest diagonal.
3265 # Type SMESH.FunctorType._items in the Python Console to see all items.
3266 # Note that not all items correspond to numerical functors.
3267 # @return TRUE in case of success, FALSE otherwise.
3268 # @ingroup l2_modif_cutquadr
3269 def QuadToTri (self, IDsOfElements, theCriterion = None):
3270 if IDsOfElements == []:
3271 IDsOfElements = self.GetElementsId()
3272 if theCriterion is None:
3273 theCriterion = FT_MaxElementLength2D
3274 Functor = self.smeshpyD.GetFunctor(theCriterion)
3275 return self.editor.QuadToTri(IDsOfElements, Functor)
3277 ## Split quadrangles into triangles.
3278 # @param theObject the object from which the list of elements is taken,
3279 # this is mesh, submesh or group
3280 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3281 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3282 # value, then quadrangles will be split by the smallest diagonal.
3283 # Type SMESH.FunctorType._items in the Python Console to see all items.
3284 # Note that not all items correspond to numerical functors.
3285 # @return TRUE in case of success, FALSE otherwise.
3286 # @ingroup l2_modif_cutquadr
3287 def QuadToTriObject (self, theObject, theCriterion = None):
3288 if ( isinstance( theObject, Mesh )):
3289 theObject = theObject.GetMesh()
3290 if theCriterion is None:
3291 theCriterion = FT_MaxElementLength2D
3292 Functor = self.smeshpyD.GetFunctor(theCriterion)
3293 return self.editor.QuadToTriObject(theObject, Functor)
3295 ## Split each of given quadrangles into 4 triangles. A node is added at the center of
3297 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3298 # group or a list of face IDs. By default all quadrangles are split
3299 # @ingroup l2_modif_cutquadr
3300 def QuadTo4Tri (self, theElements=[]):
3301 unRegister = genObjUnRegister()
3302 if isinstance( theElements, Mesh ):
3303 theElements = theElements.mesh
3304 elif not theElements:
3305 theElements = self.mesh
3306 elif isinstance( theElements, list ):
3307 theElements = self.GetIDSource( theElements, SMESH.FACE )
3308 unRegister.set( theElements )
3309 return self.editor.QuadTo4Tri( theElements )
3311 ## Split quadrangles into triangles.
3312 # @param IDsOfElements the faces to be splitted
3313 # @param Diag13 is used to choose a diagonal for splitting.
3314 # @return TRUE in case of success, FALSE otherwise.
3315 # @ingroup l2_modif_cutquadr
3316 def SplitQuad (self, IDsOfElements, Diag13):
3317 if IDsOfElements == []:
3318 IDsOfElements = self.GetElementsId()
3319 return self.editor.SplitQuad(IDsOfElements, Diag13)
3321 ## Split quadrangles into triangles.
3322 # @param theObject the object from which the list of elements is taken,
3323 # this is mesh, submesh or group
3324 # @param Diag13 is used to choose a diagonal for splitting.
3325 # @return TRUE in case of success, FALSE otherwise.
3326 # @ingroup l2_modif_cutquadr
3327 def SplitQuadObject (self, theObject, Diag13):
3328 if ( isinstance( theObject, Mesh )):
3329 theObject = theObject.GetMesh()
3330 return self.editor.SplitQuadObject(theObject, Diag13)
3332 ## Find a better splitting of the given quadrangle.
3333 # @param IDOfQuad the ID of the quadrangle to be splitted.
3334 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3335 # choose a diagonal for splitting.
3336 # Type SMESH.FunctorType._items in the Python Console to see all items.
3337 # Note that not all items correspond to numerical functors.
3338 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3339 # diagonal is better, 0 if error occurs.
3340 # @ingroup l2_modif_cutquadr
3341 def BestSplit (self, IDOfQuad, theCriterion):
3342 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3344 ## Split volumic elements into tetrahedrons
3345 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3346 # @param method flags passing splitting method:
3347 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3348 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3349 # @ingroup l2_modif_cutquadr
3350 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3351 unRegister = genObjUnRegister()
3352 if isinstance( elems, Mesh ):
3353 elems = elems.GetMesh()
3354 if ( isinstance( elems, list )):
3355 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3356 unRegister.set( elems )
3357 self.editor.SplitVolumesIntoTetra(elems, method)
3360 ## Split bi-quadratic elements into linear ones without creation of additional nodes:
3361 # - bi-quadratic triangle will be split into 3 linear quadrangles;
3362 # - bi-quadratic quadrangle will be split into 4 linear quadrangles;
3363 # - tri-quadratic hexahedron will be split into 8 linear hexahedra.
3364 # Quadratic elements of lower dimension adjacent to the split bi-quadratic element
3365 # will be split in order to keep the mesh conformal.
3366 # @param elems - elements to split: sub-meshes, groups, filters or element IDs;
3367 # if None (default), all bi-quadratic elements will be split
3368 # @ingroup l2_modif_cutquadr
3369 def SplitBiQuadraticIntoLinear(self, elems=None):
3370 unRegister = genObjUnRegister()
3371 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
3372 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
3373 unRegister.set( elems )
3375 elems = [ self.GetMesh() ]
3376 if isinstance( elems, Mesh ):
3377 elems = [ elems.GetMesh() ]
3378 if not isinstance( elems, list ):
3380 self.editor.SplitBiQuadraticIntoLinear( elems )
3382 ## Split hexahedra into prisms
3383 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3384 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3385 # gives a normal vector defining facets to split into triangles.
3386 # @a startHexPoint can be either a triple of coordinates or a vertex.
3387 # @param facetNormal a normal to a facet to split into triangles of a
3388 # hexahedron found by @a startHexPoint.
3389 # @a facetNormal can be either a triple of coordinates or an edge.
3390 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3391 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3392 # @param allDomains if @c False, only hexahedra adjacent to one closest
3393 # to @a startHexPoint are split, else @a startHexPoint
3394 # is used to find the facet to split in all domains present in @a elems.
3395 # @ingroup l2_modif_cutquadr
3396 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3397 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3399 unRegister = genObjUnRegister()
3400 if isinstance( elems, Mesh ):
3401 elems = elems.GetMesh()
3402 if ( isinstance( elems, list )):
3403 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3404 unRegister.set( elems )
3407 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3408 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3409 elif isinstance( startHexPoint, list ):
3410 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3413 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3414 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3415 elif isinstance( facetNormal, list ):
3416 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3419 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3421 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3423 ## Split quadrangle faces near triangular facets of volumes
3425 # @ingroup l2_modif_cutquadr
3426 def SplitQuadsNearTriangularFacets(self):
3427 faces_array = self.GetElementsByType(SMESH.FACE)
3428 for face_id in faces_array:
3429 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3430 quad_nodes = self.mesh.GetElemNodes(face_id)
3431 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3432 isVolumeFound = False
3433 for node1_elem in node1_elems:
3434 if not isVolumeFound:
3435 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3436 nb_nodes = self.GetElemNbNodes(node1_elem)
3437 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3438 volume_elem = node1_elem
3439 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3440 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3441 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3442 isVolumeFound = True
3443 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3444 self.SplitQuad([face_id], False) # diagonal 2-4
3445 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3446 isVolumeFound = True
3447 self.SplitQuad([face_id], True) # diagonal 1-3
3448 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3449 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3450 isVolumeFound = True
3451 self.SplitQuad([face_id], True) # diagonal 1-3
3453 ## @brief Splits hexahedrons into tetrahedrons.
3455 # This operation uses pattern mapping functionality for splitting.
3456 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3457 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3458 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3459 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3460 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3461 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3462 # @return TRUE in case of success, FALSE otherwise.
3463 # @ingroup l2_modif_cutquadr
3464 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3465 # Pattern: 5.---------.6
3470 # (0,0,1) 4.---------.7 * |
3477 # (0,0,0) 0.---------.3
3478 pattern_tetra = "!!! Nb of points: \n 8 \n\
3488 !!! Indices of points of 6 tetras: \n\
3496 pattern = self.smeshpyD.GetPattern()
3497 isDone = pattern.LoadFromFile(pattern_tetra)
3499 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3502 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3503 isDone = pattern.MakeMesh(self.mesh, False, False)
3504 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3506 # split quafrangle faces near triangular facets of volumes
3507 self.SplitQuadsNearTriangularFacets()
3511 ## @brief Split hexahedrons into prisms.
3513 # Uses the pattern mapping functionality for splitting.
3514 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3515 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3516 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3517 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3518 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3519 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3520 # @return TRUE in case of success, FALSE otherwise.
3521 # @ingroup l2_modif_cutquadr
3522 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3523 # Pattern: 5.---------.6
3528 # (0,0,1) 4.---------.7 |
3535 # (0,0,0) 0.---------.3
3536 pattern_prism = "!!! Nb of points: \n 8 \n\
3546 !!! Indices of points of 2 prisms: \n\
3550 pattern = self.smeshpyD.GetPattern()
3551 isDone = pattern.LoadFromFile(pattern_prism)
3553 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3556 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3557 isDone = pattern.MakeMesh(self.mesh, False, False)
3558 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3560 # Split quafrangle faces near triangular facets of volumes
3561 self.SplitQuadsNearTriangularFacets()
3566 # @param IDsOfElements the list if ids of elements to smooth
3567 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3568 # Note that nodes built on edges and boundary nodes are always fixed.
3569 # @param MaxNbOfIterations the maximum number of iterations
3570 # @param MaxAspectRatio varies in range [1.0, inf]
3571 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3572 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3573 # @return TRUE in case of success, FALSE otherwise.
3574 # @ingroup l2_modif_smooth
3575 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3576 MaxNbOfIterations, MaxAspectRatio, Method):
3577 if IDsOfElements == []:
3578 IDsOfElements = self.GetElementsId()
3579 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3580 self.mesh.SetParameters(Parameters)
3581 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3582 MaxNbOfIterations, MaxAspectRatio, Method)
3584 ## Smooth elements which belong to the given object
3585 # @param theObject the object to smooth
3586 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3587 # Note that nodes built on edges and boundary nodes are always fixed.
3588 # @param MaxNbOfIterations the maximum number of iterations
3589 # @param MaxAspectRatio varies in range [1.0, inf]
3590 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3591 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3592 # @return TRUE in case of success, FALSE otherwise.
3593 # @ingroup l2_modif_smooth
3594 def SmoothObject(self, theObject, IDsOfFixedNodes,
3595 MaxNbOfIterations, MaxAspectRatio, Method):
3596 if ( isinstance( theObject, Mesh )):
3597 theObject = theObject.GetMesh()
3598 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3599 MaxNbOfIterations, MaxAspectRatio, Method)
3601 ## Parametrically smooth the given elements
3602 # @param IDsOfElements the list if ids of elements to smooth
3603 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3604 # Note that nodes built on edges and boundary nodes are always fixed.
3605 # @param MaxNbOfIterations the maximum number of iterations
3606 # @param MaxAspectRatio varies in range [1.0, inf]
3607 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3608 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3609 # @return TRUE in case of success, FALSE otherwise.
3610 # @ingroup l2_modif_smooth
3611 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3612 MaxNbOfIterations, MaxAspectRatio, Method):
3613 if IDsOfElements == []:
3614 IDsOfElements = self.GetElementsId()
3615 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3616 self.mesh.SetParameters(Parameters)
3617 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3618 MaxNbOfIterations, MaxAspectRatio, Method)
3620 ## Parametrically smooth the elements which belong to the given object
3621 # @param theObject the object to smooth
3622 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3623 # Note that nodes built on edges and boundary nodes are always fixed.
3624 # @param MaxNbOfIterations the maximum number of iterations
3625 # @param MaxAspectRatio varies in range [1.0, inf]
3626 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3627 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3628 # @return TRUE in case of success, FALSE otherwise.
3629 # @ingroup l2_modif_smooth
3630 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3631 MaxNbOfIterations, MaxAspectRatio, Method):
3632 if ( isinstance( theObject, Mesh )):
3633 theObject = theObject.GetMesh()
3634 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3635 MaxNbOfIterations, MaxAspectRatio, Method)
3637 ## Convert the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3638 # them with quadratic with the same id.
3639 # @param theForce3d new node creation method:
3640 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3641 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3642 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3643 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3644 # @return SMESH.ComputeError which can hold a warning
3645 # @ingroup l2_modif_tofromqu
3646 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3647 if isinstance( theSubMesh, Mesh ):
3648 theSubMesh = theSubMesh.mesh
3650 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3653 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3655 self.editor.ConvertToQuadratic(theForce3d)
3656 error = self.editor.GetLastError()
3657 if error and error.comment:
3661 ## Convert the mesh from quadratic to ordinary,
3662 # deletes old quadratic elements, \n replacing
3663 # them with ordinary mesh elements with the same id.
3664 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3665 # @ingroup l2_modif_tofromqu
3666 def ConvertFromQuadratic(self, theSubMesh=None):
3668 self.editor.ConvertFromQuadraticObject(theSubMesh)
3670 return self.editor.ConvertFromQuadratic()
3672 ## Create 2D mesh as skin on boundary faces of a 3D mesh
3673 # @return TRUE if operation has been completed successfully, FALSE otherwise
3674 # @ingroup l2_modif_add
3675 def Make2DMeshFrom3D(self):
3676 return self.editor.Make2DMeshFrom3D()
3678 ## Create missing boundary elements
3679 # @param elements - elements whose boundary is to be checked:
3680 # mesh, group, sub-mesh or list of elements
3681 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3682 # @param dimension - defines type of boundary elements to create, either of
3683 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3684 # SMESH.BND_1DFROM3D create mesh edges on all borders of free facets of 3D cells
3685 # @param groupName - a name of group to store created boundary elements in,
3686 # "" means not to create the group
3687 # @param meshName - a name of new mesh to store created boundary elements in,
3688 # "" means not to create the new mesh
3689 # @param toCopyElements - if true, the checked elements will be copied into
3690 # the new mesh else only boundary elements will be copied into the new mesh
3691 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3692 # boundary elements will be copied into the new mesh
3693 # @return tuple (mesh, group) where boundary elements were added to
3694 # @ingroup l2_modif_add
3695 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3696 toCopyElements=False, toCopyExistingBondary=False):
3697 unRegister = genObjUnRegister()
3698 if isinstance( elements, Mesh ):
3699 elements = elements.GetMesh()
3700 if ( isinstance( elements, list )):
3701 elemType = SMESH.ALL
3702 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3703 elements = self.editor.MakeIDSource(elements, elemType)
3704 unRegister.set( elements )
3705 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3706 toCopyElements,toCopyExistingBondary)
3707 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3711 # @brief Create missing boundary elements around either the whole mesh or
3712 # groups of elements
3713 # @param dimension - defines type of boundary elements to create, either of
3714 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3715 # @param groupName - a name of group to store all boundary elements in,
3716 # "" means not to create the group
3717 # @param meshName - a name of a new mesh, which is a copy of the initial
3718 # mesh + created boundary elements; "" means not to create the new mesh
3719 # @param toCopyAll - if true, the whole initial mesh will be copied into
3720 # the new mesh else only boundary elements will be copied into the new mesh
3721 # @param groups - groups of elements to make boundary around
3722 # @retval tuple( long, mesh, groups )
3723 # long - number of added boundary elements
3724 # mesh - the mesh where elements were added to
3725 # group - the group of boundary elements or None
3727 # @ingroup l2_modif_add
3728 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3729 toCopyAll=False, groups=[]):
3730 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3732 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3733 return nb, mesh, group
3735 ## Renumber mesh nodes (Obsolete, does nothing)
3736 # @ingroup l2_modif_renumber
3737 def RenumberNodes(self):
3738 self.editor.RenumberNodes()
3740 ## Renumber mesh elements (Obsole, does nothing)
3741 # @ingroup l2_modif_renumber
3742 def RenumberElements(self):
3743 self.editor.RenumberElements()
3745 ## Private method converting \a arg into a list of SMESH_IdSource's
3746 def _getIdSourceList(self, arg, idType, unRegister):
3747 if arg and isinstance( arg, list ):
3748 if isinstance( arg[0], int ):
3749 arg = self.GetIDSource( arg, idType )
3750 unRegister.set( arg )
3751 elif isinstance( arg[0], Mesh ):
3752 arg[0] = arg[0].GetMesh()
3753 elif isinstance( arg, Mesh ):
3755 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3759 ## Generate new elements by rotation of the given elements and nodes around the axis
3760 # @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3761 # @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3762 # @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3763 # @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3764 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3765 # which defines angle in degrees
3766 # @param NbOfSteps the number of steps
3767 # @param Tolerance tolerance
3768 # @param MakeGroups forces the generation of new groups from existing ones
3769 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3770 # of all steps, else - size of each step
3771 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3772 # @ingroup l2_modif_extrurev
3773 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3774 MakeGroups=False, TotalAngle=False):
3775 unRegister = genObjUnRegister()
3776 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3777 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3778 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3780 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3781 Axis = self.smeshpyD.GetAxisStruct( Axis )
3782 if isinstance( Axis, list ):
3783 Axis = SMESH.AxisStruct( *Axis )
3785 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3786 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3787 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3788 self.mesh.SetParameters(Parameters)
3789 if TotalAngle and NbOfSteps:
3790 AngleInRadians /= NbOfSteps
3791 return self.editor.RotationSweepObjects( nodes, edges, faces,
3792 Axis, AngleInRadians,
3793 NbOfSteps, Tolerance, MakeGroups)
3795 ## Generate new elements by rotation of the elements around the axis
3796 # @param IDsOfElements the list of ids of elements to sweep
3797 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3798 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3799 # @param NbOfSteps the number of steps
3800 # @param Tolerance tolerance
3801 # @param MakeGroups forces the generation of new groups from existing ones
3802 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3803 # of all steps, else - size of each step
3804 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3805 # @ingroup l2_modif_extrurev
3806 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3807 MakeGroups=False, TotalAngle=False):
3808 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3809 AngleInRadians, NbOfSteps, Tolerance,
3810 MakeGroups, TotalAngle)
3812 ## Generate new elements by rotation of the elements of object around the axis
3813 # @param theObject object which elements should be sweeped.
3814 # It can be a mesh, a sub mesh or a group.
3815 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3816 # @param AngleInRadians the angle of Rotation
3817 # @param NbOfSteps number of steps
3818 # @param Tolerance tolerance
3819 # @param MakeGroups forces the generation of new groups from existing ones
3820 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3821 # of all steps, else - size of each step
3822 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3823 # @ingroup l2_modif_extrurev
3824 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3825 MakeGroups=False, TotalAngle=False):
3826 return self.RotationSweepObjects( [], theObject, theObject, Axis,
3827 AngleInRadians, NbOfSteps, Tolerance,
3828 MakeGroups, TotalAngle )
3830 ## Generate new elements by rotation of the elements of object around the axis
3831 # @param theObject object which elements should be sweeped.
3832 # It can be a mesh, a sub mesh or a group.
3833 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3834 # @param AngleInRadians the angle of Rotation
3835 # @param NbOfSteps number of steps
3836 # @param Tolerance tolerance
3837 # @param MakeGroups forces the generation of new groups from existing ones
3838 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3839 # of all steps, else - size of each step
3840 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3841 # @ingroup l2_modif_extrurev
3842 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3843 MakeGroups=False, TotalAngle=False):
3844 return self.RotationSweepObjects([],theObject,[], Axis,
3845 AngleInRadians, NbOfSteps, Tolerance,
3846 MakeGroups, TotalAngle)
3848 ## Generate new elements by rotation of the elements of object around the axis
3849 # @param theObject object which elements should be sweeped.
3850 # It can be a mesh, a sub mesh or a group.
3851 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3852 # @param AngleInRadians the angle of Rotation
3853 # @param NbOfSteps number of steps
3854 # @param Tolerance tolerance
3855 # @param MakeGroups forces the generation of new groups from existing ones
3856 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3857 # of all steps, else - size of each step
3858 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3859 # @ingroup l2_modif_extrurev
3860 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3861 MakeGroups=False, TotalAngle=False):
3862 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3863 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3865 ## Generate new elements by extrusion of the given elements and nodes
3866 # @param nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3867 # @param edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3868 # @param faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3869 # @param StepVector vector or DirStruct or 3 vector components, defining
3870 # the direction and value of extrusion for one step (the total extrusion
3871 # length will be NbOfSteps * ||StepVector||)
3872 # @param NbOfSteps the number of steps
3873 # @param MakeGroups forces the generation of new groups from existing ones
3874 # @param scaleFactors optional scale factors to apply during extrusion
3875 # @param linearVariation if @c True, scaleFactors are spread over all @a scaleFactors,
3876 # else scaleFactors[i] is applied to nodes at the i-th extrusion step
3877 # @param basePoint optional scaling center; if not provided, a gravity center of
3878 # nodes and elements being extruded is used as the scaling center.
3880 # - a list of tree components of the point or
3883 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3884 # @ingroup l2_modif_extrurev
3885 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False,
3886 scaleFactors=[], linearVariation=False, basePoint=[] ):
3887 unRegister = genObjUnRegister()
3888 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3889 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3890 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3892 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3893 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3894 if isinstance( StepVector, list ):
3895 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3897 if isinstance( basePoint, int):
3898 xyz = self.GetNodeXYZ( basePoint )
3900 raise RuntimeError, "Invalid node ID: %s" % basePoint
3902 if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
3903 basePoint = self.geompyD.PointCoordinates( basePoint )
3905 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3906 Parameters = StepVector.PS.parameters + var_separator + Parameters
3907 self.mesh.SetParameters(Parameters)
3909 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
3910 StepVector, NbOfSteps,
3911 scaleFactors, linearVariation, basePoint,
3915 ## Generate new elements by extrusion of the elements with given ids
3916 # @param IDsOfElements the list of ids of elements or nodes for extrusion
3917 # @param StepVector vector or DirStruct or 3 vector components, defining
3918 # the direction and value of extrusion for one step (the total extrusion
3919 # length will be NbOfSteps * ||StepVector||)
3920 # @param NbOfSteps the number of steps
3921 # @param MakeGroups forces the generation of new groups from existing ones
3922 # @param IsNodes is True if elements with given ids are nodes
3923 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3924 # @ingroup l2_modif_extrurev
3925 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3927 if IsNodes: n = IDsOfElements
3928 else : e,f, = IDsOfElements,IDsOfElements
3929 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3931 ## Generate new elements by extrusion along the normal to a discretized surface or wire
3932 # @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh.
3933 # Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
3934 # @param StepSize length of one extrusion step (the total extrusion
3935 # length will be \a NbOfSteps * \a StepSize ).
3936 # @param NbOfSteps number of extrusion steps.
3937 # @param ByAverageNormal if True each node is translated by \a StepSize
3938 # along the average of the normal vectors to the faces sharing the node;
3939 # else each node is translated along the same average normal till
3940 # intersection with the plane got by translation of the face sharing
3941 # the node along its own normal by \a StepSize.
3942 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3943 # for every node of \a Elements.
3944 # @param MakeGroups forces generation of new groups from existing ones.
3945 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
3946 # is not yet implemented. This parameter is used if \a Elements contains
3947 # both faces and edges, i.e. \a Elements is a Mesh.
3948 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
3949 # empty list otherwise.
3950 # @ingroup l2_modif_extrurev
3951 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
3952 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
3953 unRegister = genObjUnRegister()
3954 if isinstance( Elements, Mesh ):
3955 Elements = [ Elements.GetMesh() ]
3956 if isinstance( Elements, list ):
3958 raise RuntimeError, "Elements empty!"
3959 if isinstance( Elements[0], int ):
3960 Elements = self.GetIDSource( Elements, SMESH.ALL )
3961 unRegister.set( Elements )
3962 if not isinstance( Elements, list ):
3963 Elements = [ Elements ]
3964 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
3965 self.mesh.SetParameters(Parameters)
3966 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
3967 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
3969 ## Generate new elements by extrusion of the elements or nodes which belong to the object
3970 # @param theObject the object whose elements or nodes should be processed.
3971 # It can be a mesh, a sub-mesh or a group.
3972 # @param StepVector vector or DirStruct or 3 vector components, defining
3973 # the direction and value of extrusion for one step (the total extrusion
3974 # length will be NbOfSteps * ||StepVector||)
3975 # @param NbOfSteps the number of steps
3976 # @param MakeGroups forces the generation of new groups from existing ones
3977 # @param IsNodes is True if elements to extrude are nodes
3978 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3979 # @ingroup l2_modif_extrurev
3980 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3982 if IsNodes: n = theObject
3983 else : e,f, = theObject,theObject
3984 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3986 ## Generate new elements by extrusion of edges which belong to the object
3987 # @param theObject object whose 1D elements should be processed.
3988 # It can be a mesh, a sub-mesh or a group.
3989 # @param StepVector vector or DirStruct or 3 vector components, defining
3990 # the direction and value of extrusion for one step (the total extrusion
3991 # length will be NbOfSteps * ||StepVector||)
3992 # @param NbOfSteps the number of steps
3993 # @param MakeGroups to generate new groups from existing ones
3994 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3995 # @ingroup l2_modif_extrurev
3996 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3997 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
3999 ## Generate new elements by extrusion of faces which belong to the object
4000 # @param theObject object whose 2D elements should be processed.
4001 # It can be a mesh, a sub-mesh or a group.
4002 # @param StepVector vector or DirStruct or 3 vector components, defining
4003 # the direction and value of extrusion for one step (the total extrusion
4004 # length will be NbOfSteps * ||StepVector||)
4005 # @param NbOfSteps the number of steps
4006 # @param MakeGroups forces the generation of new groups from existing ones
4007 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4008 # @ingroup l2_modif_extrurev
4009 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
4010 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
4012 ## Generate new elements by extrusion of the elements with given ids
4013 # @param IDsOfElements is ids of elements
4014 # @param StepVector vector or DirStruct or 3 vector components, defining
4015 # the direction and value of extrusion for one step (the total extrusion
4016 # length will be NbOfSteps * ||StepVector||)
4017 # @param NbOfSteps the number of steps
4018 # @param ExtrFlags sets flags for extrusion
4019 # @param SewTolerance uses for comparing locations of nodes if flag
4020 # EXTRUSION_FLAG_SEW is set
4021 # @param MakeGroups forces the generation of new groups from existing ones
4022 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4023 # @ingroup l2_modif_extrurev
4024 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
4025 ExtrFlags, SewTolerance, MakeGroups=False):
4026 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
4027 StepVector = self.smeshpyD.GetDirStruct(StepVector)
4028 if isinstance( StepVector, list ):
4029 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
4030 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
4031 ExtrFlags, SewTolerance, MakeGroups)
4033 ## Generate new elements by extrusion of the given elements and nodes along the path.
4034 # The path of extrusion must be a meshed edge.
4035 # @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
4036 # @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
4037 # @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
4038 # @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4039 # @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
4040 # contains not only path segments, else it can be None
4041 # @param NodeStart the first or the last node on the path. Defines the direction of extrusion
4042 # @param HasAngles allows the shape to be rotated around the path
4043 # to get the resulting mesh in a helical fashion
4044 # @param Angles list of angles
4045 # @param LinearVariation forces the computation of rotation angles as linear
4046 # variation of the given Angles along path steps
4047 # @param HasRefPoint allows using the reference point
4048 # @param RefPoint the point around which the shape is rotated (the mass center of the
4049 # shape by default). The User can specify any point as the Reference Point.
4050 # @param MakeGroups forces the generation of new groups from existing ones
4051 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
4052 # @ingroup l2_modif_extrurev
4053 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
4054 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
4055 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
4056 unRegister = genObjUnRegister()
4057 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
4058 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
4059 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
4061 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
4062 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4063 if isinstance( RefPoint, list ):
4064 if not RefPoint: RefPoint = [0,0,0]
4065 RefPoint = SMESH.PointStruct( *RefPoint )
4066 if isinstance( PathMesh, Mesh ):
4067 PathMesh = PathMesh.GetMesh()
4068 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4069 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4070 self.mesh.SetParameters(Parameters)
4071 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
4072 PathMesh, PathShape, NodeStart,
4073 HasAngles, Angles, LinearVariation,
4074 HasRefPoint, RefPoint, MakeGroups)
4076 ## Generate new elements by extrusion of the given elements
4077 # The path of extrusion must be a meshed edge.
4078 # @param Base mesh or group, or sub-mesh, or list of ids of elements for extrusion
4079 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4080 # @param NodeStart the start node from Path. Defines the direction of extrusion
4081 # @param HasAngles allows the shape to be rotated around the path
4082 # to get the resulting mesh in a helical fashion
4083 # @param Angles list of angles in radians
4084 # @param LinearVariation forces the computation of rotation angles as linear
4085 # variation of the given Angles along path steps
4086 # @param HasRefPoint allows using the reference point
4087 # @param RefPoint the point around which the elements are rotated (the mass
4088 # center of the elements by default).
4089 # The User can specify any point as the Reference Point.
4090 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
4091 # @param MakeGroups forces the generation of new groups from existing ones
4092 # @param ElemType type of elements for extrusion (if param Base is a mesh)
4093 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4094 # only SMESH::Extrusion_Error otherwise
4095 # @ingroup l2_modif_extrurev
4096 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
4097 HasAngles=False, Angles=[], LinearVariation=False,
4098 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
4099 ElemType=SMESH.FACE):
4101 if ElemType == SMESH.NODE: n = Base
4102 if ElemType == SMESH.EDGE: e = Base
4103 if ElemType == SMESH.FACE: f = Base
4104 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
4105 HasAngles, Angles, LinearVariation,
4106 HasRefPoint, RefPoint, MakeGroups)
4107 if MakeGroups: return gr,er
4110 ## Generate new elements by extrusion of the given elements
4111 # The path of extrusion must be a meshed edge.
4112 # @param IDsOfElements ids of elements
4113 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
4114 # @param PathShape shape(edge) defines the sub-mesh for the path
4115 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4116 # @param HasAngles allows the shape to be rotated around the path
4117 # to get the resulting mesh in a helical fashion
4118 # @param Angles list of angles in radians
4119 # @param HasRefPoint allows using the reference point
4120 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4121 # The User can specify any point as the Reference Point.
4122 # @param MakeGroups forces the generation of new groups from existing ones
4123 # @param LinearVariation forces the computation of rotation angles as linear
4124 # variation of the given Angles along path steps
4125 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4126 # only SMESH::Extrusion_Error otherwise
4127 # @ingroup l2_modif_extrurev
4128 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
4129 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4130 MakeGroups=False, LinearVariation=False):
4131 n,e,f = [],IDsOfElements,IDsOfElements
4132 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
4133 NodeStart, HasAngles, Angles,
4135 HasRefPoint, RefPoint, MakeGroups)
4136 if MakeGroups: return gr,er
4139 ## Generate new elements by extrusion of the elements which belong to the object
4140 # The path of extrusion must be a meshed edge.
4141 # @param theObject the object whose elements should be processed.
4142 # It can be a mesh, a sub-mesh or a group.
4143 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4144 # @param PathShape shape(edge) defines the sub-mesh for the path
4145 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4146 # @param HasAngles allows the shape to be rotated around the path
4147 # to get the resulting mesh in a helical fashion
4148 # @param Angles list of angles
4149 # @param HasRefPoint allows using the reference point
4150 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4151 # The User can specify any point as the Reference Point.
4152 # @param MakeGroups forces the generation of new groups from existing ones
4153 # @param LinearVariation forces the computation of rotation angles as linear
4154 # variation of the given Angles along path steps
4155 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4156 # only SMESH::Extrusion_Error otherwise
4157 # @ingroup l2_modif_extrurev
4158 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4159 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4160 MakeGroups=False, LinearVariation=False):
4161 n,e,f = [],theObject,theObject
4162 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4163 HasAngles, Angles, LinearVariation,
4164 HasRefPoint, RefPoint, MakeGroups)
4165 if MakeGroups: return gr,er
4168 ## Generate new elements by extrusion of mesh segments which belong to the object
4169 # The path of extrusion must be a meshed edge.
4170 # @param theObject the object whose 1D elements should be processed.
4171 # It can be a mesh, a sub-mesh or a group.
4172 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4173 # @param PathShape shape(edge) defines the sub-mesh for the path
4174 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4175 # @param HasAngles allows the shape to be rotated around the path
4176 # to get the resulting mesh in a helical fashion
4177 # @param Angles list of angles
4178 # @param HasRefPoint allows using the reference point
4179 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4180 # The User can specify any point as the Reference Point.
4181 # @param MakeGroups forces the generation of new groups from existing ones
4182 # @param LinearVariation forces the computation of rotation angles as linear
4183 # variation of the given Angles along path steps
4184 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4185 # only SMESH::Extrusion_Error otherwise
4186 # @ingroup l2_modif_extrurev
4187 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4188 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4189 MakeGroups=False, LinearVariation=False):
4190 n,e,f = [],theObject,[]
4191 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4192 HasAngles, Angles, LinearVariation,
4193 HasRefPoint, RefPoint, MakeGroups)
4194 if MakeGroups: return gr,er
4197 ## Generate new elements by extrusion of faces which belong to the object
4198 # The path of extrusion must be a meshed edge.
4199 # @param theObject the object whose 2D elements should be processed.
4200 # It can be a mesh, a sub-mesh or a group.
4201 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4202 # @param PathShape shape(edge) defines the sub-mesh for the path
4203 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4204 # @param HasAngles allows the shape to be rotated around the path
4205 # to get the resulting mesh in a helical fashion
4206 # @param Angles list of angles
4207 # @param HasRefPoint allows using the reference point
4208 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4209 # The User can specify any point as the Reference Point.
4210 # @param MakeGroups forces the generation of new groups from existing ones
4211 # @param LinearVariation forces the computation of rotation angles as linear
4212 # variation of the given Angles along path steps
4213 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4214 # only SMESH::Extrusion_Error otherwise
4215 # @ingroup l2_modif_extrurev
4216 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4217 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4218 MakeGroups=False, LinearVariation=False):
4219 n,e,f = [],[],theObject
4220 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4221 HasAngles, Angles, LinearVariation,
4222 HasRefPoint, RefPoint, MakeGroups)
4223 if MakeGroups: return gr,er
4226 ## Create a symmetrical copy of mesh elements
4227 # @param IDsOfElements list of elements ids
4228 # @param Mirror is AxisStruct or geom object(point, line, plane)
4229 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4230 # If the Mirror is a geom object this parameter is unnecessary
4231 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4232 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4233 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4234 # @ingroup l2_modif_trsf
4235 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4236 if IDsOfElements == []:
4237 IDsOfElements = self.GetElementsId()
4238 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4239 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4240 theMirrorType = Mirror._mirrorType
4242 self.mesh.SetParameters(Mirror.parameters)
4243 if Copy and MakeGroups:
4244 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4245 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4248 ## Create a new mesh by a symmetrical copy of mesh elements
4249 # @param IDsOfElements the list of elements ids
4250 # @param Mirror is AxisStruct or geom object (point, line, plane)
4251 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4252 # If the Mirror is a geom object this parameter is unnecessary
4253 # @param MakeGroups to generate new groups from existing ones
4254 # @param NewMeshName a name of the new mesh to create
4255 # @return instance of Mesh class
4256 # @ingroup l2_modif_trsf
4257 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4258 if IDsOfElements == []:
4259 IDsOfElements = self.GetElementsId()
4260 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4261 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4262 theMirrorType = Mirror._mirrorType
4264 self.mesh.SetParameters(Mirror.parameters)
4265 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4266 MakeGroups, NewMeshName)
4267 return Mesh(self.smeshpyD,self.geompyD,mesh)
4269 ## Create a symmetrical copy of the object
4270 # @param theObject mesh, submesh or group
4271 # @param Mirror AxisStruct or geom object (point, line, plane)
4272 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4273 # If the Mirror is a geom object this parameter is unnecessary
4274 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4275 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4276 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4277 # @ingroup l2_modif_trsf
4278 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4279 if ( isinstance( theObject, Mesh )):
4280 theObject = theObject.GetMesh()
4281 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4282 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4283 theMirrorType = Mirror._mirrorType
4285 self.mesh.SetParameters(Mirror.parameters)
4286 if Copy and MakeGroups:
4287 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4288 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4291 ## Create a new mesh by a symmetrical copy of the object
4292 # @param theObject mesh, submesh or group
4293 # @param Mirror AxisStruct or geom object (point, line, plane)
4294 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4295 # If the Mirror is a geom object this parameter is unnecessary
4296 # @param MakeGroups forces the generation of new groups from existing ones
4297 # @param NewMeshName the name of the new mesh to create
4298 # @return instance of Mesh class
4299 # @ingroup l2_modif_trsf
4300 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4301 if ( isinstance( theObject, Mesh )):
4302 theObject = theObject.GetMesh()
4303 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4304 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4305 theMirrorType = Mirror._mirrorType
4307 self.mesh.SetParameters(Mirror.parameters)
4308 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4309 MakeGroups, NewMeshName)
4310 return Mesh( self.smeshpyD,self.geompyD,mesh )
4312 ## Translate the elements
4313 # @param IDsOfElements list of elements ids
4314 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4315 # @param Copy allows copying the translated elements
4316 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4317 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4318 # @ingroup l2_modif_trsf
4319 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4320 if IDsOfElements == []:
4321 IDsOfElements = self.GetElementsId()
4322 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4323 Vector = self.smeshpyD.GetDirStruct(Vector)
4324 if isinstance( Vector, list ):
4325 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4326 self.mesh.SetParameters(Vector.PS.parameters)
4327 if Copy and MakeGroups:
4328 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4329 self.editor.Translate(IDsOfElements, Vector, Copy)
4332 ## Create a new mesh of translated elements
4333 # @param IDsOfElements list of elements ids
4334 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4335 # @param MakeGroups forces the generation of new groups from existing ones
4336 # @param NewMeshName the name of the newly created mesh
4337 # @return instance of Mesh class
4338 # @ingroup l2_modif_trsf
4339 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4340 if IDsOfElements == []:
4341 IDsOfElements = self.GetElementsId()
4342 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4343 Vector = self.smeshpyD.GetDirStruct(Vector)
4344 if isinstance( Vector, list ):
4345 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4346 self.mesh.SetParameters(Vector.PS.parameters)
4347 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4348 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4350 ## Translate the object
4351 # @param theObject the object to translate (mesh, submesh, or group)
4352 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4353 # @param Copy allows copying the translated elements
4354 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4355 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4356 # @ingroup l2_modif_trsf
4357 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4358 if ( isinstance( theObject, Mesh )):
4359 theObject = theObject.GetMesh()
4360 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4361 Vector = self.smeshpyD.GetDirStruct(Vector)
4362 if isinstance( Vector, list ):
4363 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4364 self.mesh.SetParameters(Vector.PS.parameters)
4365 if Copy and MakeGroups:
4366 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4367 self.editor.TranslateObject(theObject, Vector, Copy)
4370 ## Create a new mesh from the translated object
4371 # @param theObject the object to translate (mesh, submesh, or group)
4372 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4373 # @param MakeGroups forces the generation of new groups from existing ones
4374 # @param NewMeshName the name of the newly created mesh
4375 # @return instance of Mesh class
4376 # @ingroup l2_modif_trsf
4377 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4378 if isinstance( theObject, Mesh ):
4379 theObject = theObject.GetMesh()
4380 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4381 Vector = self.smeshpyD.GetDirStruct(Vector)
4382 if isinstance( Vector, list ):
4383 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4384 self.mesh.SetParameters(Vector.PS.parameters)
4385 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4386 return Mesh( self.smeshpyD, self.geompyD, mesh )
4391 # @param theObject - the object to translate (mesh, submesh, or group)
4392 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4393 # @param theScaleFact - list of 1-3 scale factors for axises
4394 # @param Copy - allows copying the translated elements
4395 # @param MakeGroups - forces the generation of new groups from existing
4397 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4398 # empty list otherwise
4399 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4400 unRegister = genObjUnRegister()
4401 if ( isinstance( theObject, Mesh )):
4402 theObject = theObject.GetMesh()
4403 if ( isinstance( theObject, list )):
4404 theObject = self.GetIDSource(theObject, SMESH.ALL)
4405 unRegister.set( theObject )
4406 if ( isinstance( thePoint, list )):
4407 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4408 if ( isinstance( theScaleFact, float )):
4409 theScaleFact = [theScaleFact]
4410 if ( isinstance( theScaleFact, int )):
4411 theScaleFact = [ float(theScaleFact)]
4413 self.mesh.SetParameters(thePoint.parameters)
4415 if Copy and MakeGroups:
4416 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4417 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4420 ## Create a new mesh from the translated object
4421 # @param theObject - the object to translate (mesh, submesh, or group)
4422 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4423 # @param theScaleFact - list of 1-3 scale factors for axises
4424 # @param MakeGroups - forces the generation of new groups from existing ones
4425 # @param NewMeshName - the name of the newly created mesh
4426 # @return instance of Mesh class
4427 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4428 unRegister = genObjUnRegister()
4429 if (isinstance(theObject, Mesh)):
4430 theObject = theObject.GetMesh()
4431 if ( isinstance( theObject, list )):
4432 theObject = self.GetIDSource(theObject,SMESH.ALL)
4433 unRegister.set( theObject )
4434 if ( isinstance( thePoint, list )):
4435 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4436 if ( isinstance( theScaleFact, float )):
4437 theScaleFact = [theScaleFact]
4438 if ( isinstance( theScaleFact, int )):
4439 theScaleFact = [ float(theScaleFact)]
4441 self.mesh.SetParameters(thePoint.parameters)
4442 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4443 MakeGroups, NewMeshName)
4444 return Mesh( self.smeshpyD, self.geompyD, mesh )
4448 ## Rotate the elements
4449 # @param IDsOfElements list of elements ids
4450 # @param Axis the axis of rotation (AxisStruct or geom line)
4451 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4452 # @param Copy allows copying the rotated elements
4453 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4454 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4455 # @ingroup l2_modif_trsf
4456 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4457 if IDsOfElements == []:
4458 IDsOfElements = self.GetElementsId()
4459 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4460 Axis = self.smeshpyD.GetAxisStruct(Axis)
4461 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4462 Parameters = Axis.parameters + var_separator + Parameters
4463 self.mesh.SetParameters(Parameters)
4464 if Copy and MakeGroups:
4465 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4466 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4469 ## Create a new mesh of rotated elements
4470 # @param IDsOfElements list of element ids
4471 # @param Axis the axis of rotation (AxisStruct or geom line)
4472 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4473 # @param MakeGroups forces the generation of new groups from existing ones
4474 # @param NewMeshName the name of the newly created mesh
4475 # @return instance of Mesh class
4476 # @ingroup l2_modif_trsf
4477 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4478 if IDsOfElements == []:
4479 IDsOfElements = self.GetElementsId()
4480 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4481 Axis = self.smeshpyD.GetAxisStruct(Axis)
4482 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4483 Parameters = Axis.parameters + var_separator + Parameters
4484 self.mesh.SetParameters(Parameters)
4485 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4486 MakeGroups, NewMeshName)
4487 return Mesh( self.smeshpyD, self.geompyD, mesh )
4489 ## Rotate the object
4490 # @param theObject the object to rotate( mesh, submesh, or group)
4491 # @param Axis the axis of rotation (AxisStruct or geom line)
4492 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4493 # @param Copy allows copying the rotated elements
4494 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4495 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4496 # @ingroup l2_modif_trsf
4497 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4498 if (isinstance(theObject, Mesh)):
4499 theObject = theObject.GetMesh()
4500 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4501 Axis = self.smeshpyD.GetAxisStruct(Axis)
4502 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4503 Parameters = Axis.parameters + ":" + Parameters
4504 self.mesh.SetParameters(Parameters)
4505 if Copy and MakeGroups:
4506 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4507 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4510 ## Create a new mesh from the rotated object
4511 # @param theObject the object to rotate (mesh, submesh, or group)
4512 # @param Axis the axis of rotation (AxisStruct or geom line)
4513 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4514 # @param MakeGroups forces the generation of new groups from existing ones
4515 # @param NewMeshName the name of the newly created mesh
4516 # @return instance of Mesh class
4517 # @ingroup l2_modif_trsf
4518 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4519 if (isinstance( theObject, Mesh )):
4520 theObject = theObject.GetMesh()
4521 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4522 Axis = self.smeshpyD.GetAxisStruct(Axis)
4523 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4524 Parameters = Axis.parameters + ":" + Parameters
4525 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4526 MakeGroups, NewMeshName)
4527 self.mesh.SetParameters(Parameters)
4528 return Mesh( self.smeshpyD, self.geompyD, mesh )
4530 ## Find groups of adjacent nodes within Tolerance.
4531 # @param Tolerance the value of tolerance
4532 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4533 # corner and medium nodes in separate groups thus preventing
4534 # their further merge.
4535 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4536 # @ingroup l2_modif_trsf
4537 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
4538 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
4540 ## Find groups of ajacent nodes within Tolerance.
4541 # @param Tolerance the value of tolerance
4542 # @param SubMeshOrGroup SubMesh, Group or Filter
4543 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4544 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4545 # corner and medium nodes in separate groups thus preventing
4546 # their further merge.
4547 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4548 # @ingroup l2_modif_trsf
4549 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
4550 exceptNodes=[], SeparateCornerAndMediumNodes=False):
4551 unRegister = genObjUnRegister()
4552 if (isinstance( SubMeshOrGroup, Mesh )):
4553 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4554 if not isinstance( exceptNodes, list ):
4555 exceptNodes = [ exceptNodes ]
4556 if exceptNodes and isinstance( exceptNodes[0], int ):
4557 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
4558 unRegister.set( exceptNodes )
4559 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
4560 exceptNodes, SeparateCornerAndMediumNodes)
4563 # @param GroupsOfNodes a list of groups of nodes IDs for merging
4564 # (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
4565 # by nodes 1 and 25 correspondingly in all elements and groups
4566 # @param NodesToKeep nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
4567 # If @a NodesToKeep does not include a node to keep for some group to merge,
4568 # then the first node in the group is kept.
4569 # @param AvoidMakingHoles prevent merging nodes which cause removal of elements becoming
4571 # @ingroup l2_modif_trsf
4572 def MergeNodes (self, GroupsOfNodes, NodesToKeep=[], AvoidMakingHoles=False):
4573 # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
4574 self.editor.MergeNodes( GroupsOfNodes, NodesToKeep, AvoidMakingHoles )
4576 ## Find the elements built on the same nodes.
4577 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4578 # @return the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
4579 # @ingroup l2_modif_trsf
4580 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4581 if not MeshOrSubMeshOrGroup:
4582 MeshOrSubMeshOrGroup=self.mesh
4583 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4584 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4585 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4587 ## Merge elements in each given group.
4588 # @param GroupsOfElementsID a list of groups of elements IDs for merging
4589 # (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
4590 # replaced by elements 1 and 25 in all groups)
4591 # @ingroup l2_modif_trsf
4592 def MergeElements(self, GroupsOfElementsID):
4593 self.editor.MergeElements(GroupsOfElementsID)
4595 ## Leave one element and remove all other elements built on the same nodes.
4596 # @ingroup l2_modif_trsf
4597 def MergeEqualElements(self):
4598 self.editor.MergeEqualElements()
4600 ## Return groups of FreeBorder's coincident within the given tolerance.
4601 # @param tolerance the tolerance. If the tolerance <= 0.0 then one tenth of an average
4602 # size of elements adjacent to free borders being compared is used.
4603 # @return SMESH.CoincidentFreeBorders structure
4604 # @ingroup l2_modif_trsf
4605 def FindCoincidentFreeBorders (self, tolerance=0.):
4606 return self.editor.FindCoincidentFreeBorders( tolerance )
4608 ## Sew FreeBorder's of each group
4609 # @param freeBorders either a SMESH.CoincidentFreeBorders structure or a list of lists
4610 # where each enclosed list contains node IDs of a group of coincident free
4611 # borders such that each consequent triple of IDs within a group describes
4612 # a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
4613 # last node of a border.
4614 # For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
4615 # groups of coincident free borders, each group including two borders.
4616 # @param createPolygons if @c True faces adjacent to free borders are converted to
4617 # polygons if a node of opposite border falls on a face edge, else such
4618 # faces are split into several ones.
4619 # @param createPolyhedra if @c True volumes adjacent to free borders are converted to
4620 # polyhedra if a node of opposite border falls on a volume edge, else such
4621 # volumes, if any, remain intact and the mesh becomes non-conformal.
4622 # @return a number of successfully sewed groups
4623 # @ingroup l2_modif_trsf
4624 def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
4625 if freeBorders and isinstance( freeBorders, list ):
4626 # construct SMESH.CoincidentFreeBorders
4627 if isinstance( freeBorders[0], int ):
4628 freeBorders = [freeBorders]
4630 coincidentGroups = []
4631 for nodeList in freeBorders:
4632 if not nodeList or len( nodeList ) % 3:
4633 raise ValueError, "Wrong number of nodes in this group: %s" % nodeList
4636 group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
4637 borders.append( SMESH.FreeBorder( nodeList[:3] ))
4638 nodeList = nodeList[3:]
4640 coincidentGroups.append( group )
4642 freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
4644 return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
4647 # @return SMESH::Sew_Error
4648 # @ingroup l2_modif_trsf
4649 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4650 FirstNodeID2, SecondNodeID2, LastNodeID2,
4651 CreatePolygons, CreatePolyedrs):
4652 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4653 FirstNodeID2, SecondNodeID2, LastNodeID2,
4654 CreatePolygons, CreatePolyedrs)
4656 ## Sew conform free borders
4657 # @return SMESH::Sew_Error
4658 # @ingroup l2_modif_trsf
4659 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4660 FirstNodeID2, SecondNodeID2):
4661 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4662 FirstNodeID2, SecondNodeID2)
4664 ## Sew border to side
4665 # @return SMESH::Sew_Error
4666 # @ingroup l2_modif_trsf
4667 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4668 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4669 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4670 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4672 ## Sew two sides of a mesh. The nodes belonging to Side1 are
4673 # merged with the nodes of elements of Side2.
4674 # The number of elements in theSide1 and in theSide2 must be
4675 # equal and they should have similar nodal connectivity.
4676 # The nodes to merge should belong to side borders and
4677 # the first node should be linked to the second.
4678 # @return SMESH::Sew_Error
4679 # @ingroup l2_modif_trsf
4680 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4681 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4682 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4683 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4684 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4685 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4687 ## Set new nodes for the given element.
4688 # @param ide the element id
4689 # @param newIDs nodes ids
4690 # @return If the number of nodes does not correspond to the type of element - return false
4691 # @ingroup l2_modif_edit
4692 def ChangeElemNodes(self, ide, newIDs):
4693 return self.editor.ChangeElemNodes(ide, newIDs)
4695 ## If during the last operation of MeshEditor some nodes were
4696 # created, this method return the list of their IDs, \n
4697 # if new nodes were not created - return empty list
4698 # @return the list of integer values (can be empty)
4699 # @ingroup l2_modif_add
4700 def GetLastCreatedNodes(self):
4701 return self.editor.GetLastCreatedNodes()
4703 ## If during the last operation of MeshEditor some elements were
4704 # created this method return the list of their IDs, \n
4705 # if new elements were not created - return empty list
4706 # @return the list of integer values (can be empty)
4707 # @ingroup l2_modif_add
4708 def GetLastCreatedElems(self):
4709 return self.editor.GetLastCreatedElems()
4711 ## Forget what nodes and elements were created by the last mesh edition operation
4712 # @ingroup l2_modif_add
4713 def ClearLastCreated(self):
4714 self.editor.ClearLastCreated()
4716 ## Create duplicates of given elements, i.e. create new elements based on the
4717 # same nodes as the given ones.
4718 # @param theElements - container of elements to duplicate. It can be a Mesh,
4719 # sub-mesh, group, filter or a list of element IDs. If \a theElements is
4720 # a Mesh, elements of highest dimension are duplicated
4721 # @param theGroupName - a name of group to contain the generated elements.
4722 # If a group with such a name already exists, the new elements
4723 # are added to the existng group, else a new group is created.
4724 # If \a theGroupName is empty, new elements are not added
4726 # @return a group where the new elements are added. None if theGroupName == "".
4727 # @ingroup l2_modif_duplicat
4728 def DoubleElements(self, theElements, theGroupName=""):
4729 unRegister = genObjUnRegister()
4730 if isinstance( theElements, Mesh ):
4731 theElements = theElements.mesh
4732 elif isinstance( theElements, list ):
4733 theElements = self.GetIDSource( theElements, SMESH.ALL )
4734 unRegister.set( theElements )
4735 return self.editor.DoubleElements(theElements, theGroupName)
4737 ## Create a hole in a mesh by doubling the nodes of some particular elements
4738 # @param theNodes identifiers of nodes to be doubled
4739 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4740 # nodes. If list of element identifiers is empty then nodes are doubled but
4741 # they not assigned to elements
4742 # @return TRUE if operation has been completed successfully, FALSE otherwise
4743 # @ingroup l2_modif_duplicat
4744 def DoubleNodes(self, theNodes, theModifiedElems):
4745 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4747 ## Create a hole in a mesh by doubling the nodes of some particular elements
4748 # This method provided for convenience works as DoubleNodes() described above.
4749 # @param theNodeId identifiers of node to be doubled
4750 # @param theModifiedElems identifiers of elements to be updated
4751 # @return TRUE if operation has been completed successfully, FALSE otherwise
4752 # @ingroup l2_modif_duplicat
4753 def DoubleNode(self, theNodeId, theModifiedElems):
4754 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4756 ## Create a hole in a mesh by doubling the nodes of some particular elements
4757 # This method provided for convenience works as DoubleNodes() described above.
4758 # @param theNodes group of nodes to be doubled
4759 # @param theModifiedElems group of elements to be updated.
4760 # @param theMakeGroup forces the generation of a group containing new nodes.
4761 # @return TRUE or a created group if operation has been completed successfully,
4762 # FALSE or None otherwise
4763 # @ingroup l2_modif_duplicat
4764 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4766 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4767 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4769 ## Create a hole in a mesh by doubling the nodes of some particular elements
4770 # This method provided for convenience works as DoubleNodes() described above.
4771 # @param theNodes list of groups of nodes to be doubled
4772 # @param theModifiedElems list of groups of elements to be updated.
4773 # @param theMakeGroup forces the generation of a group containing new nodes.
4774 # @return TRUE if operation has been completed successfully, FALSE otherwise
4775 # @ingroup l2_modif_duplicat
4776 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4778 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4779 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4781 ## Create a hole in a mesh by doubling the nodes of some particular elements
4782 # @param theElems - the list of elements (edges or faces) to be replicated
4783 # The nodes for duplication could be found from these elements
4784 # @param theNodesNot - list of nodes to NOT replicate
4785 # @param theAffectedElems - the list of elements (cells and edges) to which the
4786 # replicated nodes should be associated to.
4787 # @return TRUE if operation has been completed successfully, FALSE otherwise
4788 # @ingroup l2_modif_duplicat
4789 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4790 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4792 ## Create a hole in a mesh by doubling the nodes of some particular elements
4793 # @param theElems - the list of elements (edges or faces) to be replicated
4794 # The nodes for duplication could be found from these elements
4795 # @param theNodesNot - list of nodes to NOT replicate
4796 # @param theShape - shape to detect affected elements (element which geometric center
4797 # located on or inside shape).
4798 # The replicated nodes should be associated to affected elements.
4799 # @return TRUE if operation has been completed successfully, FALSE otherwise
4800 # @ingroup l2_modif_duplicat
4801 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4802 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4804 ## Create a hole in a mesh by doubling the nodes of some particular elements
4805 # This method provided for convenience works as DoubleNodes() described above.
4806 # @param theElems - group of of elements (edges or faces) to be replicated
4807 # @param theNodesNot - group of nodes not to replicated
4808 # @param theAffectedElems - group of elements to which the replicated nodes
4809 # should be associated to.
4810 # @param theMakeGroup forces the generation of a group containing new elements.
4811 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4812 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4813 # FALSE or None otherwise
4814 # @ingroup l2_modif_duplicat
4815 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4816 theMakeGroup=False, theMakeNodeGroup=False):
4817 if theMakeGroup or theMakeNodeGroup:
4818 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4820 theMakeGroup, theMakeNodeGroup)
4821 if theMakeGroup and theMakeNodeGroup:
4824 return twoGroups[ int(theMakeNodeGroup) ]
4825 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4827 ## Create a hole in a mesh by doubling the nodes of some particular elements
4828 # This method provided for convenience works as DoubleNodes() described above.
4829 # @param theElems - group of of elements (edges or faces) to be replicated
4830 # @param theNodesNot - group of nodes not to replicated
4831 # @param theShape - shape to detect affected elements (element which geometric center
4832 # located on or inside shape).
4833 # The replicated nodes should be associated to affected elements.
4834 # @ingroup l2_modif_duplicat
4835 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4836 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4838 ## Create a hole in a mesh by doubling the nodes of some particular elements
4839 # This method provided for convenience works as DoubleNodes() described above.
4840 # @param theElems - list of groups of elements (edges or faces) to be replicated
4841 # @param theNodesNot - list of groups of nodes not to replicated
4842 # @param theAffectedElems - group of elements to which the replicated nodes
4843 # should be associated to.
4844 # @param theMakeGroup forces the generation of a group containing new elements.
4845 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4846 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4847 # FALSE or None otherwise
4848 # @ingroup l2_modif_duplicat
4849 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4850 theMakeGroup=False, theMakeNodeGroup=False):
4851 if theMakeGroup or theMakeNodeGroup:
4852 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4854 theMakeGroup, theMakeNodeGroup)
4855 if theMakeGroup and theMakeNodeGroup:
4858 return twoGroups[ int(theMakeNodeGroup) ]
4859 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4861 ## Create a hole in a mesh by doubling the nodes of some particular elements
4862 # This method provided for convenience works as DoubleNodes() described above.
4863 # @param theElems - list of groups of elements (edges or faces) to be replicated
4864 # @param theNodesNot - list of groups of nodes not to replicated
4865 # @param theShape - shape to detect affected elements (element which geometric center
4866 # located on or inside shape).
4867 # The replicated nodes should be associated to affected elements.
4868 # @return TRUE if operation has been completed successfully, FALSE otherwise
4869 # @ingroup l2_modif_duplicat
4870 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4871 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4873 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4874 # This method is the first step of DoubleNodeElemGroupsInRegion.
4875 # @param theElems - list of groups of elements (edges or faces) to be replicated
4876 # @param theNodesNot - list of groups of nodes not to replicated
4877 # @param theShape - shape to detect affected elements (element which geometric center
4878 # located on or inside shape).
4879 # The replicated nodes should be associated to affected elements.
4880 # @return groups of affected elements
4881 # @ingroup l2_modif_duplicat
4882 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4883 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4885 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4886 # The list of groups must describe a partition of the mesh volumes.
4887 # The nodes of the internal faces at the boundaries of the groups are doubled.
4888 # In option, the internal faces are replaced by flat elements.
4889 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4890 # @param theDomains - list of groups of volumes
4891 # @param createJointElems - if TRUE, create the elements
4892 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4893 # the boundary between \a theDomains and the rest mesh
4894 # @return TRUE if operation has been completed successfully, FALSE otherwise
4895 # @ingroup l2_modif_duplicat
4896 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4897 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4899 ## Double nodes on some external faces and create flat elements.
4900 # Flat elements are mainly used by some types of mechanic calculations.
4902 # Each group of the list must be constituted of faces.
4903 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4904 # @param theGroupsOfFaces - list of groups of faces
4905 # @return TRUE if operation has been completed successfully, FALSE otherwise
4906 # @ingroup l2_modif_duplicat
4907 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4908 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4910 ## identify all the elements around a geom shape, get the faces delimiting the hole
4912 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4913 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4915 def _getFunctor(self, funcType ):
4916 fn = self.functors[ funcType._v ]
4918 fn = self.smeshpyD.GetFunctor(funcType)
4919 fn.SetMesh(self.mesh)
4920 self.functors[ funcType._v ] = fn
4923 ## Return value of a functor for a given element
4924 # @param funcType an item of SMESH.FunctorType enum
4925 # Type "SMESH.FunctorType._items" in the Python Console to see all items.
4926 # @param elemId element or node ID
4927 # @param isElem @a elemId is ID of element or node
4928 # @return the functor value or zero in case of invalid arguments
4929 # @ingroup l1_measurements
4930 def FunctorValue(self, funcType, elemId, isElem=True):
4931 fn = self._getFunctor( funcType )
4932 if fn.GetElementType() == self.GetElementType(elemId, isElem):
4933 val = fn.GetValue(elemId)
4938 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4939 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4940 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4941 # @ingroup l1_measurements
4942 def GetLength(self, elemId=None):
4945 length = self.smeshpyD.GetLength(self)
4947 length = self.FunctorValue(SMESH.FT_Length, elemId)
4950 ## Get area of 2D element or sum of areas of all 2D mesh elements
4951 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4952 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4953 # @ingroup l1_measurements
4954 def GetArea(self, elemId=None):
4957 area = self.smeshpyD.GetArea(self)
4959 area = self.FunctorValue(SMESH.FT_Area, elemId)
4962 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4963 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4964 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4965 # @ingroup l1_measurements
4966 def GetVolume(self, elemId=None):
4969 volume = self.smeshpyD.GetVolume(self)
4971 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
4974 ## Get maximum element length.
4975 # @param elemId mesh element ID
4976 # @return element's maximum length value
4977 # @ingroup l1_measurements
4978 def GetMaxElementLength(self, elemId):
4979 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4980 ftype = SMESH.FT_MaxElementLength3D
4982 ftype = SMESH.FT_MaxElementLength2D
4983 return self.FunctorValue(ftype, elemId)
4985 ## Get aspect ratio of 2D or 3D element.
4986 # @param elemId mesh element ID
4987 # @return element's aspect ratio value
4988 # @ingroup l1_measurements
4989 def GetAspectRatio(self, elemId):
4990 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4991 ftype = SMESH.FT_AspectRatio3D
4993 ftype = SMESH.FT_AspectRatio
4994 return self.FunctorValue(ftype, elemId)
4996 ## Get warping angle of 2D element.
4997 # @param elemId mesh element ID
4998 # @return element's warping angle value
4999 # @ingroup l1_measurements
5000 def GetWarping(self, elemId):
5001 return self.FunctorValue(SMESH.FT_Warping, elemId)
5003 ## Get minimum angle of 2D element.
5004 # @param elemId mesh element ID
5005 # @return element's minimum angle value
5006 # @ingroup l1_measurements
5007 def GetMinimumAngle(self, elemId):
5008 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
5010 ## Get taper of 2D element.
5011 # @param elemId mesh element ID
5012 # @return element's taper value
5013 # @ingroup l1_measurements
5014 def GetTaper(self, elemId):
5015 return self.FunctorValue(SMESH.FT_Taper, elemId)
5017 ## Get skew of 2D element.
5018 # @param elemId mesh element ID
5019 # @return element's skew value
5020 # @ingroup l1_measurements
5021 def GetSkew(self, elemId):
5022 return self.FunctorValue(SMESH.FT_Skew, elemId)
5024 ## Return minimal and maximal value of a given functor.
5025 # @param funType a functor type, an item of SMESH.FunctorType enum
5026 # (one of SMESH.FunctorType._items)
5027 # @param meshPart a part of mesh (group, sub-mesh) to treat
5028 # @return tuple (min,max)
5029 # @ingroup l1_measurements
5030 def GetMinMax(self, funType, meshPart=None):
5031 unRegister = genObjUnRegister()
5032 if isinstance( meshPart, list ):
5033 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
5034 unRegister.set( meshPart )
5035 if isinstance( meshPart, Mesh ):
5036 meshPart = meshPart.mesh
5037 fun = self._getFunctor( funType )
5040 if hasattr( meshPart, "SetMesh" ):
5041 meshPart.SetMesh( self.mesh ) # set mesh to filter
5042 hist = fun.GetLocalHistogram( 1, False, meshPart )
5044 hist = fun.GetHistogram( 1, False )
5046 return hist[0].min, hist[0].max
5049 pass # end of Mesh class
5052 ## Private class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
5053 # with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
5055 class meshProxy(SMESH._objref_SMESH_Mesh):
5057 SMESH._objref_SMESH_Mesh.__init__(self)
5058 def __deepcopy__(self, memo=None):
5059 new = self.__class__()
5061 def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
5062 if len( args ) == 3:
5063 args += SMESH.ALL_NODES, True
5064 return SMESH._objref_SMESH_Mesh.CreateDimGroup( self, *args )
5066 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
5069 ## Private class wrapping SMESH.SMESH_SubMesh in order to add Compute()
5071 class submeshProxy(SMESH._objref_SMESH_subMesh):
5073 SMESH._objref_SMESH_subMesh.__init__(self)
5075 def __deepcopy__(self, memo=None):
5076 new = self.__class__()
5079 ## Compute the sub-mesh and return the status of the computation
5080 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
5081 # @return True or False
5083 # This is a method of SMESH.SMESH_submesh that can be obtained via Mesh.GetSubMesh() or
5084 # @ref smesh_algorithm.Mesh_Algorithm.GetSubMesh() "Mesh_Algorithm.GetSubMesh()".
5085 # @ingroup l2_submeshes
5086 def Compute(self,refresh=False):
5088 self.mesh = Mesh( smeshBuilder(), None, self.GetMesh())
5090 ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
5092 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
5093 smeshgui = salome.ImportComponentGUI("SMESH")
5094 smeshgui.Init(self.mesh.GetStudyId())
5095 smeshgui.SetMeshIcon( salome.ObjectToID( self ), ok, (self.GetNumberOfElements()==0) )
5096 if refresh: salome.sg.updateObjBrowser(True)
5101 omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy)
5104 ## Private class used to compensate change of CORBA API of SMESH_MeshEditor for backward
5105 # compatibility with old dump scripts which call SMESH_MeshEditor directly and not via
5108 class meshEditor(SMESH._objref_SMESH_MeshEditor):
5110 SMESH._objref_SMESH_MeshEditor.__init__(self)
5112 def __getattr__(self, name ): # method called if an attribute not found
5113 if not self.mesh: # look for name() method in Mesh class
5114 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
5115 if hasattr( self.mesh, name ):
5116 return getattr( self.mesh, name )
5117 if name == "ExtrusionAlongPathObjX":
5118 return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
5119 print "meshEditor: attribute '%s' NOT FOUND" % name
5121 def __deepcopy__(self, memo=None):
5122 new = self.__class__()
5124 def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
5125 if len( args ) == 1: args += False,
5126 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
5127 def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
5128 if len( args ) == 2: args += False,
5129 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
5130 def MergeNodes(self,*args): # 2 args added (NodesToKeep,AvoidMakingHoles)
5131 if len( args ) == 1:
5132 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [], False )
5133 NodesToKeep = args[1]
5134 AvoidMakingHoles = args[2] if len( args ) == 3 else False
5135 unRegister = genObjUnRegister()
5137 if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
5138 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
5139 if not isinstance( NodesToKeep, list ):
5140 NodesToKeep = [ NodesToKeep ]
5141 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep, AvoidMakingHoles )
5143 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
5145 ## Private class wrapping SMESH.SMESH_Pattern CORBA class in order to treat Notebook
5146 # variables in some methods
5148 class Pattern(SMESH._objref_SMESH_Pattern):
5150 def LoadFromFile(self, patternTextOrFile ):
5151 text = patternTextOrFile
5152 if os.path.exists( text ):
5153 text = open( patternTextOrFile ).read()
5155 return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
5157 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
5158 decrFun = lambda i: i-1
5159 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
5160 theMesh.SetParameters(Parameters)
5161 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
5163 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
5164 decrFun = lambda i: i-1
5165 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
5166 theMesh.SetParameters(Parameters)
5167 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
5169 def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
5170 if isinstance( mesh, Mesh ):
5171 mesh = mesh.GetMesh()
5172 return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
5174 # Registering the new proxy for Pattern
5175 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
5177 ## Private class used to bind methods creating algorithms to the class Mesh
5182 self.defaultAlgoType = ""
5183 self.algoTypeToClass = {}
5185 # Store a python class of algorithm
5186 def add(self, algoClass):
5187 if type( algoClass ).__name__ == 'classobj' and \
5188 hasattr( algoClass, "algoType"):
5189 self.algoTypeToClass[ algoClass.algoType ] = algoClass
5190 if not self.defaultAlgoType and \
5191 hasattr( algoClass, "isDefault") and algoClass.isDefault:
5192 self.defaultAlgoType = algoClass.algoType
5193 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
5195 # Create a copy of self and assign mesh to the copy
5196 def copy(self, mesh):
5197 other = algoCreator()
5198 other.defaultAlgoType = self.defaultAlgoType
5199 other.algoTypeToClass = self.algoTypeToClass
5203 # Create an instance of algorithm
5204 def __call__(self,algo="",geom=0,*args):
5205 algoType = self.defaultAlgoType
5206 for arg in args + (algo,geom):
5207 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
5209 if isinstance( arg, str ) and arg:
5211 if not algoType and self.algoTypeToClass:
5212 algoType = self.algoTypeToClass.keys()[0]
5213 if self.algoTypeToClass.has_key( algoType ):
5214 #print "Create algo",algoType
5215 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
5216 raise RuntimeError, "No class found for algo type %s" % algoType
5219 ## Private class used to substitute and store variable parameters of hypotheses.
5221 class hypMethodWrapper:
5222 def __init__(self, hyp, method):
5224 self.method = method
5225 #print "REBIND:", method.__name__
5228 # call a method of hypothesis with calling SetVarParameter() before
5229 def __call__(self,*args):
5231 return self.method( self.hyp, *args ) # hypothesis method with no args
5233 #print "MethWrapper.__call__",self.method.__name__, args
5235 parsed = ParseParameters(*args) # replace variables with their values
5236 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
5237 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
5238 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
5239 # maybe there is a replaced string arg which is not variable
5240 result = self.method( self.hyp, *args )
5241 except ValueError, detail: # raised by ParseParameters()
5243 result = self.method( self.hyp, *args )
5244 except omniORB.CORBA.BAD_PARAM:
5245 raise ValueError, detail # wrong variable name
5250 ## A helper class that calls UnRegister() of SALOME.GenericObj'es stored in it
5252 class genObjUnRegister:
5254 def __init__(self, genObj=None):
5255 self.genObjList = []
5259 def set(self, genObj):
5260 "Store one or a list of of SALOME.GenericObj'es"
5261 if isinstance( genObj, list ):
5262 self.genObjList.extend( genObj )
5264 self.genObjList.append( genObj )
5268 for genObj in self.genObjList:
5269 if genObj and hasattr( genObj, "UnRegister" ):
5273 ## Bind methods creating mesher plug-ins to the Mesh class
5275 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
5277 #print "pluginName: ", pluginName
5278 pluginBuilderName = pluginName + "Builder"
5280 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
5281 except Exception, e:
5282 from salome_utils import verbose
5283 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
5285 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5286 plugin = eval( pluginBuilderName )
5287 #print " plugin:" , str(plugin)
5289 # add methods creating algorithms to Mesh
5290 for k in dir( plugin ):
5291 if k[0] == '_': continue
5292 algo = getattr( plugin, k )
5293 #print " algo:", str(algo)
5294 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
5295 #print " meshMethod:" , str(algo.meshMethod)
5296 if not hasattr( Mesh, algo.meshMethod ):
5297 setattr( Mesh, algo.meshMethod, algoCreator() )
5299 getattr( Mesh, algo.meshMethod ).add( algo )