1 # Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 # File : smeshBuilder.py
20 # Author : Francis KLOSS, OCC
23 ## @package smeshBuilder
24 # Python API for SALOME %Mesh module
26 ## @defgroup l1_auxiliary Auxiliary methods and structures
27 ## @defgroup l1_creating Creating meshes
29 ## @defgroup l2_impexp Importing and exporting meshes
32 ## These are methods of class \ref smeshBuilder.smeshBuilder "smeshBuilder"
34 ## @defgroup l2_construct Constructing meshes
35 ## @defgroup l2_algorithms Defining Algorithms
37 ## @defgroup l3_algos_basic Basic meshing algorithms
38 ## @defgroup l3_algos_proj Projection Algorithms
39 ## @defgroup l3_algos_segmarv Segments around Vertex
40 ## @defgroup l3_algos_3dextr 3D extrusion meshing algorithm
43 ## @defgroup l2_hypotheses Defining hypotheses
45 ## @defgroup l3_hypos_1dhyps 1D Meshing Hypotheses
46 ## @defgroup l3_hypos_2dhyps 2D Meshing Hypotheses
47 ## @defgroup l3_hypos_maxvol Max Element Volume hypothesis
48 ## @defgroup l3_hypos_quad Quadrangle Parameters hypothesis
49 ## @defgroup l3_hypos_additi Additional Hypotheses
52 ## @defgroup l2_submeshes Constructing sub-meshes
53 ## @defgroup l2_editing Editing Meshes
56 ## @defgroup l1_meshinfo Mesh Information
57 ## @defgroup l1_controls Quality controls and Filtering
58 ## @defgroup l1_grouping Grouping elements
60 ## @defgroup l2_grps_create Creating groups
61 ## @defgroup l2_grps_operon Using operations on groups
62 ## @defgroup l2_grps_delete Deleting Groups
65 ## @defgroup l1_modifying Modifying meshes
67 ## @defgroup l2_modif_add Adding nodes and elements
68 ## @defgroup l2_modif_del Removing nodes and elements
69 ## @defgroup l2_modif_edit Modifying nodes and elements
70 ## @defgroup l2_modif_renumber Renumbering nodes and elements
71 ## @defgroup l2_modif_trsf Transforming meshes (Translation, Rotation, Symmetry, Sewing, Merging)
72 ## @defgroup l2_modif_unitetri Uniting triangles
73 ## @defgroup l2_modif_cutquadr Cutting elements
74 ## @defgroup l2_modif_changori Changing orientation of elements
75 ## @defgroup l2_modif_smooth Smoothing
76 ## @defgroup l2_modif_extrurev Extrusion and Revolution
77 ## @defgroup l2_modif_tofromqu Convert to/from Quadratic Mesh
78 ## @defgroup l2_modif_duplicat Duplication of nodes and elements (to emulate cracks)
81 ## @defgroup l1_measurements Measurements
84 from salome.geom import geomBuilder
86 import SMESH # This is necessary for back compatibility
87 import omniORB # back compatibility
88 SMESH.MED_V2_1 = omniORB.EnumItem("MED_V2_1", 0) # back compatibility
89 SMESH.MED_V2_2 = omniORB.EnumItem("MED_V2_2", 1) # back compatibility
92 from salome.smesh.smesh_algorithm import Mesh_Algorithm
98 ## Private class used to workaround a problem that sometimes isinstance(m, Mesh) returns False
100 class MeshMeta(type):
101 def __instancecheck__(cls, inst):
102 """Implement isinstance(inst, cls)."""
103 return any(cls.__subclasscheck__(c)
104 for c in {type(inst), inst.__class__})
106 def __subclasscheck__(cls, sub):
107 """Implement issubclass(sub, cls)."""
108 return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
110 ## @addtogroup l1_auxiliary
113 ## Convert an angle from degrees to radians
114 def DegreesToRadians(AngleInDegrees):
116 return AngleInDegrees * pi / 180.0
118 import salome_notebook
119 notebook = salome_notebook.notebook
120 # Salome notebook variable separator
123 ## Return list of variable values from salome notebook.
124 # The last argument, if is callable, is used to modify values got from notebook
125 def ParseParameters(*args):
130 if args and callable( args[-1] ):
131 args, varModifFun = args[:-1], args[-1]
132 for parameter in args:
134 Parameters += str(parameter) + var_separator
136 if isinstance(parameter,str):
137 # check if there is an inexistent variable name
138 if not notebook.isVariable(parameter):
139 raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
140 parameter = notebook.get(parameter)
143 parameter = varModifFun(parameter)
146 Result.append(parameter)
149 Parameters = Parameters[:-1]
150 Result.append( Parameters )
151 Result.append( hasVariables )
154 ## Parse parameters while converting variables to radians
155 def ParseAngles(*args):
156 return ParseParameters( *( args + (DegreesToRadians, )))
158 ## Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
159 # Parameters are stored in PointStruct.parameters attribute
160 def __initPointStruct(point,*args):
161 point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
163 SMESH.PointStruct.__init__ = __initPointStruct
165 ## Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
166 # Parameters are stored in AxisStruct.parameters attribute
167 def __initAxisStruct(ax,*args):
170 "Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args ))
171 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
173 SMESH.AxisStruct.__init__ = __initAxisStruct
175 smeshPrecisionConfusion = 1.e-07
176 ## Compare real values using smeshPrecisionConfusion as tolerance
177 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
178 if abs(val1 - val2) < tol:
184 ## Return object name
188 if isinstance(obj, SALOMEDS._objref_SObject):
192 ior = salome.orb.object_to_string(obj)
197 studies = salome.myStudyManager.GetOpenStudies()
198 for sname in studies:
199 s = salome.myStudyManager.GetStudyByName(sname)
201 sobj = s.FindObjectIOR(ior)
202 if not sobj: continue
203 return sobj.GetName()
204 if hasattr(obj, "GetName"):
205 # unknown CORBA object, having GetName() method
208 # unknown CORBA object, no GetName() method
211 if hasattr(obj, "GetName"):
212 # unknown non-CORBA object, having GetName() method
215 raise RuntimeError, "Null or invalid object"
217 ## Print error message if a hypothesis was not assigned.
218 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
220 hypType = "algorithm"
222 hypType = "hypothesis"
225 if hasattr( status, "__getitem__" ):
226 status,reason = status[0],status[1]
227 if status == HYP_UNKNOWN_FATAL :
228 reason = "for unknown reason"
229 elif status == HYP_INCOMPATIBLE :
230 reason = "this hypothesis mismatches the algorithm"
231 elif status == HYP_NOTCONFORM :
232 reason = "a non-conform mesh would be built"
233 elif status == HYP_ALREADY_EXIST :
234 if isAlgo: return # it does not influence anything
235 reason = hypType + " of the same dimension is already assigned to this shape"
236 elif status == HYP_BAD_DIM :
237 reason = hypType + " mismatches the shape"
238 elif status == HYP_CONCURENT :
239 reason = "there are concurrent hypotheses on sub-shapes"
240 elif status == HYP_BAD_SUBSHAPE :
241 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
242 elif status == HYP_BAD_GEOMETRY:
243 reason = "the algorithm is not applicable to this geometry"
244 elif status == HYP_HIDDEN_ALGO:
245 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
246 elif status == HYP_HIDING_ALGO:
247 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
248 elif status == HYP_NEED_SHAPE:
249 reason = "algorithm can't work without shape"
250 elif status == HYP_INCOMPAT_HYPS:
256 where = '"%s"' % geomName
258 meshName = GetName( mesh )
259 if meshName and meshName != NO_NAME:
260 where = '"%s" shape in "%s" mesh ' % ( geomName, meshName )
261 if status < HYP_UNKNOWN_FATAL and where:
262 print '"%s" was assigned to %s but %s' %( hypName, where, reason )
264 print '"%s" was not assigned to %s : %s' %( hypName, where, reason )
266 print '"%s" was not assigned : %s' %( hypName, reason )
269 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
270 def AssureGeomPublished(mesh, geom, name=''):
271 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
273 if not geom.GetStudyEntry() and \
274 mesh.smeshpyD.GetCurrentStudy():
276 studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
277 if studyID != mesh.geompyD.myStudyId:
278 mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
280 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
281 # for all groups SubShapeName() return "Compound_-1"
282 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
284 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
286 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
289 ## Return the first vertex of a geometrical edge by ignoring orientation
290 def FirstVertexOnCurve(mesh, edge):
291 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
293 raise TypeError, "Given object has no vertices"
294 if len( vv ) == 1: return vv[0]
295 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
296 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
297 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
298 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
301 dist1 += abs( xyz[i] - xyz1[i] )
302 dist2 += abs( xyz[i] - xyz2[i] )
308 # end of l1_auxiliary
312 # Warning: smeshInst is a singleton
318 ## This class allows to create, load or manipulate meshes.
319 # It has a set of methods to create, load or copy meshes, to combine several meshes, etc.
320 # It also has methods to get infos and measure meshes.
321 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
323 # MirrorType enumeration
324 POINT = SMESH_MeshEditor.POINT
325 AXIS = SMESH_MeshEditor.AXIS
326 PLANE = SMESH_MeshEditor.PLANE
328 # Smooth_Method enumeration
329 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
330 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
332 PrecisionConfusion = smeshPrecisionConfusion
334 # TopAbs_State enumeration
335 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
337 # Methods of splitting a hexahedron into tetrahedra
338 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
344 #print "==== __new__", engine, smeshInst, doLcc
346 if smeshInst is None:
347 # smesh engine is either retrieved from engine, or created
349 # Following test avoids a recursive loop
351 if smeshInst is not None:
352 # smesh engine not created: existing engine found
356 # FindOrLoadComponent called:
357 # 1. CORBA resolution of server
358 # 2. the __new__ method is called again
359 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
360 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
362 # FindOrLoadComponent not called
363 if smeshInst is None:
364 # smeshBuilder instance is created from lcc.FindOrLoadComponent
365 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
366 smeshInst = super(smeshBuilder,cls).__new__(cls)
368 # smesh engine not created: existing engine found
369 #print "==== existing ", engine, smeshInst, doLcc
371 #print "====1 ", smeshInst
374 #print "====2 ", smeshInst
379 #print "--------------- smeshbuilder __init__ ---", created
382 SMESH._objref_SMESH_Gen.__init__(self)
384 ## Dump component to the Python script
385 # This method overrides IDL function to allow default values for the parameters.
386 # @ingroup l1_auxiliary
387 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
388 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
390 ## Set mode of DumpPython(), \a historical or \a snapshot.
391 # In the \a historical mode, the Python Dump script includes all commands
392 # performed by SMESH engine. In the \a snapshot mode, commands
393 # relating to objects removed from the Study are excluded from the script
394 # as well as commands not influencing the current state of meshes
395 # @ingroup l1_auxiliary
396 def SetDumpPythonHistorical(self, isHistorical):
397 if isHistorical: val = "true"
399 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
401 ## Set the current study and Geometry component
402 # @ingroup l1_auxiliary
403 def init_smesh(self,theStudy,geompyD = None):
405 self.SetCurrentStudy(theStudy,geompyD)
408 notebook.myStudy = theStudy
410 ## Create a mesh. This can be either an empty mesh, possibly having an underlying geometry,
411 # or a mesh wrapping a CORBA mesh given as a parameter.
412 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
413 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
414 # (2) a Geometrical object for meshing or
416 # @param name the name for the new mesh.
417 # @return an instance of Mesh class.
418 # @ingroup l2_construct
419 def Mesh(self, obj=0, name=0):
420 if isinstance(obj,str):
422 return Mesh(self,self.geompyD,obj,name)
424 ## Return a long value from enumeration
425 # @ingroup l1_auxiliary
426 def EnumToLong(self,theItem):
429 ## Return a string representation of the color.
430 # To be used with filters.
431 # @param c color value (SALOMEDS.Color)
432 # @ingroup l1_auxiliary
433 def ColorToString(self,c):
435 if isinstance(c, SALOMEDS.Color):
436 val = "%s;%s;%s" % (c.R, c.G, c.B)
437 elif isinstance(c, str):
440 raise ValueError, "Color value should be of string or SALOMEDS.Color type"
443 ## Get PointStruct from vertex
444 # @param theVertex a GEOM object(vertex)
445 # @return SMESH.PointStruct
446 # @ingroup l1_auxiliary
447 def GetPointStruct(self,theVertex):
448 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
449 return PointStruct(x,y,z)
451 ## Get DirStruct from vector
452 # @param theVector a GEOM object(vector)
453 # @return SMESH.DirStruct
454 # @ingroup l1_auxiliary
455 def GetDirStruct(self,theVector):
456 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
457 if(len(vertices) != 2):
458 print "Error: vector object is incorrect."
460 p1 = self.geompyD.PointCoordinates(vertices[0])
461 p2 = self.geompyD.PointCoordinates(vertices[1])
462 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
463 dirst = DirStruct(pnt)
466 ## Make DirStruct from a triplet
467 # @param x,y,z vector components
468 # @return SMESH.DirStruct
469 # @ingroup l1_auxiliary
470 def MakeDirStruct(self,x,y,z):
471 pnt = PointStruct(x,y,z)
472 return DirStruct(pnt)
474 ## Get AxisStruct from object
475 # @param theObj a GEOM object (line or plane)
476 # @return SMESH.AxisStruct
477 # @ingroup l1_auxiliary
478 def GetAxisStruct(self,theObj):
480 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
483 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
484 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
485 vertex1 = self.geompyD.PointCoordinates(vertex1)
486 vertex2 = self.geompyD.PointCoordinates(vertex2)
487 vertex3 = self.geompyD.PointCoordinates(vertex3)
488 vertex4 = self.geompyD.PointCoordinates(vertex4)
489 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
490 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
491 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] ]
492 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
493 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
494 elif len(edges) == 1:
495 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
496 p1 = self.geompyD.PointCoordinates( vertex1 )
497 p2 = self.geompyD.PointCoordinates( vertex2 )
498 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
499 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
500 elif theObj.GetShapeType() == GEOM.VERTEX:
501 x,y,z = self.geompyD.PointCoordinates( theObj )
502 axis = AxisStruct( x,y,z, 1,0,0,)
503 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
506 # From SMESH_Gen interface:
507 # ------------------------
509 ## Set the given name to the object
510 # @param obj the object to rename
511 # @param name a new object name
512 # @ingroup l1_auxiliary
513 def SetName(self, obj, name):
514 if isinstance( obj, Mesh ):
516 elif isinstance( obj, Mesh_Algorithm ):
517 obj = obj.GetAlgorithm()
518 ior = salome.orb.object_to_string(obj)
519 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
521 ## Set the current mode
522 # @ingroup l1_auxiliary
523 def SetEmbeddedMode( self,theMode ):
524 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
526 ## Get the current mode
527 # @ingroup l1_auxiliary
528 def IsEmbeddedMode(self):
529 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
531 ## Set the current study. Calling SetCurrentStudy( None ) allows to
532 # switch OFF automatic pubilishing in the Study of mesh objects.
533 # @ingroup l1_auxiliary
534 def SetCurrentStudy( self, theStudy, geompyD = None ):
536 from salome.geom import geomBuilder
537 geompyD = geomBuilder.geom
540 self.SetGeomEngine(geompyD)
541 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
544 notebook = salome_notebook.NoteBook( theStudy )
546 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
548 sb = theStudy.NewBuilder()
549 sc = theStudy.FindComponent("SMESH")
550 if sc: sb.LoadWith(sc, self)
554 ## Get the current study
555 # @ingroup l1_auxiliary
556 def GetCurrentStudy(self):
557 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
559 ## Create a Mesh object importing data from the given UNV file
560 # @return an instance of Mesh class
562 def CreateMeshesFromUNV( self,theFileName ):
563 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
564 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
567 ## Create a Mesh object(s) importing data from the given MED file
568 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
570 def CreateMeshesFromMED( self,theFileName ):
571 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
572 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
573 return aMeshes, aStatus
575 ## Create a Mesh object(s) importing data from the given SAUV file
576 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
578 def CreateMeshesFromSAUV( self,theFileName ):
579 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
580 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
581 return aMeshes, aStatus
583 ## Create a Mesh object importing data from the given STL file
584 # @return an instance of Mesh class
586 def CreateMeshesFromSTL( self, theFileName ):
587 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
588 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
591 ## Create Mesh objects importing data from the given CGNS file
592 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
594 def CreateMeshesFromCGNS( self, theFileName ):
595 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
596 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
597 return aMeshes, aStatus
599 ## Create a Mesh object importing data from the given GMF file.
600 # GMF files must have .mesh extension for the ASCII format and .meshb for
602 # @return [ an instance of Mesh class, SMESH.ComputeError ]
604 def CreateMeshesFromGMF( self, theFileName ):
605 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
608 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
609 return Mesh(self, self.geompyD, aSmeshMesh), error
611 ## Concatenate the given meshes into one mesh. All groups of input meshes will be
612 # present in the new mesh.
613 # @param meshes the meshes, sub-meshes and groups to combine into one mesh
614 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
615 # @param mergeNodesAndElements if true, equal nodes and elements are merged
616 # @param mergeTolerance tolerance for merging nodes
617 # @param allGroups forces creation of groups corresponding to every input mesh
618 # @param name name of a new mesh
619 # @return an instance of Mesh class
620 # @ingroup l1_creating
621 def Concatenate( self, meshes, uniteIdenticalGroups,
622 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
624 if not meshes: return None
625 for i,m in enumerate(meshes):
626 if isinstance(m, Mesh):
627 meshes[i] = m.GetMesh()
628 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
629 meshes[0].SetParameters(Parameters)
631 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
632 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
634 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
635 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
636 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
639 ## Create a mesh by copying a part of another mesh.
640 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
641 # to copy nodes or elements not contained in any mesh object,
642 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
643 # @param meshName a name of the new mesh
644 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
645 # @param toKeepIDs to preserve order of the copied elements or not
646 # @return an instance of Mesh class
647 # @ingroup l1_creating
648 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
649 if (isinstance( meshPart, Mesh )):
650 meshPart = meshPart.GetMesh()
651 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
652 return Mesh(self, self.geompyD, mesh)
654 ## Return IDs of sub-shapes
655 # @return the list of integer values
656 # @ingroup l1_auxiliary
657 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
658 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
660 ## Create a pattern mapper.
661 # @return an instance of SMESH_Pattern
663 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
664 # @ingroup l1_modifying
665 def GetPattern(self):
666 return SMESH._objref_SMESH_Gen.GetPattern(self)
668 ## Set number of segments per diagonal of boundary box of geometry, by which
669 # default segment length of appropriate 1D hypotheses is defined in GUI.
670 # Default value is 10.
671 # @ingroup l1_auxiliary
672 def SetBoundaryBoxSegmentation(self, nbSegments):
673 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
675 # Filtering. Auxiliary functions:
676 # ------------------------------
678 ## Create an empty criterion
679 # @return SMESH.Filter.Criterion
680 # @ingroup l1_controls
681 def GetEmptyCriterion(self):
682 Type = self.EnumToLong(FT_Undefined)
683 Compare = self.EnumToLong(FT_Undefined)
687 UnaryOp = self.EnumToLong(FT_Undefined)
688 BinaryOp = self.EnumToLong(FT_Undefined)
691 Precision = -1 ##@1e-07
692 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
693 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
695 ## Create a criterion by the given parameters
696 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
697 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
698 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
699 # Type SMESH.FunctorType._items in the Python Console to see all values.
700 # Note that the items starting from FT_LessThan are not suitable for CritType.
701 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
702 # @param Threshold the threshold value (range of ids as string, shape, numeric)
703 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
704 # @param BinaryOp a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or
706 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
707 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
708 # @return SMESH.Filter.Criterion
710 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
711 # @ingroup l1_controls
712 def GetCriterion(self,elementType,
714 Compare = FT_EqualTo,
716 UnaryOp=FT_Undefined,
717 BinaryOp=FT_Undefined,
719 if not CritType in SMESH.FunctorType._items:
720 raise TypeError, "CritType should be of SMESH.FunctorType"
721 aCriterion = self.GetEmptyCriterion()
722 aCriterion.TypeOfElement = elementType
723 aCriterion.Type = self.EnumToLong(CritType)
724 aCriterion.Tolerance = Tolerance
726 aThreshold = Threshold
728 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
729 aCriterion.Compare = self.EnumToLong(Compare)
730 elif Compare == "=" or Compare == "==":
731 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
733 aCriterion.Compare = self.EnumToLong(FT_LessThan)
735 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
736 elif Compare != FT_Undefined:
737 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
740 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
741 FT_BelongToCylinder, FT_LyingOnGeom]:
742 # Check that Threshold is GEOM object
743 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
744 aCriterion.ThresholdStr = GetName(aThreshold)
745 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
746 if not aCriterion.ThresholdID:
747 name = aCriterion.ThresholdStr
749 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
750 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
751 # or a name of GEOM object
752 elif isinstance( aThreshold, str ):
753 aCriterion.ThresholdStr = aThreshold
755 raise TypeError, "The Threshold should be a shape."
756 if isinstance(UnaryOp,float):
757 aCriterion.Tolerance = UnaryOp
758 UnaryOp = FT_Undefined
760 elif CritType == FT_BelongToMeshGroup:
761 # Check that Threshold is a group
762 if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
763 if aThreshold.GetType() != elementType:
764 raise ValueError, "Group type mismatches Element type"
765 aCriterion.ThresholdStr = aThreshold.GetName()
766 aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
767 study = self.GetCurrentStudy()
769 so = study.FindObjectIOR( aCriterion.ThresholdID )
773 aCriterion.ThresholdID = entry
775 raise TypeError, "The Threshold should be a Mesh Group"
776 elif CritType == FT_RangeOfIds:
777 # Check that Threshold is string
778 if isinstance(aThreshold, str):
779 aCriterion.ThresholdStr = aThreshold
781 raise TypeError, "The Threshold should be a string."
782 elif CritType == FT_CoplanarFaces:
783 # Check the Threshold
784 if isinstance(aThreshold, int):
785 aCriterion.ThresholdID = str(aThreshold)
786 elif isinstance(aThreshold, str):
789 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
790 aCriterion.ThresholdID = aThreshold
793 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
794 elif CritType == FT_ConnectedElements:
795 # Check the Threshold
796 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
797 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
798 if not aCriterion.ThresholdID:
799 name = aThreshold.GetName()
801 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
802 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
803 elif isinstance(aThreshold, int): # node id
804 aCriterion.Threshold = aThreshold
805 elif isinstance(aThreshold, list): # 3 point coordinates
806 if len( aThreshold ) < 3:
807 raise ValueError, "too few point coordinates, must be 3"
808 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
809 elif isinstance(aThreshold, str):
810 if aThreshold.isdigit():
811 aCriterion.Threshold = aThreshold # node id
813 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
816 "The Threshold should either a VERTEX, or a node ID, "\
817 "or a list of point coordinates and not '%s'"%aThreshold
818 elif CritType == FT_ElemGeomType:
819 # Check the Threshold
821 aCriterion.Threshold = self.EnumToLong(aThreshold)
822 assert( aThreshold in SMESH.GeometryType._items )
824 if isinstance(aThreshold, int):
825 aCriterion.Threshold = aThreshold
827 raise TypeError, "The Threshold should be an integer or SMESH.GeometryType."
830 elif CritType == FT_EntityType:
831 # Check the Threshold
833 aCriterion.Threshold = self.EnumToLong(aThreshold)
834 assert( aThreshold in SMESH.EntityType._items )
836 if isinstance(aThreshold, int):
837 aCriterion.Threshold = aThreshold
839 raise TypeError, "The Threshold should be an integer or SMESH.EntityType."
843 elif CritType == FT_GroupColor:
844 # Check the Threshold
846 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
848 raise TypeError, "The threshold value should be of SALOMEDS.Color type"
850 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
851 FT_LinearOrQuadratic, FT_BadOrientedVolume,
852 FT_BareBorderFace, FT_BareBorderVolume,
853 FT_OverConstrainedFace, FT_OverConstrainedVolume,
854 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
855 # At this point the Threshold is unnecessary
856 if aThreshold == FT_LogicalNOT:
857 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
858 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
859 aCriterion.BinaryOp = aThreshold
863 aThreshold = float(aThreshold)
864 aCriterion.Threshold = aThreshold
866 raise TypeError, "The Threshold should be a number."
869 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
870 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
872 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
873 aCriterion.BinaryOp = self.EnumToLong(Threshold)
875 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
876 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
878 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
879 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
883 ## Create a filter with the given parameters
884 # @param elementType the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
885 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
886 # Type SMESH.FunctorType._items in the Python Console to see all values.
887 # Note that the items starting from FT_LessThan are not suitable for CritType.
888 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
889 # @param Threshold the threshold value (range of ids as string, shape, numeric)
890 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
891 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
892 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
893 # @param mesh the mesh to initialize the filter with
894 # @return SMESH_Filter
896 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
897 # @ingroup l1_controls
898 def GetFilter(self,elementType,
899 CritType=FT_Undefined,
902 UnaryOp=FT_Undefined,
905 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
906 aFilterMgr = self.CreateFilterManager()
907 aFilter = aFilterMgr.CreateFilter()
909 aCriteria.append(aCriterion)
910 aFilter.SetCriteria(aCriteria)
912 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
913 else : aFilter.SetMesh( mesh )
914 aFilterMgr.UnRegister()
917 ## Create a filter from criteria
918 # @param criteria a list of criteria
919 # @param binOp binary operator used when binary operator of criteria is undefined
920 # @return SMESH_Filter
922 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
923 # @ingroup l1_controls
924 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
925 for i in range( len( criteria ) - 1 ):
926 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
927 criteria[i].BinaryOp = self.EnumToLong( binOp )
928 aFilterMgr = self.CreateFilterManager()
929 aFilter = aFilterMgr.CreateFilter()
930 aFilter.SetCriteria(criteria)
931 aFilterMgr.UnRegister()
934 ## Create a numerical functor by its type
935 # @param theCriterion functor type - an item of SMESH.FunctorType enumeration.
936 # Type SMESH.FunctorType._items in the Python Console to see all items.
937 # Note that not all items correspond to numerical functors.
938 # @return SMESH_NumericalFunctor
939 # @ingroup l1_controls
940 def GetFunctor(self,theCriterion):
941 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
943 aFilterMgr = self.CreateFilterManager()
945 if theCriterion == FT_AspectRatio:
946 functor = aFilterMgr.CreateAspectRatio()
947 elif theCriterion == FT_AspectRatio3D:
948 functor = aFilterMgr.CreateAspectRatio3D()
949 elif theCriterion == FT_Warping:
950 functor = aFilterMgr.CreateWarping()
951 elif theCriterion == FT_MinimumAngle:
952 functor = aFilterMgr.CreateMinimumAngle()
953 elif theCriterion == FT_Taper:
954 functor = aFilterMgr.CreateTaper()
955 elif theCriterion == FT_Skew:
956 functor = aFilterMgr.CreateSkew()
957 elif theCriterion == FT_Area:
958 functor = aFilterMgr.CreateArea()
959 elif theCriterion == FT_Volume3D:
960 functor = aFilterMgr.CreateVolume3D()
961 elif theCriterion == FT_MaxElementLength2D:
962 functor = aFilterMgr.CreateMaxElementLength2D()
963 elif theCriterion == FT_MaxElementLength3D:
964 functor = aFilterMgr.CreateMaxElementLength3D()
965 elif theCriterion == FT_MultiConnection:
966 functor = aFilterMgr.CreateMultiConnection()
967 elif theCriterion == FT_MultiConnection2D:
968 functor = aFilterMgr.CreateMultiConnection2D()
969 elif theCriterion == FT_Length:
970 functor = aFilterMgr.CreateLength()
971 elif theCriterion == FT_Length2D:
972 functor = aFilterMgr.CreateLength2D()
973 elif theCriterion == FT_NodeConnectivityNumber:
974 functor = aFilterMgr.CreateNodeConnectivityNumber()
975 elif theCriterion == FT_BallDiameter:
976 functor = aFilterMgr.CreateBallDiameter()
978 print "Error: given parameter is not numerical functor type."
979 aFilterMgr.UnRegister()
983 # @param theHType mesh hypothesis type (string)
984 # @param theLibName mesh plug-in library name
985 # @return created hypothesis instance
986 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
987 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
989 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
992 # wrap hypothesis methods
993 #print "HYPOTHESIS", theHType
994 for meth_name in dir( hyp.__class__ ):
995 if not meth_name.startswith("Get") and \
996 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
997 method = getattr ( hyp.__class__, meth_name )
999 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
1003 ## Get the mesh statistic
1004 # @return dictionary "element type" - "count of elements"
1005 # @ingroup l1_meshinfo
1006 def GetMeshInfo(self, obj):
1007 if isinstance( obj, Mesh ):
1010 if hasattr(obj, "GetMeshInfo"):
1011 values = obj.GetMeshInfo()
1012 for i in range(SMESH.Entity_Last._v):
1013 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1017 ## Get minimum distance between two objects
1019 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1020 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1022 # @param src1 first source object
1023 # @param src2 second source object
1024 # @param id1 node/element id from the first source
1025 # @param id2 node/element id from the second (or first) source
1026 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1027 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1028 # @return minimum distance value
1029 # @sa GetMinDistance()
1030 # @ingroup l1_measurements
1031 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1032 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1036 result = result.value
1039 ## Get measure structure specifying minimum distance data between two objects
1041 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1042 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1044 # @param src1 first source object
1045 # @param src2 second source object
1046 # @param id1 node/element id from the first source
1047 # @param id2 node/element id from the second (or first) source
1048 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1049 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1050 # @return Measure structure or None if input data is invalid
1052 # @ingroup l1_measurements
1053 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1054 if isinstance(src1, Mesh): src1 = src1.mesh
1055 if isinstance(src2, Mesh): src2 = src2.mesh
1056 if src2 is None and id2 != 0: src2 = src1
1057 if not hasattr(src1, "_narrow"): return None
1058 src1 = src1._narrow(SMESH.SMESH_IDSource)
1059 if not src1: return None
1060 unRegister = genObjUnRegister()
1063 e = m.GetMeshEditor()
1065 src1 = e.MakeIDSource([id1], SMESH.FACE)
1067 src1 = e.MakeIDSource([id1], SMESH.NODE)
1068 unRegister.set( src1 )
1070 if hasattr(src2, "_narrow"):
1071 src2 = src2._narrow(SMESH.SMESH_IDSource)
1072 if src2 and id2 != 0:
1074 e = m.GetMeshEditor()
1076 src2 = e.MakeIDSource([id2], SMESH.FACE)
1078 src2 = e.MakeIDSource([id2], SMESH.NODE)
1079 unRegister.set( src2 )
1082 aMeasurements = self.CreateMeasurements()
1083 unRegister.set( aMeasurements )
1084 result = aMeasurements.MinDistance(src1, src2)
1087 ## Get bounding box of the specified object(s)
1088 # @param objects single source object or list of source objects
1089 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1090 # @sa GetBoundingBox()
1091 # @ingroup l1_measurements
1092 def BoundingBox(self, objects):
1093 result = self.GetBoundingBox(objects)
1097 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1100 ## Get measure structure specifying bounding box data of the specified object(s)
1101 # @param objects single source object or list of source objects
1102 # @return Measure structure
1104 # @ingroup l1_measurements
1105 def GetBoundingBox(self, objects):
1106 if isinstance(objects, tuple):
1107 objects = list(objects)
1108 if not isinstance(objects, list):
1112 if isinstance(o, Mesh):
1113 srclist.append(o.mesh)
1114 elif hasattr(o, "_narrow"):
1115 src = o._narrow(SMESH.SMESH_IDSource)
1116 if src: srclist.append(src)
1119 aMeasurements = self.CreateMeasurements()
1120 result = aMeasurements.BoundingBox(srclist)
1121 aMeasurements.UnRegister()
1124 ## Get sum of lengths of all 1D elements in the mesh object.
1125 # @param obj mesh, submesh or group
1126 # @return sum of lengths of all 1D elements
1127 # @ingroup l1_measurements
1128 def GetLength(self, obj):
1129 if isinstance(obj, Mesh): obj = obj.mesh
1130 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1131 aMeasurements = self.CreateMeasurements()
1132 value = aMeasurements.Length(obj)
1133 aMeasurements.UnRegister()
1136 ## Get sum of areas of all 2D elements in the mesh object.
1137 # @param obj mesh, submesh or group
1138 # @return sum of areas of all 2D elements
1139 # @ingroup l1_measurements
1140 def GetArea(self, obj):
1141 if isinstance(obj, Mesh): obj = obj.mesh
1142 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1143 aMeasurements = self.CreateMeasurements()
1144 value = aMeasurements.Area(obj)
1145 aMeasurements.UnRegister()
1148 ## Get sum of volumes of all 3D elements in the mesh object.
1149 # @param obj mesh, submesh or group
1150 # @return sum of volumes of all 3D elements
1151 # @ingroup l1_measurements
1152 def GetVolume(self, obj):
1153 if isinstance(obj, Mesh): obj = obj.mesh
1154 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1155 aMeasurements = self.CreateMeasurements()
1156 value = aMeasurements.Volume(obj)
1157 aMeasurements.UnRegister()
1160 pass # end of class smeshBuilder
1163 #Registering the new proxy for SMESH_Gen
1164 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1166 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1167 # interface to create or load meshes.
1172 # salome.salome_init()
1173 # from salome.smesh import smeshBuilder
1174 # smesh = smeshBuilder.New(salome.myStudy)
1176 # @param study SALOME study, generally obtained by salome.myStudy.
1177 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1178 # @return smeshBuilder instance
1180 def New( study, instance=None):
1182 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1183 interface to create or load meshes.
1187 salome.salome_init()
1188 from salome.smesh import smeshBuilder
1189 smesh = smeshBuilder.New(salome.myStudy)
1192 study SALOME study, generally obtained by salome.myStudy.
1193 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1195 smeshBuilder instance
1203 smeshInst = smeshBuilder()
1204 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1205 smeshInst.init_smesh(study)
1209 # Public class: Mesh
1210 # ==================
1212 ## This class allows defining and managing a mesh.
1213 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1214 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1215 # new nodes and elements and by changing the existing entities), to get information
1216 # about a mesh and to export a mesh in different formats.
1218 __metaclass__ = MeshMeta
1226 # Create a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1227 # sets the GUI name of this mesh to \a name.
1228 # @param smeshpyD an instance of smeshBuilder class
1229 # @param geompyD an instance of geomBuilder class
1230 # @param obj Shape to be meshed or SMESH_Mesh object
1231 # @param name Study name of the mesh
1232 # @ingroup l2_construct
1233 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1234 self.smeshpyD=smeshpyD
1235 self.geompyD=geompyD
1240 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1243 # publish geom of mesh (issue 0021122)
1244 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1246 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1247 if studyID != geompyD.myStudyId:
1248 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1251 geo_name = name + " shape"
1253 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1254 geompyD.addToStudy( self.geom, geo_name )
1255 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1257 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1260 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1262 self.smeshpyD.SetName(self.mesh, name)
1264 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1267 self.geom = self.mesh.GetShapeToMesh()
1269 self.editor = self.mesh.GetMeshEditor()
1270 self.functors = [None] * SMESH.FT_Undefined._v
1272 # set self to algoCreator's
1273 for attrName in dir(self):
1274 attr = getattr( self, attrName )
1275 if isinstance( attr, algoCreator ):
1276 setattr( self, attrName, attr.copy( self ))
1281 ## Destructor. Clean-up resources
1284 #self.mesh.UnRegister()
1288 ## Initialize the Mesh object from an instance of SMESH_Mesh interface
1289 # @param theMesh a SMESH_Mesh object
1290 # @ingroup l2_construct
1291 def SetMesh(self, theMesh):
1292 # do not call Register() as this prevents mesh servant deletion at closing study
1293 #if self.mesh: self.mesh.UnRegister()
1296 #self.mesh.Register()
1297 self.geom = self.mesh.GetShapeToMesh()
1300 ## Return the mesh, that is an instance of SMESH_Mesh interface
1301 # @return a SMESH_Mesh object
1302 # @ingroup l2_construct
1306 ## Get the name of the mesh
1307 # @return the name of the mesh as a string
1308 # @ingroup l2_construct
1310 name = GetName(self.GetMesh())
1313 ## Set a name to the mesh
1314 # @param name a new name of the mesh
1315 # @ingroup l2_construct
1316 def SetName(self, name):
1317 self.smeshpyD.SetName(self.GetMesh(), name)
1319 ## Get a sub-mesh object associated to a \a geom geometrical object.
1320 # @param geom a geometrical object (shape)
1321 # @param name a name for the sub-mesh in the Object Browser
1322 # @return an object of type SMESH.SMESH_subMesh, representing a part of mesh,
1323 # which lies on the given shape
1325 # The sub-mesh object gives access to the IDs of nodes and elements.
1326 # The sub-mesh object has the following methods:
1327 # - SMESH.SMESH_subMesh.GetNumberOfElements()
1328 # - SMESH.SMESH_subMesh.GetNumberOfNodes( all )
1329 # - SMESH.SMESH_subMesh.GetElementsId()
1330 # - SMESH.SMESH_subMesh.GetElementsByType( ElementType )
1331 # - SMESH.SMESH_subMesh.GetNodesId()
1332 # - SMESH.SMESH_subMesh.GetSubShape()
1333 # - SMESH.SMESH_subMesh.GetFather()
1334 # - SMESH.SMESH_subMesh.GetId()
1335 # @note A sub-mesh is implicitly created when a sub-shape is specified at
1336 # creating an algorithm, for example: <code>algo1D = mesh.Segment(geom=Edge_1) </code>
1337 # creates a sub-mesh on @c Edge_1 and assign Wire Discretization algorithm to it.
1338 # The created sub-mesh can be retrieved from the algorithm:
1339 # <code>submesh = algo1D.GetSubMesh()</code>
1340 # @ingroup l2_submeshes
1341 def GetSubMesh(self, geom, name):
1342 AssureGeomPublished( self, geom, name )
1343 submesh = self.mesh.GetSubMesh( geom, name )
1346 ## Return the shape associated to the mesh
1347 # @return a GEOM_Object
1348 # @ingroup l2_construct
1352 ## Associate the given shape to the mesh (entails the recreation of the mesh)
1353 # @param geom the shape to be meshed (GEOM_Object)
1354 # @ingroup l2_construct
1355 def SetShape(self, geom):
1356 self.mesh = self.smeshpyD.CreateMesh(geom)
1358 ## Load mesh from the study after opening the study
1362 ## Return true if the hypotheses are defined well
1363 # @param theSubObject a sub-shape of a mesh shape
1364 # @return True or False
1365 # @ingroup l2_construct
1366 def IsReadyToCompute(self, theSubObject):
1367 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1369 ## Return errors of hypotheses definition.
1370 # The list of errors is empty if everything is OK.
1371 # @param theSubObject a sub-shape of a mesh shape
1372 # @return a list of errors
1373 # @ingroup l2_construct
1374 def GetAlgoState(self, theSubObject):
1375 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1377 ## Return a geometrical object on which the given element was built.
1378 # The returned geometrical object, if not nil, is either found in the
1379 # study or published by this method with the given name
1380 # @param theElementID the id of the mesh element
1381 # @param theGeomName the user-defined name of the geometrical object
1382 # @return GEOM::GEOM_Object instance
1383 # @ingroup l1_meshinfo
1384 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1385 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1387 ## Return the mesh dimension depending on the dimension of the underlying shape
1388 # or, if the mesh is not based on any shape, basing on deimension of elements
1389 # @return mesh dimension as an integer value [0,3]
1390 # @ingroup l1_meshinfo
1391 def MeshDimension(self):
1392 if self.mesh.HasShapeToMesh():
1393 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1394 if len( shells ) > 0 :
1396 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1398 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1403 if self.NbVolumes() > 0: return 3
1404 if self.NbFaces() > 0: return 2
1405 if self.NbEdges() > 0: return 1
1408 ## Evaluate size of prospective mesh on a shape
1409 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1410 # To know predicted number of e.g. edges, inquire it this way
1411 # Evaluate()[ EnumToLong( Entity_Edge )]
1412 # @ingroup l2_construct
1413 def Evaluate(self, geom=0):
1414 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1416 geom = self.mesh.GetShapeToMesh()
1419 return self.smeshpyD.Evaluate(self.mesh, geom)
1422 ## Compute the mesh and return the status of the computation
1423 # @param geom geomtrical shape on which mesh data should be computed
1424 # @param discardModifs if True and the mesh has been edited since
1425 # a last total re-compute and that may prevent successful partial re-compute,
1426 # then the mesh is cleaned before Compute()
1427 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1428 # @return True or False
1429 # @ingroup l2_construct
1430 def Compute(self, geom=0, discardModifs=False, refresh=False):
1431 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1433 geom = self.mesh.GetShapeToMesh()
1438 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1440 ok = self.smeshpyD.Compute(self.mesh, geom)
1441 except SALOME.SALOME_Exception, ex:
1442 print "Mesh computation failed, exception caught:"
1443 print " ", ex.details.text
1446 print "Mesh computation failed, exception caught:"
1447 traceback.print_exc()
1451 # Treat compute errors
1452 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1454 for err in computeErrors:
1455 if self.mesh.HasShapeToMesh():
1456 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1458 stdErrors = ["OK", #COMPERR_OK
1459 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1460 "std::exception", #COMPERR_STD_EXCEPTION
1461 "OCC exception", #COMPERR_OCC_EXCEPTION
1462 "..", #COMPERR_SLM_EXCEPTION
1463 "Unknown exception", #COMPERR_EXCEPTION
1464 "Memory allocation problem", #COMPERR_MEMORY_PB
1465 "Algorithm failed", #COMPERR_ALGO_FAILED
1466 "Unexpected geometry", #COMPERR_BAD_SHAPE
1467 "Warning", #COMPERR_WARNING
1468 "Computation cancelled",#COMPERR_CANCELED
1469 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1471 if err.code < len(stdErrors): errText = stdErrors[err.code]
1473 errText = "code %s" % -err.code
1474 if errText: errText += ". "
1475 errText += err.comment
1476 if allReasons != "":allReasons += "\n"
1478 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1480 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1484 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1486 if err.isGlobalAlgo:
1494 reason = '%s %sD algorithm is missing' % (glob, dim)
1495 elif err.state == HYP_MISSING:
1496 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1497 % (glob, dim, name, dim))
1498 elif err.state == HYP_NOTCONFORM:
1499 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1500 elif err.state == HYP_BAD_PARAMETER:
1501 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1502 % ( glob, dim, name ))
1503 elif err.state == HYP_BAD_GEOMETRY:
1504 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1505 'geometry' % ( glob, dim, name ))
1506 elif err.state == HYP_HIDDEN_ALGO:
1507 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1508 'algorithm of upper dimension generating %sD mesh'
1509 % ( glob, dim, name, glob, dim ))
1511 reason = ("For unknown reason. "
1512 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1514 if allReasons != "":allReasons += "\n"
1515 allReasons += "- " + reason
1517 if not ok or allReasons != "":
1518 msg = '"' + GetName(self.mesh) + '"'
1519 if ok: msg += " has been computed with warnings"
1520 else: msg += " has not been computed"
1521 if allReasons != "": msg += ":"
1526 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1527 if not isinstance( refresh, list): # not a call from subMesh.Compute()
1528 smeshgui = salome.ImportComponentGUI("SMESH")
1529 smeshgui.Init(self.mesh.GetStudyId())
1530 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1531 if refresh: salome.sg.updateObjBrowser(True)
1535 ## Return a list of error messages (SMESH.ComputeError) of the last Compute()
1536 # @ingroup l2_construct
1537 def GetComputeErrors(self, shape=0 ):
1539 shape = self.mesh.GetShapeToMesh()
1540 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1542 ## Return a name of a sub-shape by its ID
1543 # @param subShapeID a unique ID of a sub-shape
1544 # @return a string describing the sub-shape; possible variants:
1545 # - "Face_12" (published sub-shape)
1546 # - FACE #3 (not published sub-shape)
1547 # - sub-shape #3 (invalid sub-shape ID)
1548 # - #3 (error in this function)
1549 # @ingroup l1_auxiliary
1550 def GetSubShapeName(self, subShapeID ):
1551 if not self.mesh.HasShapeToMesh():
1555 mainIOR = salome.orb.object_to_string( self.GetShape() )
1556 for sname in salome.myStudyManager.GetOpenStudies():
1557 s = salome.myStudyManager.GetStudyByName(sname)
1559 mainSO = s.FindObjectIOR(mainIOR)
1560 if not mainSO: continue
1562 shapeText = '"%s"' % mainSO.GetName()
1563 subIt = s.NewChildIterator(mainSO)
1565 subSO = subIt.Value()
1567 obj = subSO.GetObject()
1568 if not obj: continue
1569 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1572 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1575 if ids == subShapeID:
1576 shapeText = '"%s"' % subSO.GetName()
1579 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1581 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1583 shapeText = 'sub-shape #%s' % (subShapeID)
1585 shapeText = "#%s" % (subShapeID)
1588 ## Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1589 # error of an algorithm
1590 # @param publish if @c True, the returned groups will be published in the study
1591 # @return a list of GEOM groups each named after a failed algorithm
1592 # @ingroup l2_construct
1593 def GetFailedShapes(self, publish=False):
1596 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1597 for err in computeErrors:
1598 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1599 if not shape: continue
1600 if err.algoName in algo2shapes:
1601 algo2shapes[ err.algoName ].append( shape )
1603 algo2shapes[ err.algoName ] = [ shape ]
1607 for algoName, shapes in algo2shapes.items():
1609 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1610 otherTypeShapes = []
1612 group = self.geompyD.CreateGroup( self.geom, groupType )
1613 for shape in shapes:
1614 if shape.GetShapeType() == shapes[0].GetShapeType():
1615 sameTypeShapes.append( shape )
1617 otherTypeShapes.append( shape )
1618 self.geompyD.UnionList( group, sameTypeShapes )
1620 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1622 group.SetName( algoName )
1623 groups.append( group )
1624 shapes = otherTypeShapes
1627 for group in groups:
1628 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1631 ## Return sub-mesh objects list in meshing order
1632 # @return list of lists of sub-meshes
1633 # @ingroup l2_construct
1634 def GetMeshOrder(self):
1635 return self.mesh.GetMeshOrder()
1637 ## Set order in which concurrent sub-meshes sould be meshed
1638 # @param submeshes list of lists of sub-meshes
1639 # @ingroup l2_construct
1640 def SetMeshOrder(self, submeshes):
1641 return self.mesh.SetMeshOrder(submeshes)
1643 ## Remove all nodes and elements generated on geometry. Imported elements remain.
1644 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1645 # @ingroup l2_construct
1646 def Clear(self, refresh=False):
1648 if ( salome.sg.hasDesktop() and
1649 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1650 smeshgui = salome.ImportComponentGUI("SMESH")
1651 smeshgui.Init(self.mesh.GetStudyId())
1652 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1653 if refresh: salome.sg.updateObjBrowser(True)
1655 ## Remove all nodes and elements of indicated shape
1656 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1657 # @param geomId the ID of a sub-shape to remove elements on
1658 # @ingroup l2_submeshes
1659 def ClearSubMesh(self, geomId, refresh=False):
1660 self.mesh.ClearSubMesh(geomId)
1661 if salome.sg.hasDesktop():
1662 smeshgui = salome.ImportComponentGUI("SMESH")
1663 smeshgui.Init(self.mesh.GetStudyId())
1664 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1665 if refresh: salome.sg.updateObjBrowser(True)
1667 ## Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1668 # @param fineness [0.0,1.0] defines mesh fineness
1669 # @return True or False
1670 # @ingroup l3_algos_basic
1671 def AutomaticTetrahedralization(self, fineness=0):
1672 dim = self.MeshDimension()
1674 self.RemoveGlobalHypotheses()
1675 self.Segment().AutomaticLength(fineness)
1677 self.Triangle().LengthFromEdges()
1682 return self.Compute()
1684 ## Compute an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1685 # @param fineness [0.0, 1.0] defines mesh fineness
1686 # @return True or False
1687 # @ingroup l3_algos_basic
1688 def AutomaticHexahedralization(self, fineness=0):
1689 dim = self.MeshDimension()
1690 # assign the hypotheses
1691 self.RemoveGlobalHypotheses()
1692 self.Segment().AutomaticLength(fineness)
1699 return self.Compute()
1701 ## Assign a hypothesis
1702 # @param hyp a hypothesis to assign
1703 # @param geom a subhape of mesh geometry
1704 # @return SMESH.Hypothesis_Status
1705 # @ingroup l2_editing
1706 def AddHypothesis(self, hyp, geom=0):
1707 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1708 hyp, geom = geom, hyp
1709 if isinstance( hyp, Mesh_Algorithm ):
1710 hyp = hyp.GetAlgorithm()
1715 geom = self.mesh.GetShapeToMesh()
1718 if self.mesh.HasShapeToMesh():
1719 hyp_type = hyp.GetName()
1720 lib_name = hyp.GetLibName()
1721 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1722 # if checkAll and geom:
1723 # checkAll = geom.GetType() == 37
1725 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1727 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1728 status = self.mesh.AddHypothesis(geom, hyp)
1730 status = HYP_BAD_GEOMETRY,""
1731 hyp_name = GetName( hyp )
1734 geom_name = geom.GetName()
1735 isAlgo = hyp._narrow( SMESH_Algo )
1736 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1739 ## Return True if an algorithm of hypothesis is assigned to a given shape
1740 # @param hyp a hypothesis to check
1741 # @param geom a subhape of mesh geometry
1742 # @return True of False
1743 # @ingroup l2_editing
1744 def IsUsedHypothesis(self, hyp, geom):
1745 if not hyp: # or not geom
1747 if isinstance( hyp, Mesh_Algorithm ):
1748 hyp = hyp.GetAlgorithm()
1750 hyps = self.GetHypothesisList(geom)
1752 if h.GetId() == hyp.GetId():
1756 ## Unassign a hypothesis
1757 # @param hyp a hypothesis to unassign
1758 # @param geom a sub-shape of mesh geometry
1759 # @return SMESH.Hypothesis_Status
1760 # @ingroup l2_editing
1761 def RemoveHypothesis(self, hyp, geom=0):
1764 if isinstance( hyp, Mesh_Algorithm ):
1765 hyp = hyp.GetAlgorithm()
1771 if self.IsUsedHypothesis( hyp, shape ):
1772 return self.mesh.RemoveHypothesis( shape, hyp )
1773 hypName = GetName( hyp )
1774 geoName = GetName( shape )
1775 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1778 ## Get the list of hypotheses added on a geometry
1779 # @param geom a sub-shape of mesh geometry
1780 # @return the sequence of SMESH_Hypothesis
1781 # @ingroup l2_editing
1782 def GetHypothesisList(self, geom):
1783 return self.mesh.GetHypothesisList( geom )
1785 ## Remove all global hypotheses
1786 # @ingroup l2_editing
1787 def RemoveGlobalHypotheses(self):
1788 current_hyps = self.mesh.GetHypothesisList( self.geom )
1789 for hyp in current_hyps:
1790 self.mesh.RemoveHypothesis( self.geom, hyp )
1794 ## Export the mesh in a file in MED format
1795 ## allowing to overwrite the file if it exists or add the exported data to its contents
1796 # @param fileName is the file name
1797 # @param auto_groups boolean parameter for creating/not creating
1798 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1799 # the typical use is auto_groups=False.
1800 # @param overwrite boolean parameter for overwriting/not overwriting the file
1801 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1802 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1803 # - 1D if all mesh nodes lie on OX coordinate axis, or
1804 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1805 # - 3D in the rest cases.<br>
1806 # If @a autoDimension is @c False, the space dimension is always 3.
1807 # @param fields list of GEOM fields defined on the shape to mesh.
1808 # @param geomAssocFields each character of this string means a need to export a
1809 # corresponding field; correspondence between fields and characters is following:
1810 # - 'v' stands for "_vertices _" field;
1811 # - 'e' stands for "_edges _" field;
1812 # - 'f' stands for "_faces _" field;
1813 # - 's' stands for "_solids _" field.
1814 # @ingroup l2_impexp
1815 def ExportMED(self, *args, **kwargs):
1816 # process positional arguments
1817 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
1819 auto_groups = args[1] if len(args) > 1 else False
1820 overwrite = args[2] if len(args) > 2 else True
1821 meshPart = args[3] if len(args) > 3 else None
1822 autoDimension = args[4] if len(args) > 4 else True
1823 fields = args[5] if len(args) > 5 else []
1824 geomAssocFields = args[6] if len(args) > 6 else ''
1825 # process keywords arguments
1826 auto_groups = kwargs.get("auto_groups", auto_groups)
1827 overwrite = kwargs.get("overwrite", overwrite)
1828 meshPart = kwargs.get("meshPart", meshPart)
1829 autoDimension = kwargs.get("autoDimension", autoDimension)
1830 fields = kwargs.get("fields", fields)
1831 geomAssocFields = kwargs.get("geomAssocFields", geomAssocFields)
1832 # invoke engine's function
1833 if meshPart or fields or geomAssocFields:
1834 unRegister = genObjUnRegister()
1835 if isinstance( meshPart, list ):
1836 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1837 unRegister.set( meshPart )
1838 self.mesh.ExportPartToMED( meshPart, fileName, auto_groups, overwrite, autoDimension,
1839 fields, geomAssocFields)
1841 self.mesh.ExportMED(fileName, auto_groups, overwrite, autoDimension)
1843 ## Export the mesh in a file in SAUV format
1844 # @param f is the file name
1845 # @param auto_groups boolean parameter for creating/not creating
1846 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1847 # the typical use is auto_groups=false.
1848 # @ingroup l2_impexp
1849 def ExportSAUV(self, f, auto_groups=0):
1850 self.mesh.ExportSAUV(f, auto_groups)
1852 ## Export the mesh in a file in DAT format
1853 # @param f the file name
1854 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1855 # @ingroup l2_impexp
1856 def ExportDAT(self, f, meshPart=None):
1858 unRegister = genObjUnRegister()
1859 if isinstance( meshPart, list ):
1860 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1861 unRegister.set( meshPart )
1862 self.mesh.ExportPartToDAT( meshPart, f )
1864 self.mesh.ExportDAT(f)
1866 ## Export the mesh in a file in UNV format
1867 # @param f the file name
1868 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1869 # @ingroup l2_impexp
1870 def ExportUNV(self, f, meshPart=None):
1872 unRegister = genObjUnRegister()
1873 if isinstance( meshPart, list ):
1874 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1875 unRegister.set( meshPart )
1876 self.mesh.ExportPartToUNV( meshPart, f )
1878 self.mesh.ExportUNV(f)
1880 ## Export the mesh in a file in STL format
1881 # @param f the file name
1882 # @param ascii defines the file encoding
1883 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1884 # @ingroup l2_impexp
1885 def ExportSTL(self, f, ascii=1, meshPart=None):
1887 unRegister = genObjUnRegister()
1888 if isinstance( meshPart, list ):
1889 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1890 unRegister.set( meshPart )
1891 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1893 self.mesh.ExportSTL(f, ascii)
1895 ## Export the mesh in a file in CGNS format
1896 # @param f is the file name
1897 # @param overwrite boolean parameter for overwriting/not overwriting the file
1898 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1899 # @ingroup l2_impexp
1900 def ExportCGNS(self, f, overwrite=1, 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.ExportCGNS(meshPart, f, overwrite)
1911 ## Export the mesh in a file in GMF format.
1912 # GMF files must have .mesh extension for the ASCII format and .meshb for
1913 # the bynary format. Other extensions are not allowed.
1914 # @param f is the file name
1915 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1916 # @ingroup l2_impexp
1917 def ExportGMF(self, f, meshPart=None):
1918 unRegister = genObjUnRegister()
1919 if isinstance( meshPart, list ):
1920 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1921 unRegister.set( meshPart )
1922 if isinstance( meshPart, Mesh ):
1923 meshPart = meshPart.mesh
1925 meshPart = self.mesh
1926 self.mesh.ExportGMF(meshPart, f, True)
1928 ## Deprecated, used only for compatibility! Please, use ExportMED() method instead.
1929 # Export the mesh in a file in MED format
1930 # allowing to overwrite the file if it exists or add the exported data to its contents
1931 # @param fileName the file name
1932 # @param opt boolean parameter for creating/not creating
1933 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1934 # @param overwrite boolean parameter for overwriting/not overwriting the file
1935 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1936 # - 1D if all mesh nodes lie on OX coordinate axis, or
1937 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1938 # - 3D in the rest cases.<br>
1939 # If @a autoDimension is @c False, the space dimension is always 3.
1940 # @ingroup l2_impexp
1941 def ExportToMED(self, *args, **kwargs):
1942 print "WARNING: ExportToMED() is deprecated, use ExportMED() instead"
1943 # process positional arguments
1944 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
1946 auto_groups = args[1] if len(args) > 1 else False
1947 overwrite = args[2] if len(args) > 2 else True
1948 autoDimension = args[3] if len(args) > 3 else True
1949 # process keywords arguments
1950 auto_groups = kwargs.get("opt", auto_groups) # old keyword name
1951 auto_groups = kwargs.get("auto_groups", auto_groups) # new keyword name
1952 overwrite = kwargs.get("overwrite", overwrite)
1953 autoDimension = kwargs.get("autoDimension", autoDimension)
1954 # invoke engine's function
1955 self.mesh.ExportMED(fileName, auto_groups, overwrite, autoDimension)
1957 ## Deprecated, used only for compatibility! Please, use ExportMED() method instead.
1958 # Export the mesh in a file in MED format
1959 # allowing to overwrite the file if it exists or add the exported data to its contents
1960 # @param fileName the file name
1961 # @param opt boolean parameter for creating/not creating
1962 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1963 # @param overwrite boolean parameter for overwriting/not overwriting the file
1964 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1965 # - 1D if all mesh nodes lie on OX coordinate axis, or
1966 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1967 # - 3D in the rest cases.<br>
1968 # If @a autoDimension is @c False, the space dimension is always 3.
1969 # @ingroup l2_impexp
1970 def ExportToMEDX(self, *args, **kwargs):
1971 print "WARNING: ExportToMEDX() is deprecated, use ExportMED() instead"
1972 # process positional arguments
1973 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
1975 auto_groups = args[1] if len(args) > 1 else False
1976 overwrite = args[2] if len(args) > 2 else True
1977 autoDimension = args[3] if len(args) > 3 else True
1978 # process keywords arguments
1979 auto_groups = kwargs.get("auto_groups", auto_groups)
1980 overwrite = kwargs.get("overwrite", overwrite)
1981 autoDimension = kwargs.get("autoDimension", autoDimension)
1982 # invoke engine's function
1983 self.mesh.ExportMED(fileName, auto_groups, overwrite, autoDimension)
1985 # Operations with groups:
1986 # ----------------------
1988 ## Create an empty mesh group
1989 # @param elementType the type of elements in the group; either of
1990 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1991 # @param name the name of the mesh group
1992 # @return SMESH_Group
1993 # @ingroup l2_grps_create
1994 def CreateEmptyGroup(self, elementType, name):
1995 return self.mesh.CreateGroup(elementType, name)
1997 ## Create a mesh group based on the geometric object \a grp
1998 # and gives a \a name, \n if this parameter is not defined
1999 # the name is the same as the geometric group name \n
2000 # Note: Works like GroupOnGeom().
2001 # @param grp a geometric group, a vertex, an edge, a face or a solid
2002 # @param name the name of the mesh group
2003 # @return SMESH_GroupOnGeom
2004 # @ingroup l2_grps_create
2005 def Group(self, grp, name=""):
2006 return self.GroupOnGeom(grp, name)
2008 ## Create a mesh group based on the geometrical object \a grp
2009 # and gives a \a name, \n if this parameter is not defined
2010 # the name is the same as the geometrical group name
2011 # @param grp a geometrical group, a vertex, an edge, a face or a solid
2012 # @param name the name of the mesh group
2013 # @param typ the type of elements in the group; either of
2014 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
2015 # automatically detected by the type of the geometry
2016 # @return SMESH_GroupOnGeom
2017 # @ingroup l2_grps_create
2018 def GroupOnGeom(self, grp, name="", typ=None):
2019 AssureGeomPublished( self, grp, name )
2021 name = grp.GetName()
2023 typ = self._groupTypeFromShape( grp )
2024 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
2026 ## Pivate method to get a type of group on geometry
2027 def _groupTypeFromShape( self, shape ):
2028 tgeo = str(shape.GetShapeType())
2029 if tgeo == "VERTEX":
2031 elif tgeo == "EDGE":
2033 elif tgeo == "FACE" or tgeo == "SHELL":
2035 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
2037 elif tgeo == "COMPOUND":
2038 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
2040 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
2041 return self._groupTypeFromShape( sub[0] )
2044 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
2047 ## Create a mesh group with given \a name based on the \a filter which
2048 ## is a special type of group dynamically updating it's contents during
2049 ## mesh modification
2050 # @param typ the type of elements in the group; either of
2051 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2052 # @param name the name of the mesh group
2053 # @param filter the filter defining group contents
2054 # @return SMESH_GroupOnFilter
2055 # @ingroup l2_grps_create
2056 def GroupOnFilter(self, typ, name, filter):
2057 return self.mesh.CreateGroupFromFilter(typ, name, filter)
2059 ## Create a mesh group by the given ids of elements
2060 # @param groupName the name of the mesh group
2061 # @param elementType the type of elements in the group; either of
2062 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2063 # @param elemIDs either the list of ids, group, sub-mesh, or filter
2064 # @return SMESH_Group
2065 # @ingroup l2_grps_create
2066 def MakeGroupByIds(self, groupName, elementType, elemIDs):
2067 group = self.mesh.CreateGroup(elementType, groupName)
2068 if hasattr( elemIDs, "GetIDs" ):
2069 if hasattr( elemIDs, "SetMesh" ):
2070 elemIDs.SetMesh( self.GetMesh() )
2071 group.AddFrom( elemIDs )
2076 ## Create a mesh group by the given conditions
2077 # @param groupName the name of the mesh group
2078 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2079 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
2080 # Type SMESH.FunctorType._items in the Python Console to see all values.
2081 # Note that the items starting from FT_LessThan are not suitable for CritType.
2082 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
2083 # @param Threshold the threshold value (range of ids as string, shape, numeric)
2084 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2085 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2086 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2087 # @return SMESH_GroupOnFilter
2088 # @ingroup l2_grps_create
2092 CritType=FT_Undefined,
2095 UnaryOp=FT_Undefined,
2097 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2098 group = self.MakeGroupByCriterion(groupName, aCriterion)
2101 ## Create a mesh group by the given criterion
2102 # @param groupName the name of the mesh group
2103 # @param Criterion the instance of Criterion class
2104 # @return SMESH_GroupOnFilter
2105 # @ingroup l2_grps_create
2106 def MakeGroupByCriterion(self, groupName, Criterion):
2107 return self.MakeGroupByCriteria( groupName, [Criterion] )
2109 ## Create a mesh group by the given criteria (list of criteria)
2110 # @param groupName the name of the mesh group
2111 # @param theCriteria the list of criteria
2112 # @param binOp binary operator used when binary operator of criteria is undefined
2113 # @return SMESH_GroupOnFilter
2114 # @ingroup l2_grps_create
2115 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2116 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2117 group = self.MakeGroupByFilter(groupName, aFilter)
2120 ## Create a mesh group by the given filter
2121 # @param groupName the name of the mesh group
2122 # @param theFilter the instance of Filter class
2123 # @return SMESH_GroupOnFilter
2124 # @ingroup l2_grps_create
2125 def MakeGroupByFilter(self, groupName, theFilter):
2126 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2127 #theFilter.SetMesh( self.mesh )
2128 #group.AddFrom( theFilter )
2129 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2133 # @ingroup l2_grps_delete
2134 def RemoveGroup(self, group):
2135 self.mesh.RemoveGroup(group)
2137 ## Remove a group with its contents
2138 # @ingroup l2_grps_delete
2139 def RemoveGroupWithContents(self, group):
2140 self.mesh.RemoveGroupWithContents(group)
2142 ## Get the list of groups existing in the mesh in the order
2143 # of creation (starting from the oldest one)
2144 # @param elemType type of elements the groups contain; either of
2145 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2146 # by default groups of elements of all types are returned
2147 # @return a sequence of SMESH_GroupBase
2148 # @ingroup l2_grps_create
2149 def GetGroups(self, elemType = SMESH.ALL):
2150 groups = self.mesh.GetGroups()
2151 if elemType == SMESH.ALL:
2155 if g.GetType() == elemType:
2156 typedGroups.append( g )
2161 ## Get the number of groups existing in the mesh
2162 # @return the quantity of groups as an integer value
2163 # @ingroup l2_grps_create
2165 return self.mesh.NbGroups()
2167 ## Get the list of names of groups existing in the mesh
2168 # @return list of strings
2169 # @ingroup l2_grps_create
2170 def GetGroupNames(self):
2171 groups = self.GetGroups()
2173 for group in groups:
2174 names.append(group.GetName())
2177 ## Find groups by name and type
2178 # @param name name of the group of interest
2179 # @param elemType type of elements the groups contain; either of
2180 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2181 # by default one group of any type of elements is returned
2182 # if elemType == SMESH.ALL then all groups of any type are returned
2183 # @return a list of SMESH_GroupBase's
2184 # @ingroup l2_grps_create
2185 def GetGroupByName(self, name, elemType = None):
2187 for group in self.GetGroups():
2188 if group.GetName() == name:
2189 if elemType is None:
2191 if ( elemType == SMESH.ALL or
2192 group.GetType() == elemType ):
2193 groups.append( group )
2196 ## Produce a union of two groups.
2197 # A new group is created. All mesh elements that are
2198 # present in the initial groups are added to the new one
2199 # @return an instance of SMESH_Group
2200 # @ingroup l2_grps_operon
2201 def UnionGroups(self, group1, group2, name):
2202 return self.mesh.UnionGroups(group1, group2, name)
2204 ## Produce a union list of groups.
2205 # New group is created. All mesh elements that are present in
2206 # initial groups are added to the new one
2207 # @return an instance of SMESH_Group
2208 # @ingroup l2_grps_operon
2209 def UnionListOfGroups(self, groups, name):
2210 return self.mesh.UnionListOfGroups(groups, name)
2212 ## Prodice an intersection of two groups.
2213 # A new group is created. All mesh elements that are common
2214 # for the two initial groups are added to the new one.
2215 # @return an instance of SMESH_Group
2216 # @ingroup l2_grps_operon
2217 def IntersectGroups(self, group1, group2, name):
2218 return self.mesh.IntersectGroups(group1, group2, name)
2220 ## Produce an intersection of groups.
2221 # New group is created. All mesh elements that are present in all
2222 # initial groups simultaneously are added to the new one
2223 # @return an instance of SMESH_Group
2224 # @ingroup l2_grps_operon
2225 def IntersectListOfGroups(self, groups, name):
2226 return self.mesh.IntersectListOfGroups(groups, name)
2228 ## Produce a cut of two groups.
2229 # A new group is created. All mesh elements that are present in
2230 # the main group but are not present in the tool group are added to the new one
2231 # @return an instance of SMESH_Group
2232 # @ingroup l2_grps_operon
2233 def CutGroups(self, main_group, tool_group, name):
2234 return self.mesh.CutGroups(main_group, tool_group, name)
2236 ## Produce a cut of groups.
2237 # A new group is created. All mesh elements that are present in main groups
2238 # but do not present in tool groups are added to the new one
2239 # @return an instance of SMESH_Group
2240 # @ingroup l2_grps_operon
2241 def CutListOfGroups(self, main_groups, tool_groups, name):
2242 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2245 # Create a standalone group of entities basing on nodes of other groups.
2246 # \param groups - list of reference groups, sub-meshes or filters, of any type.
2247 # \param elemType - a type of elements to include to the new group; either of
2248 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2249 # \param name - a name of the new group.
2250 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2251 # basing on number of element nodes common with reference \a groups.
2252 # Meaning of possible values are:
2253 # - SMESH.ALL_NODES - include if all nodes are common,
2254 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2255 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2256 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2257 # \param underlyingOnly - if \c True (default), an element is included to the
2258 # new group provided that it is based on nodes of an element of \a groups;
2259 # in this case the reference \a groups are supposed to be of higher dimension
2260 # than \a elemType, which can be useful for example to get all faces lying on
2261 # volumes of the reference \a groups.
2262 # @return an instance of SMESH_Group
2263 # @ingroup l2_grps_operon
2264 def CreateDimGroup(self, groups, elemType, name,
2265 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2266 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2268 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2271 ## Convert group on geom into standalone group
2272 # @ingroup l2_grps_operon
2273 def ConvertToStandalone(self, group):
2274 return self.mesh.ConvertToStandalone(group)
2276 # Get some info about mesh:
2277 # ------------------------
2279 ## Return the log of nodes and elements added or removed
2280 # since the previous clear of the log.
2281 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2282 # @return list of log_block structures:
2287 # @ingroup l1_auxiliary
2288 def GetLog(self, clearAfterGet):
2289 return self.mesh.GetLog(clearAfterGet)
2291 ## Clear the log of nodes and elements added or removed since the previous
2292 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2293 # @ingroup l1_auxiliary
2295 self.mesh.ClearLog()
2297 ## Toggle auto color mode on the object.
2298 # @param theAutoColor the flag which toggles auto color mode.
2300 # If switched on, a default color of a new group in Create Group dialog is chosen randomly.
2301 # @ingroup l1_grouping
2302 def SetAutoColor(self, theAutoColor):
2303 self.mesh.SetAutoColor(theAutoColor)
2305 ## Get flag of object auto color mode.
2306 # @return True or False
2307 # @ingroup l1_grouping
2308 def GetAutoColor(self):
2309 return self.mesh.GetAutoColor()
2311 ## Get the internal ID
2312 # @return integer value, which is the internal Id of the mesh
2313 # @ingroup l1_auxiliary
2315 return self.mesh.GetId()
2318 # @return integer value, which is the study Id of the mesh
2319 # @ingroup l1_auxiliary
2320 def GetStudyId(self):
2321 return self.mesh.GetStudyId()
2323 ## Check the group names for duplications.
2324 # Consider the maximum group name length stored in MED file.
2325 # @return True or False
2326 # @ingroup l1_grouping
2327 def HasDuplicatedGroupNamesMED(self):
2328 return self.mesh.HasDuplicatedGroupNamesMED()
2330 ## Obtain the mesh editor tool
2331 # @return an instance of SMESH_MeshEditor
2332 # @ingroup l1_modifying
2333 def GetMeshEditor(self):
2336 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2337 # can be passed as argument to a method accepting mesh, group or sub-mesh
2338 # @param ids list of IDs
2339 # @param elemType type of elements; this parameter is used to distinguish
2340 # IDs of nodes from IDs of elements; by default ids are treated as
2341 # IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2342 # @return an instance of SMESH_IDSource
2343 # @warning call UnRegister() for the returned object as soon as it is no more useful:
2344 # idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2345 # mesh.DoSomething( idSrc )
2346 # idSrc.UnRegister()
2347 # @ingroup l1_auxiliary
2348 def GetIDSource(self, ids, elemType = SMESH.ALL):
2349 if isinstance( ids, int ):
2351 return self.editor.MakeIDSource(ids, elemType)
2354 # Get informations about mesh contents:
2355 # ------------------------------------
2357 ## Get the mesh stattistic
2358 # @return dictionary type element - count of elements
2359 # @ingroup l1_meshinfo
2360 def GetMeshInfo(self, obj = None):
2361 if not obj: obj = self.mesh
2362 return self.smeshpyD.GetMeshInfo(obj)
2364 ## Return the number of nodes in the mesh
2365 # @return an integer value
2366 # @ingroup l1_meshinfo
2368 return self.mesh.NbNodes()
2370 ## Return the number of elements in the mesh
2371 # @return an integer value
2372 # @ingroup l1_meshinfo
2373 def NbElements(self):
2374 return self.mesh.NbElements()
2376 ## Return the number of 0d elements in the mesh
2377 # @return an integer value
2378 # @ingroup l1_meshinfo
2379 def Nb0DElements(self):
2380 return self.mesh.Nb0DElements()
2382 ## Return the number of ball discrete elements in the mesh
2383 # @return an integer value
2384 # @ingroup l1_meshinfo
2386 return self.mesh.NbBalls()
2388 ## Return the number of edges in the mesh
2389 # @return an integer value
2390 # @ingroup l1_meshinfo
2392 return self.mesh.NbEdges()
2394 ## Return the number of edges with the given order in the mesh
2395 # @param elementOrder the order of elements:
2396 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2397 # @return an integer value
2398 # @ingroup l1_meshinfo
2399 def NbEdgesOfOrder(self, elementOrder):
2400 return self.mesh.NbEdgesOfOrder(elementOrder)
2402 ## Return the number of faces in the mesh
2403 # @return an integer value
2404 # @ingroup l1_meshinfo
2406 return self.mesh.NbFaces()
2408 ## Return the number of faces with the given order in the mesh
2409 # @param elementOrder the order of elements:
2410 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2411 # @return an integer value
2412 # @ingroup l1_meshinfo
2413 def NbFacesOfOrder(self, elementOrder):
2414 return self.mesh.NbFacesOfOrder(elementOrder)
2416 ## Return the number of triangles in the mesh
2417 # @return an integer value
2418 # @ingroup l1_meshinfo
2419 def NbTriangles(self):
2420 return self.mesh.NbTriangles()
2422 ## Return the number of triangles with the given order in the mesh
2423 # @param elementOrder is the order of elements:
2424 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2425 # @return an integer value
2426 # @ingroup l1_meshinfo
2427 def NbTrianglesOfOrder(self, elementOrder):
2428 return self.mesh.NbTrianglesOfOrder(elementOrder)
2430 ## Return the number of biquadratic triangles in the mesh
2431 # @return an integer value
2432 # @ingroup l1_meshinfo
2433 def NbBiQuadTriangles(self):
2434 return self.mesh.NbBiQuadTriangles()
2436 ## Return the number of quadrangles in the mesh
2437 # @return an integer value
2438 # @ingroup l1_meshinfo
2439 def NbQuadrangles(self):
2440 return self.mesh.NbQuadrangles()
2442 ## Return the number of quadrangles with the given order in the mesh
2443 # @param elementOrder the order of elements:
2444 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2445 # @return an integer value
2446 # @ingroup l1_meshinfo
2447 def NbQuadranglesOfOrder(self, elementOrder):
2448 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2450 ## Return the number of biquadratic quadrangles in the mesh
2451 # @return an integer value
2452 # @ingroup l1_meshinfo
2453 def NbBiQuadQuadrangles(self):
2454 return self.mesh.NbBiQuadQuadrangles()
2456 ## Return the number of polygons of given order in the mesh
2457 # @param elementOrder the order of elements:
2458 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2459 # @return an integer value
2460 # @ingroup l1_meshinfo
2461 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2462 return self.mesh.NbPolygonsOfOrder(elementOrder)
2464 ## Return the number of volumes in the mesh
2465 # @return an integer value
2466 # @ingroup l1_meshinfo
2467 def NbVolumes(self):
2468 return self.mesh.NbVolumes()
2470 ## Return the number of volumes with the given order in the mesh
2471 # @param elementOrder the order of elements:
2472 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2473 # @return an integer value
2474 # @ingroup l1_meshinfo
2475 def NbVolumesOfOrder(self, elementOrder):
2476 return self.mesh.NbVolumesOfOrder(elementOrder)
2478 ## Return the number of tetrahedrons in the mesh
2479 # @return an integer value
2480 # @ingroup l1_meshinfo
2482 return self.mesh.NbTetras()
2484 ## Return the number of tetrahedrons with the given order in the mesh
2485 # @param elementOrder the order of elements:
2486 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2487 # @return an integer value
2488 # @ingroup l1_meshinfo
2489 def NbTetrasOfOrder(self, elementOrder):
2490 return self.mesh.NbTetrasOfOrder(elementOrder)
2492 ## Return the number of hexahedrons in the mesh
2493 # @return an integer value
2494 # @ingroup l1_meshinfo
2496 return self.mesh.NbHexas()
2498 ## Return the number of hexahedrons with the given order in the mesh
2499 # @param elementOrder the order of elements:
2500 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2501 # @return an integer value
2502 # @ingroup l1_meshinfo
2503 def NbHexasOfOrder(self, elementOrder):
2504 return self.mesh.NbHexasOfOrder(elementOrder)
2506 ## Return the number of triquadratic hexahedrons in the mesh
2507 # @return an integer value
2508 # @ingroup l1_meshinfo
2509 def NbTriQuadraticHexas(self):
2510 return self.mesh.NbTriQuadraticHexas()
2512 ## Return the number of pyramids in the mesh
2513 # @return an integer value
2514 # @ingroup l1_meshinfo
2515 def NbPyramids(self):
2516 return self.mesh.NbPyramids()
2518 ## Return the number of pyramids with the given order in the mesh
2519 # @param elementOrder the order of elements:
2520 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2521 # @return an integer value
2522 # @ingroup l1_meshinfo
2523 def NbPyramidsOfOrder(self, elementOrder):
2524 return self.mesh.NbPyramidsOfOrder(elementOrder)
2526 ## Return the number of prisms in the mesh
2527 # @return an integer value
2528 # @ingroup l1_meshinfo
2530 return self.mesh.NbPrisms()
2532 ## Return the number of prisms with the given order in the mesh
2533 # @param elementOrder the order of elements:
2534 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2535 # @return an integer value
2536 # @ingroup l1_meshinfo
2537 def NbPrismsOfOrder(self, elementOrder):
2538 return self.mesh.NbPrismsOfOrder(elementOrder)
2540 ## Return the number of hexagonal prisms in the mesh
2541 # @return an integer value
2542 # @ingroup l1_meshinfo
2543 def NbHexagonalPrisms(self):
2544 return self.mesh.NbHexagonalPrisms()
2546 ## Return the number of polyhedrons in the mesh
2547 # @return an integer value
2548 # @ingroup l1_meshinfo
2549 def NbPolyhedrons(self):
2550 return self.mesh.NbPolyhedrons()
2552 ## Return the number of submeshes in the mesh
2553 # @return an integer value
2554 # @ingroup l1_meshinfo
2555 def NbSubMesh(self):
2556 return self.mesh.NbSubMesh()
2558 ## Return the list of mesh elements IDs
2559 # @return the list of integer values
2560 # @ingroup l1_meshinfo
2561 def GetElementsId(self):
2562 return self.mesh.GetElementsId()
2564 ## Return the list of IDs of mesh elements with the given type
2565 # @param elementType the required type of elements, either of
2566 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2567 # @return list of integer values
2568 # @ingroup l1_meshinfo
2569 def GetElementsByType(self, elementType):
2570 return self.mesh.GetElementsByType(elementType)
2572 ## Return the list of mesh nodes IDs
2573 # @return the list of integer values
2574 # @ingroup l1_meshinfo
2575 def GetNodesId(self):
2576 return self.mesh.GetNodesId()
2578 # Get the information about mesh elements:
2579 # ------------------------------------
2581 ## Return the type of mesh element
2582 # @return the value from SMESH::ElementType enumeration
2583 # Type SMESH.ElementType._items in the Python Console to see all possible values.
2584 # @ingroup l1_meshinfo
2585 def GetElementType(self, id, iselem=True):
2586 return self.mesh.GetElementType(id, iselem)
2588 ## Return the geometric type of mesh element
2589 # @return the value from SMESH::EntityType enumeration
2590 # Type SMESH.EntityType._items in the Python Console to see all possible values.
2591 # @ingroup l1_meshinfo
2592 def GetElementGeomType(self, id):
2593 return self.mesh.GetElementGeomType(id)
2595 ## Return the shape type of mesh element
2596 # @return the value from SMESH::GeometryType enumeration.
2597 # Type SMESH.GeometryType._items in the Python Console to see all possible values.
2598 # @ingroup l1_meshinfo
2599 def GetElementShape(self, id):
2600 return self.mesh.GetElementShape(id)
2602 ## Return the list of submesh elements IDs
2603 # @param Shape a geom object(sub-shape)
2604 # Shape must be the sub-shape of a ShapeToMesh()
2605 # @return the list of integer values
2606 # @ingroup l1_meshinfo
2607 def GetSubMeshElementsId(self, Shape):
2608 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2609 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2612 return self.mesh.GetSubMeshElementsId(ShapeID)
2614 ## Return the list of submesh nodes IDs
2615 # @param Shape a geom object(sub-shape)
2616 # Shape must be the sub-shape of a ShapeToMesh()
2617 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2618 # @return the list of integer values
2619 # @ingroup l1_meshinfo
2620 def GetSubMeshNodesId(self, Shape, all):
2621 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2622 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2625 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2627 ## Return type of elements on given shape
2628 # @param Shape a geom object(sub-shape)
2629 # Shape must be a sub-shape of a ShapeToMesh()
2630 # @return element type
2631 # @ingroup l1_meshinfo
2632 def GetSubMeshElementType(self, Shape):
2633 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2634 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2637 return self.mesh.GetSubMeshElementType(ShapeID)
2639 ## Get the mesh description
2640 # @return string value
2641 # @ingroup l1_meshinfo
2643 return self.mesh.Dump()
2646 # Get the information about nodes and elements of a mesh by its IDs:
2647 # -----------------------------------------------------------
2649 ## Get XYZ coordinates of a node
2650 # \n If there is no nodes for the given ID - return an empty list
2651 # @return a list of double precision values
2652 # @ingroup l1_meshinfo
2653 def GetNodeXYZ(self, id):
2654 return self.mesh.GetNodeXYZ(id)
2656 ## Return list of IDs of inverse elements for the given node
2657 # \n If there is no node for the given ID - return an empty list
2658 # @return a list of integer values
2659 # @ingroup l1_meshinfo
2660 def GetNodeInverseElements(self, id):
2661 return self.mesh.GetNodeInverseElements(id)
2663 ## Return the position of a node on the shape
2664 # @return SMESH::NodePosition
2665 # @ingroup l1_meshinfo
2666 def GetNodePosition(self,NodeID):
2667 return self.mesh.GetNodePosition(NodeID)
2669 ## Return the position of an element on the shape
2670 # @return SMESH::ElementPosition
2671 # @ingroup l1_meshinfo
2672 def GetElementPosition(self,ElemID):
2673 return self.mesh.GetElementPosition(ElemID)
2675 ## Return the ID of the shape, on which the given node was generated.
2676 # @return an integer value > 0 or -1 if there is no node for the given
2677 # ID or the node is not assigned to any geometry
2678 # @ingroup l1_meshinfo
2679 def GetShapeID(self, id):
2680 return self.mesh.GetShapeID(id)
2682 ## Return the ID of the shape, on which the given element was generated.
2683 # @return an integer value > 0 or -1 if there is no element for the given
2684 # ID or the element is not assigned to any geometry
2685 # @ingroup l1_meshinfo
2686 def GetShapeIDForElem(self,id):
2687 return self.mesh.GetShapeIDForElem(id)
2689 ## Return the number of nodes of the given element
2690 # @return an integer value > 0 or -1 if there is no element for the given ID
2691 # @ingroup l1_meshinfo
2692 def GetElemNbNodes(self, id):
2693 return self.mesh.GetElemNbNodes(id)
2695 ## Return the node ID the given (zero based) index for the given element
2696 # \n If there is no element for the given ID - return -1
2697 # \n If there is no node for the given index - return -2
2698 # @return an integer value
2699 # @ingroup l1_meshinfo
2700 def GetElemNode(self, id, index):
2701 return self.mesh.GetElemNode(id, index)
2703 ## Return the IDs of nodes of the given element
2704 # @return a list of integer values
2705 # @ingroup l1_meshinfo
2706 def GetElemNodes(self, id):
2707 return self.mesh.GetElemNodes(id)
2709 ## Return true if the given node is the medium node in the given quadratic element
2710 # @ingroup l1_meshinfo
2711 def IsMediumNode(self, elementID, nodeID):
2712 return self.mesh.IsMediumNode(elementID, nodeID)
2714 ## Return true if the given node is the medium node in one of quadratic elements
2715 # @param nodeID ID of the node
2716 # @param elementType the type of elements to check a state of the node, either of
2717 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2718 # @ingroup l1_meshinfo
2719 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2720 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2722 ## Return the number of edges for the given element
2723 # @ingroup l1_meshinfo
2724 def ElemNbEdges(self, id):
2725 return self.mesh.ElemNbEdges(id)
2727 ## Return the number of faces for the given element
2728 # @ingroup l1_meshinfo
2729 def ElemNbFaces(self, id):
2730 return self.mesh.ElemNbFaces(id)
2732 ## Return nodes of given face (counted from zero) for given volumic element.
2733 # @ingroup l1_meshinfo
2734 def GetElemFaceNodes(self,elemId, faceIndex):
2735 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2737 ## Return three components of normal of given mesh face
2738 # (or an empty array in KO case)
2739 # @ingroup l1_meshinfo
2740 def GetFaceNormal(self, faceId, normalized=False):
2741 return self.mesh.GetFaceNormal(faceId,normalized)
2743 ## Return an element based on all given nodes.
2744 # @ingroup l1_meshinfo
2745 def FindElementByNodes(self,nodes):
2746 return self.mesh.FindElementByNodes(nodes)
2748 ## Return true if the given element is a polygon
2749 # @ingroup l1_meshinfo
2750 def IsPoly(self, id):
2751 return self.mesh.IsPoly(id)
2753 ## Return true if the given element is quadratic
2754 # @ingroup l1_meshinfo
2755 def IsQuadratic(self, id):
2756 return self.mesh.IsQuadratic(id)
2758 ## Return diameter of a ball discrete element or zero in case of an invalid \a id
2759 # @ingroup l1_meshinfo
2760 def GetBallDiameter(self, id):
2761 return self.mesh.GetBallDiameter(id)
2763 ## Return XYZ coordinates of the barycenter of the given element
2764 # \n If there is no element for the given ID - return an empty list
2765 # @return a list of three double values
2766 # @ingroup l1_meshinfo
2767 def BaryCenter(self, id):
2768 return self.mesh.BaryCenter(id)
2770 ## Pass mesh elements through the given filter and return IDs of fitting elements
2771 # @param theFilter SMESH_Filter
2772 # @return a list of ids
2773 # @ingroup l1_controls
2774 def GetIdsFromFilter(self, theFilter):
2775 theFilter.SetMesh( self.mesh )
2776 return theFilter.GetIDs()
2778 # Get mesh measurements information:
2779 # ------------------------------------
2781 ## Verify whether a 2D mesh element has free edges (edges connected to one face only)\n
2782 # Return a list of special structures (borders).
2783 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2784 # @ingroup l1_measurements
2785 def GetFreeBorders(self):
2786 aFilterMgr = self.smeshpyD.CreateFilterManager()
2787 aPredicate = aFilterMgr.CreateFreeEdges()
2788 aPredicate.SetMesh(self.mesh)
2789 aBorders = aPredicate.GetBorders()
2790 aFilterMgr.UnRegister()
2793 ## Get minimum distance between two nodes, elements or distance to the origin
2794 # @param id1 first node/element id
2795 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2796 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2797 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2798 # @return minimum distance value
2799 # @sa GetMinDistance()
2800 # @ingroup l1_measurements
2801 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2802 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2803 return aMeasure.value
2805 ## Get measure structure specifying minimum distance data between two objects
2806 # @param id1 first node/element id
2807 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2808 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2809 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2810 # @return Measure structure
2812 # @ingroup l1_measurements
2813 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2815 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2817 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2820 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2822 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2827 aMeasurements = self.smeshpyD.CreateMeasurements()
2828 aMeasure = aMeasurements.MinDistance(id1, id2)
2829 genObjUnRegister([aMeasurements,id1, id2])
2832 ## Get bounding box of the specified object(s)
2833 # @param objects single source object or list of source objects or list of nodes/elements IDs
2834 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2835 # @c False specifies that @a objects are nodes
2836 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2837 # @sa GetBoundingBox()
2838 # @ingroup l1_measurements
2839 def BoundingBox(self, objects=None, isElem=False):
2840 result = self.GetBoundingBox(objects, isElem)
2844 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2847 ## Get measure structure specifying bounding box data of the specified object(s)
2848 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2849 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2850 # @c False specifies that @a objects are nodes
2851 # @return Measure structure
2853 # @ingroup l1_measurements
2854 def GetBoundingBox(self, IDs=None, isElem=False):
2857 elif isinstance(IDs, tuple):
2859 if not isinstance(IDs, list):
2861 if len(IDs) > 0 and isinstance(IDs[0], int):
2864 unRegister = genObjUnRegister()
2866 if isinstance(o, Mesh):
2867 srclist.append(o.mesh)
2868 elif hasattr(o, "_narrow"):
2869 src = o._narrow(SMESH.SMESH_IDSource)
2870 if src: srclist.append(src)
2872 elif isinstance(o, list):
2874 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2876 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2877 unRegister.set( srclist[-1] )
2880 aMeasurements = self.smeshpyD.CreateMeasurements()
2881 unRegister.set( aMeasurements )
2882 aMeasure = aMeasurements.BoundingBox(srclist)
2885 # Mesh edition (SMESH_MeshEditor functionality):
2886 # ---------------------------------------------
2888 ## Remove the elements from the mesh by ids
2889 # @param IDsOfElements is a list of ids of elements to remove
2890 # @return True or False
2891 # @ingroup l2_modif_del
2892 def RemoveElements(self, IDsOfElements):
2893 return self.editor.RemoveElements(IDsOfElements)
2895 ## Remove nodes from mesh by ids
2896 # @param IDsOfNodes is a list of ids of nodes to remove
2897 # @return True or False
2898 # @ingroup l2_modif_del
2899 def RemoveNodes(self, IDsOfNodes):
2900 return self.editor.RemoveNodes(IDsOfNodes)
2902 ## Remove all orphan (free) nodes from mesh
2903 # @return number of the removed nodes
2904 # @ingroup l2_modif_del
2905 def RemoveOrphanNodes(self):
2906 return self.editor.RemoveOrphanNodes()
2908 ## Add a node to the mesh by coordinates
2909 # @return Id of the new node
2910 # @ingroup l2_modif_add
2911 def AddNode(self, x, y, z):
2912 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2913 if hasVars: self.mesh.SetParameters(Parameters)
2914 return self.editor.AddNode( x, y, z)
2916 ## Create a 0D element on a node with given number.
2917 # @param IDOfNode the ID of node for creation of the element.
2918 # @param DuplicateElements to add one more 0D element to a node or not
2919 # @return the Id of the new 0D element
2920 # @ingroup l2_modif_add
2921 def Add0DElement( self, IDOfNode, DuplicateElements=True ):
2922 return self.editor.Add0DElement( IDOfNode, DuplicateElements )
2924 ## Create 0D elements on all nodes of the given elements except those
2925 # nodes on which a 0D element already exists.
2926 # @param theObject an object on whose nodes 0D elements will be created.
2927 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2928 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2929 # @param theGroupName optional name of a group to add 0D elements created
2930 # and/or found on nodes of \a theObject.
2931 # @param DuplicateElements to add one more 0D element to a node or not
2932 # @return an object (a new group or a temporary SMESH_IDSource) holding
2933 # IDs of new and/or found 0D elements. IDs of 0D elements
2934 # can be retrieved from the returned object by calling GetIDs()
2935 # @ingroup l2_modif_add
2936 def Add0DElementsToAllNodes(self, theObject, theGroupName="", DuplicateElements=False):
2937 unRegister = genObjUnRegister()
2938 if isinstance( theObject, Mesh ):
2939 theObject = theObject.GetMesh()
2940 elif isinstance( theObject, list ):
2941 theObject = self.GetIDSource( theObject, SMESH.ALL )
2942 unRegister.set( theObject )
2943 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName, DuplicateElements )
2945 ## Create a ball element on a node with given ID.
2946 # @param IDOfNode the ID of node for creation of the element.
2947 # @param diameter the bal diameter.
2948 # @return the Id of the new ball element
2949 # @ingroup l2_modif_add
2950 def AddBall(self, IDOfNode, diameter):
2951 return self.editor.AddBall( IDOfNode, diameter )
2953 ## Create a linear or quadratic edge (this is determined
2954 # by the number of given nodes).
2955 # @param IDsOfNodes the list of node IDs for creation of the element.
2956 # The order of nodes in this list should correspond to the description
2957 # of MED. \n This description is located by the following link:
2958 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2959 # @return the Id of the new edge
2960 # @ingroup l2_modif_add
2961 def AddEdge(self, IDsOfNodes):
2962 return self.editor.AddEdge(IDsOfNodes)
2964 ## Create a linear or quadratic face (this is determined
2965 # by the number of given nodes).
2966 # @param IDsOfNodes the list of node IDs for creation of the element.
2967 # The order of nodes in this list should correspond to the description
2968 # of MED. \n This description is located by the following link:
2969 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2970 # @return the Id of the new face
2971 # @ingroup l2_modif_add
2972 def AddFace(self, IDsOfNodes):
2973 return self.editor.AddFace(IDsOfNodes)
2975 ## Add a polygonal face to the mesh by the list of node IDs
2976 # @param IdsOfNodes the list of node IDs for creation of the element.
2977 # @return the Id of the new face
2978 # @ingroup l2_modif_add
2979 def AddPolygonalFace(self, IdsOfNodes):
2980 return self.editor.AddPolygonalFace(IdsOfNodes)
2982 ## Add a quadratic polygonal face to the mesh by the list of node IDs
2983 # @param IdsOfNodes the list of node IDs for creation of the element;
2984 # corner nodes follow first.
2985 # @return the Id of the new face
2986 # @ingroup l2_modif_add
2987 def AddQuadPolygonalFace(self, IdsOfNodes):
2988 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
2990 ## Create both simple and quadratic volume (this is determined
2991 # by the number of given nodes).
2992 # @param IDsOfNodes the list of node IDs for creation of the element.
2993 # The order of nodes in this list should correspond to the description
2994 # of MED. \n This description is located by the following link:
2995 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2996 # @return the Id of the new volumic element
2997 # @ingroup l2_modif_add
2998 def AddVolume(self, IDsOfNodes):
2999 return self.editor.AddVolume(IDsOfNodes)
3001 ## Create a volume of many faces, giving nodes for each face.
3002 # @param IdsOfNodes the list of node IDs for volume creation face by face.
3003 # @param Quantities the list of integer values, Quantities[i]
3004 # gives the quantity of nodes in face number i.
3005 # @return the Id of the new volumic element
3006 # @ingroup l2_modif_add
3007 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
3008 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
3010 ## Create a volume of many faces, giving the IDs of the existing faces.
3011 # @param IdsOfFaces the list of face IDs for volume creation.
3013 # Note: The created volume will refer only to the nodes
3014 # of the given faces, not to the faces themselves.
3015 # @return the Id of the new volumic element
3016 # @ingroup l2_modif_add
3017 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
3018 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
3021 ## @brief Binds a node to a vertex
3022 # @param NodeID a node ID
3023 # @param Vertex a vertex or vertex ID
3024 # @return True if succeed else raises an exception
3025 # @ingroup l2_modif_add
3026 def SetNodeOnVertex(self, NodeID, Vertex):
3027 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
3028 VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
3032 self.editor.SetNodeOnVertex(NodeID, VertexID)
3033 except SALOME.SALOME_Exception, inst:
3034 raise ValueError, inst.details.text
3038 ## @brief Stores the node position on an edge
3039 # @param NodeID a node ID
3040 # @param Edge an edge or edge ID
3041 # @param paramOnEdge a parameter on the edge where the node is located
3042 # @return True if succeed else raises an exception
3043 # @ingroup l2_modif_add
3044 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
3045 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
3046 EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
3050 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
3051 except SALOME.SALOME_Exception, inst:
3052 raise ValueError, inst.details.text
3055 ## @brief Stores node position on a face
3056 # @param NodeID a node ID
3057 # @param Face a face or face ID
3058 # @param u U parameter on the face where the node is located
3059 # @param v V parameter on the face where the node is located
3060 # @return True if succeed else raises an exception
3061 # @ingroup l2_modif_add
3062 def SetNodeOnFace(self, NodeID, Face, u, v):
3063 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
3064 FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
3068 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
3069 except SALOME.SALOME_Exception, inst:
3070 raise ValueError, inst.details.text
3073 ## @brief Binds a node to a solid
3074 # @param NodeID a node ID
3075 # @param Solid a solid or solid ID
3076 # @return True if succeed else raises an exception
3077 # @ingroup l2_modif_add
3078 def SetNodeInVolume(self, NodeID, Solid):
3079 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
3080 SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
3084 self.editor.SetNodeInVolume(NodeID, SolidID)
3085 except SALOME.SALOME_Exception, inst:
3086 raise ValueError, inst.details.text
3089 ## @brief Bind an element to a shape
3090 # @param ElementID an element ID
3091 # @param Shape a shape or shape ID
3092 # @return True if succeed else raises an exception
3093 # @ingroup l2_modif_add
3094 def SetMeshElementOnShape(self, ElementID, Shape):
3095 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
3096 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3100 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
3101 except SALOME.SALOME_Exception, inst:
3102 raise ValueError, inst.details.text
3106 ## Move the node with the given id
3107 # @param NodeID the id of the node
3108 # @param x a new X coordinate
3109 # @param y a new Y coordinate
3110 # @param z a new Z coordinate
3111 # @return True if succeed else False
3112 # @ingroup l2_modif_edit
3113 def MoveNode(self, NodeID, x, y, z):
3114 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3115 if hasVars: self.mesh.SetParameters(Parameters)
3116 return self.editor.MoveNode(NodeID, x, y, z)
3118 ## Find the node closest to a point and moves it to a point location
3119 # @param x the X coordinate of a point
3120 # @param y the Y coordinate of a point
3121 # @param z the Z coordinate of a point
3122 # @param NodeID if specified (>0), the node with this ID is moved,
3123 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
3124 # @return the ID of a node
3125 # @ingroup l2_modif_edit
3126 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3127 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3128 if hasVars: self.mesh.SetParameters(Parameters)
3129 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3131 ## Find the node closest to a point
3132 # @param x the X coordinate of a point
3133 # @param y the Y coordinate of a point
3134 # @param z the Z coordinate of a point
3135 # @return the ID of a node
3136 # @ingroup l1_meshinfo
3137 def FindNodeClosestTo(self, x, y, z):
3138 #preview = self.mesh.GetMeshEditPreviewer()
3139 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3140 return self.editor.FindNodeClosestTo(x, y, z)
3142 ## Find the elements where a point lays IN or ON
3143 # @param x the X coordinate of a point
3144 # @param y the Y coordinate of a point
3145 # @param z the Z coordinate of a point
3146 # @param elementType type of elements to find; either of
3147 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3148 # means elements of any type excluding nodes, discrete and 0D elements.
3149 # @param meshPart a part of mesh (group, sub-mesh) to search within
3150 # @return list of IDs of found elements
3151 # @ingroup l1_meshinfo
3152 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3154 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
3156 return self.editor.FindElementsByPoint(x, y, z, elementType)
3158 ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
3159 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
3160 # UNKNOWN state means that either mesh is wrong or the analysis fails.
3161 # @ingroup l1_meshinfo
3162 def GetPointState(self, x, y, z):
3163 return self.editor.GetPointState(x, y, z)
3165 ## Find the node closest to a point and moves it to a point location
3166 # @param x the X coordinate of a point
3167 # @param y the Y coordinate of a point
3168 # @param z the Z coordinate of a point
3169 # @return the ID of a moved node
3170 # @ingroup l2_modif_edit
3171 def MeshToPassThroughAPoint(self, x, y, z):
3172 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3174 ## Replace two neighbour triangles sharing Node1-Node2 link
3175 # with the triangles built on the same 4 nodes but having other common link.
3176 # @param NodeID1 the ID of the first node
3177 # @param NodeID2 the ID of the second node
3178 # @return false if proper faces were not found
3179 # @ingroup l2_modif_cutquadr
3180 def InverseDiag(self, NodeID1, NodeID2):
3181 return self.editor.InverseDiag(NodeID1, NodeID2)
3183 ## Replace two neighbour triangles sharing Node1-Node2 link
3184 # with a quadrangle built on the same 4 nodes.
3185 # @param NodeID1 the ID of the first node
3186 # @param NodeID2 the ID of the second node
3187 # @return false if proper faces were not found
3188 # @ingroup l2_modif_unitetri
3189 def DeleteDiag(self, NodeID1, NodeID2):
3190 return self.editor.DeleteDiag(NodeID1, NodeID2)
3192 ## Reorient elements by ids
3193 # @param IDsOfElements if undefined reorients all mesh elements
3194 # @return True if succeed else False
3195 # @ingroup l2_modif_changori
3196 def Reorient(self, IDsOfElements=None):
3197 if IDsOfElements == None:
3198 IDsOfElements = self.GetElementsId()
3199 return self.editor.Reorient(IDsOfElements)
3201 ## Reorient all elements of the object
3202 # @param theObject mesh, submesh or group
3203 # @return True if succeed else False
3204 # @ingroup l2_modif_changori
3205 def ReorientObject(self, theObject):
3206 if ( isinstance( theObject, Mesh )):
3207 theObject = theObject.GetMesh()
3208 return self.editor.ReorientObject(theObject)
3210 ## Reorient faces contained in \a the2DObject.
3211 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3212 # @param theDirection is a desired direction of normal of \a theFace.
3213 # It can be either a GEOM vector or a list of coordinates [x,y,z].
3214 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3215 # compared with theDirection. It can be either ID of face or a point
3216 # by which the face will be found. The point can be given as either
3217 # a GEOM vertex or a list of point coordinates.
3218 # @return number of reoriented faces
3219 # @ingroup l2_modif_changori
3220 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3221 unRegister = genObjUnRegister()
3223 if isinstance( the2DObject, Mesh ):
3224 the2DObject = the2DObject.GetMesh()
3225 if isinstance( the2DObject, list ):
3226 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3227 unRegister.set( the2DObject )
3228 # check theDirection
3229 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3230 theDirection = self.smeshpyD.GetDirStruct( theDirection )
3231 if isinstance( theDirection, list ):
3232 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
3233 # prepare theFace and thePoint
3234 theFace = theFaceOrPoint
3235 thePoint = PointStruct(0,0,0)
3236 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3237 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3239 if isinstance( theFaceOrPoint, list ):
3240 thePoint = PointStruct( *theFaceOrPoint )
3242 if isinstance( theFaceOrPoint, PointStruct ):
3243 thePoint = theFaceOrPoint
3245 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3247 ## Reorient faces according to adjacent volumes.
3248 # @param the2DObject is a mesh, sub-mesh, group or list of
3249 # either IDs of faces or face groups.
3250 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3251 # @param theOutsideNormal to orient faces to have their normals
3252 # pointing either \a outside or \a inside the adjacent volumes.
3253 # @return number of reoriented faces.
3254 # @ingroup l2_modif_changori
3255 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3256 unRegister = genObjUnRegister()
3258 if not isinstance( the2DObject, list ):
3259 the2DObject = [ the2DObject ]
3260 elif the2DObject and isinstance( the2DObject[0], int ):
3261 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3262 unRegister.set( the2DObject )
3263 the2DObject = [ the2DObject ]
3264 for i,obj2D in enumerate( the2DObject ):
3265 if isinstance( obj2D, Mesh ):
3266 the2DObject[i] = obj2D.GetMesh()
3267 if isinstance( obj2D, list ):
3268 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3269 unRegister.set( the2DObject[i] )
3271 if isinstance( the3DObject, Mesh ):
3272 the3DObject = the3DObject.GetMesh()
3273 if isinstance( the3DObject, list ):
3274 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3275 unRegister.set( the3DObject )
3276 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3278 ## Fuse the neighbouring triangles into quadrangles.
3279 # @param IDsOfElements The triangles to be fused.
3280 # @param theCriterion a numerical functor, in terms of enum SMESH.FunctorType, used to
3281 # applied to possible quadrangles to choose a neighbour to fuse with.
3282 # Type SMESH.FunctorType._items in the Python Console to see all items.
3283 # Note that not all items correspond to numerical functors.
3284 # @param MaxAngle is the maximum angle between element normals at which the fusion
3285 # is still performed; theMaxAngle is mesured in radians.
3286 # Also it could be a name of variable which defines angle in degrees.
3287 # @return TRUE in case of success, FALSE otherwise.
3288 # @ingroup l2_modif_unitetri
3289 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3290 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3291 self.mesh.SetParameters(Parameters)
3292 if not IDsOfElements:
3293 IDsOfElements = self.GetElementsId()
3294 Functor = self.smeshpyD.GetFunctor(theCriterion)
3295 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3297 ## Fuse the neighbouring triangles of the object into quadrangles
3298 # @param theObject is mesh, submesh or group
3299 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType,
3300 # applied to possible quadrangles to choose a neighbour to fuse with.
3301 # Type SMESH.FunctorType._items in the Python Console to see all items.
3302 # Note that not all items correspond to numerical functors.
3303 # @param MaxAngle a max angle between element normals at which the fusion
3304 # is still performed; theMaxAngle is mesured in radians.
3305 # @return TRUE in case of success, FALSE otherwise.
3306 # @ingroup l2_modif_unitetri
3307 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3308 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3309 self.mesh.SetParameters(Parameters)
3310 if isinstance( theObject, Mesh ):
3311 theObject = theObject.GetMesh()
3312 Functor = self.smeshpyD.GetFunctor(theCriterion)
3313 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3315 ## Split quadrangles into triangles.
3316 # @param IDsOfElements the faces to be splitted.
3317 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3318 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3319 # value, then quadrangles will be split by the smallest diagonal.
3320 # Type SMESH.FunctorType._items in the Python Console to see all items.
3321 # Note that not all items correspond to numerical functors.
3322 # @return TRUE in case of success, FALSE otherwise.
3323 # @ingroup l2_modif_cutquadr
3324 def QuadToTri (self, IDsOfElements, theCriterion = None):
3325 if IDsOfElements == []:
3326 IDsOfElements = self.GetElementsId()
3327 if theCriterion is None:
3328 theCriterion = FT_MaxElementLength2D
3329 Functor = self.smeshpyD.GetFunctor(theCriterion)
3330 return self.editor.QuadToTri(IDsOfElements, Functor)
3332 ## Split quadrangles into triangles.
3333 # @param theObject the object from which the list of elements is taken,
3334 # this is mesh, submesh or group
3335 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3336 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3337 # value, then quadrangles will be split by the smallest diagonal.
3338 # Type SMESH.FunctorType._items in the Python Console to see all items.
3339 # Note that not all items correspond to numerical functors.
3340 # @return TRUE in case of success, FALSE otherwise.
3341 # @ingroup l2_modif_cutquadr
3342 def QuadToTriObject (self, theObject, theCriterion = None):
3343 if ( isinstance( theObject, Mesh )):
3344 theObject = theObject.GetMesh()
3345 if theCriterion is None:
3346 theCriterion = FT_MaxElementLength2D
3347 Functor = self.smeshpyD.GetFunctor(theCriterion)
3348 return self.editor.QuadToTriObject(theObject, Functor)
3350 ## Split each of given quadrangles into 4 triangles. A node is added at the center of
3352 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3353 # group or a list of face IDs. By default all quadrangles are split
3354 # @ingroup l2_modif_cutquadr
3355 def QuadTo4Tri (self, theElements=[]):
3356 unRegister = genObjUnRegister()
3357 if isinstance( theElements, Mesh ):
3358 theElements = theElements.mesh
3359 elif not theElements:
3360 theElements = self.mesh
3361 elif isinstance( theElements, list ):
3362 theElements = self.GetIDSource( theElements, SMESH.FACE )
3363 unRegister.set( theElements )
3364 return self.editor.QuadTo4Tri( theElements )
3366 ## Split quadrangles into triangles.
3367 # @param IDsOfElements the faces to be splitted
3368 # @param Diag13 is used to choose a diagonal for splitting.
3369 # @return TRUE in case of success, FALSE otherwise.
3370 # @ingroup l2_modif_cutquadr
3371 def SplitQuad (self, IDsOfElements, Diag13):
3372 if IDsOfElements == []:
3373 IDsOfElements = self.GetElementsId()
3374 return self.editor.SplitQuad(IDsOfElements, Diag13)
3376 ## Split quadrangles into triangles.
3377 # @param theObject the object from which the list of elements is taken,
3378 # this is mesh, submesh or group
3379 # @param Diag13 is used to choose a diagonal for splitting.
3380 # @return TRUE in case of success, FALSE otherwise.
3381 # @ingroup l2_modif_cutquadr
3382 def SplitQuadObject (self, theObject, Diag13):
3383 if ( isinstance( theObject, Mesh )):
3384 theObject = theObject.GetMesh()
3385 return self.editor.SplitQuadObject(theObject, Diag13)
3387 ## Find a better splitting of the given quadrangle.
3388 # @param IDOfQuad the ID of the quadrangle to be splitted.
3389 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3390 # choose a diagonal for splitting.
3391 # Type SMESH.FunctorType._items in the Python Console to see all items.
3392 # Note that not all items correspond to numerical functors.
3393 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3394 # diagonal is better, 0 if error occurs.
3395 # @ingroup l2_modif_cutquadr
3396 def BestSplit (self, IDOfQuad, theCriterion):
3397 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3399 ## Split volumic elements into tetrahedrons
3400 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3401 # @param method flags passing splitting method:
3402 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3403 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3404 # @ingroup l2_modif_cutquadr
3405 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3406 unRegister = genObjUnRegister()
3407 if isinstance( elems, Mesh ):
3408 elems = elems.GetMesh()
3409 if ( isinstance( elems, list )):
3410 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3411 unRegister.set( elems )
3412 self.editor.SplitVolumesIntoTetra(elems, method)
3415 ## Split bi-quadratic elements into linear ones without creation of additional nodes:
3416 # - bi-quadratic triangle will be split into 3 linear quadrangles;
3417 # - bi-quadratic quadrangle will be split into 4 linear quadrangles;
3418 # - tri-quadratic hexahedron will be split into 8 linear hexahedra.
3419 # Quadratic elements of lower dimension adjacent to the split bi-quadratic element
3420 # will be split in order to keep the mesh conformal.
3421 # @param elems - elements to split: sub-meshes, groups, filters or element IDs;
3422 # if None (default), all bi-quadratic elements will be split
3423 # @ingroup l2_modif_cutquadr
3424 def SplitBiQuadraticIntoLinear(self, elems=None):
3425 unRegister = genObjUnRegister()
3426 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
3427 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
3428 unRegister.set( elems )
3430 elems = [ self.GetMesh() ]
3431 if isinstance( elems, Mesh ):
3432 elems = [ elems.GetMesh() ]
3433 if not isinstance( elems, list ):
3435 self.editor.SplitBiQuadraticIntoLinear( elems )
3437 ## Split hexahedra into prisms
3438 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3439 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3440 # gives a normal vector defining facets to split into triangles.
3441 # @a startHexPoint can be either a triple of coordinates or a vertex.
3442 # @param facetNormal a normal to a facet to split into triangles of a
3443 # hexahedron found by @a startHexPoint.
3444 # @a facetNormal can be either a triple of coordinates or an edge.
3445 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3446 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3447 # @param allDomains if @c False, only hexahedra adjacent to one closest
3448 # to @a startHexPoint are split, else @a startHexPoint
3449 # is used to find the facet to split in all domains present in @a elems.
3450 # @ingroup l2_modif_cutquadr
3451 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3452 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3454 unRegister = genObjUnRegister()
3455 if isinstance( elems, Mesh ):
3456 elems = elems.GetMesh()
3457 if ( isinstance( elems, list )):
3458 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3459 unRegister.set( elems )
3462 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3463 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3464 elif isinstance( startHexPoint, list ):
3465 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3468 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3469 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3470 elif isinstance( facetNormal, list ):
3471 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3474 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3476 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3478 ## Split quadrangle faces near triangular facets of volumes
3480 # @ingroup l2_modif_cutquadr
3481 def SplitQuadsNearTriangularFacets(self):
3482 faces_array = self.GetElementsByType(SMESH.FACE)
3483 for face_id in faces_array:
3484 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3485 quad_nodes = self.mesh.GetElemNodes(face_id)
3486 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3487 isVolumeFound = False
3488 for node1_elem in node1_elems:
3489 if not isVolumeFound:
3490 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3491 nb_nodes = self.GetElemNbNodes(node1_elem)
3492 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3493 volume_elem = node1_elem
3494 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3495 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3496 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3497 isVolumeFound = True
3498 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3499 self.SplitQuad([face_id], False) # diagonal 2-4
3500 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3501 isVolumeFound = True
3502 self.SplitQuad([face_id], True) # diagonal 1-3
3503 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3504 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3505 isVolumeFound = True
3506 self.SplitQuad([face_id], True) # diagonal 1-3
3508 ## @brief Splits hexahedrons into tetrahedrons.
3510 # This operation uses pattern mapping functionality for splitting.
3511 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3512 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3513 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3514 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3515 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3516 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3517 # @return TRUE in case of success, FALSE otherwise.
3518 # @ingroup l2_modif_cutquadr
3519 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3520 # Pattern: 5.---------.6
3525 # (0,0,1) 4.---------.7 * |
3532 # (0,0,0) 0.---------.3
3533 pattern_tetra = "!!! Nb of points: \n 8 \n\
3543 !!! Indices of points of 6 tetras: \n\
3551 pattern = self.smeshpyD.GetPattern()
3552 isDone = pattern.LoadFromFile(pattern_tetra)
3554 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3557 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3558 isDone = pattern.MakeMesh(self.mesh, False, False)
3559 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3561 # split quafrangle faces near triangular facets of volumes
3562 self.SplitQuadsNearTriangularFacets()
3566 ## @brief Split hexahedrons into prisms.
3568 # Uses the pattern mapping functionality for splitting.
3569 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3570 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3571 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3572 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3573 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3574 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3575 # @return TRUE in case of success, FALSE otherwise.
3576 # @ingroup l2_modif_cutquadr
3577 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3578 # Pattern: 5.---------.6
3583 # (0,0,1) 4.---------.7 |
3590 # (0,0,0) 0.---------.3
3591 pattern_prism = "!!! Nb of points: \n 8 \n\
3601 !!! Indices of points of 2 prisms: \n\
3605 pattern = self.smeshpyD.GetPattern()
3606 isDone = pattern.LoadFromFile(pattern_prism)
3608 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3611 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3612 isDone = pattern.MakeMesh(self.mesh, False, False)
3613 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3615 # Split quafrangle faces near triangular facets of volumes
3616 self.SplitQuadsNearTriangularFacets()
3621 # @param IDsOfElements the list if ids of elements 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 Smooth(self, IDsOfElements, IDsOfFixedNodes,
3631 MaxNbOfIterations, MaxAspectRatio, Method):
3632 if IDsOfElements == []:
3633 IDsOfElements = self.GetElementsId()
3634 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3635 self.mesh.SetParameters(Parameters)
3636 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3637 MaxNbOfIterations, MaxAspectRatio, Method)
3639 ## Smooth elements which belong to the given object
3640 # @param theObject the object to smooth
3641 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3642 # Note that nodes built on edges and boundary nodes are always fixed.
3643 # @param MaxNbOfIterations the maximum number of iterations
3644 # @param MaxAspectRatio varies in range [1.0, inf]
3645 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3646 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3647 # @return TRUE in case of success, FALSE otherwise.
3648 # @ingroup l2_modif_smooth
3649 def SmoothObject(self, theObject, IDsOfFixedNodes,
3650 MaxNbOfIterations, MaxAspectRatio, Method):
3651 if ( isinstance( theObject, Mesh )):
3652 theObject = theObject.GetMesh()
3653 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3654 MaxNbOfIterations, MaxAspectRatio, Method)
3656 ## Parametrically smooth the given elements
3657 # @param IDsOfElements the list if ids of elements to smooth
3658 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3659 # Note that nodes built on edges and boundary nodes are always fixed.
3660 # @param MaxNbOfIterations the maximum number of iterations
3661 # @param MaxAspectRatio varies in range [1.0, inf]
3662 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3663 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3664 # @return TRUE in case of success, FALSE otherwise.
3665 # @ingroup l2_modif_smooth
3666 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3667 MaxNbOfIterations, MaxAspectRatio, Method):
3668 if IDsOfElements == []:
3669 IDsOfElements = self.GetElementsId()
3670 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3671 self.mesh.SetParameters(Parameters)
3672 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3673 MaxNbOfIterations, MaxAspectRatio, Method)
3675 ## Parametrically smooth the elements which belong to the given object
3676 # @param theObject the object to smooth
3677 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3678 # Note that nodes built on edges and boundary nodes are always fixed.
3679 # @param MaxNbOfIterations the maximum number of iterations
3680 # @param MaxAspectRatio varies in range [1.0, inf]
3681 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3682 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3683 # @return TRUE in case of success, FALSE otherwise.
3684 # @ingroup l2_modif_smooth
3685 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3686 MaxNbOfIterations, MaxAspectRatio, Method):
3687 if ( isinstance( theObject, Mesh )):
3688 theObject = theObject.GetMesh()
3689 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3690 MaxNbOfIterations, MaxAspectRatio, Method)
3692 ## Convert the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3693 # them with quadratic with the same id.
3694 # @param theForce3d new node creation method:
3695 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3696 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3697 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3698 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3699 # @return SMESH.ComputeError which can hold a warning
3700 # @ingroup l2_modif_tofromqu
3701 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3702 if isinstance( theSubMesh, Mesh ):
3703 theSubMesh = theSubMesh.mesh
3705 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3708 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3710 self.editor.ConvertToQuadratic(theForce3d)
3711 error = self.editor.GetLastError()
3712 if error and error.comment:
3716 ## Convert the mesh from quadratic to ordinary,
3717 # deletes old quadratic elements, \n replacing
3718 # them with ordinary mesh elements with the same id.
3719 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3720 # @ingroup l2_modif_tofromqu
3721 def ConvertFromQuadratic(self, theSubMesh=None):
3723 self.editor.ConvertFromQuadraticObject(theSubMesh)
3725 return self.editor.ConvertFromQuadratic()
3727 ## Create 2D mesh as skin on boundary faces of a 3D mesh
3728 # @return TRUE if operation has been completed successfully, FALSE otherwise
3729 # @ingroup l2_modif_add
3730 def Make2DMeshFrom3D(self):
3731 return self.editor.Make2DMeshFrom3D()
3733 ## Create missing boundary elements
3734 # @param elements - elements whose boundary is to be checked:
3735 # mesh, group, sub-mesh or list of elements
3736 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3737 # @param dimension - defines type of boundary elements to create, either of
3738 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3739 # SMESH.BND_1DFROM3D create mesh edges on all borders of free facets of 3D cells
3740 # @param groupName - a name of group to store created boundary elements in,
3741 # "" means not to create the group
3742 # @param meshName - a name of new mesh to store created boundary elements in,
3743 # "" means not to create the new mesh
3744 # @param toCopyElements - if true, the checked elements will be copied into
3745 # the new mesh else only boundary elements will be copied into the new mesh
3746 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3747 # boundary elements will be copied into the new mesh
3748 # @return tuple (mesh, group) where boundary elements were added to
3749 # @ingroup l2_modif_add
3750 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3751 toCopyElements=False, toCopyExistingBondary=False):
3752 unRegister = genObjUnRegister()
3753 if isinstance( elements, Mesh ):
3754 elements = elements.GetMesh()
3755 if ( isinstance( elements, list )):
3756 elemType = SMESH.ALL
3757 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3758 elements = self.editor.MakeIDSource(elements, elemType)
3759 unRegister.set( elements )
3760 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3761 toCopyElements,toCopyExistingBondary)
3762 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3766 # @brief Create missing boundary elements around either the whole mesh or
3767 # groups of elements
3768 # @param dimension - defines type of boundary elements to create, either of
3769 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3770 # @param groupName - a name of group to store all boundary elements in,
3771 # "" means not to create the group
3772 # @param meshName - a name of a new mesh, which is a copy of the initial
3773 # mesh + created boundary elements; "" means not to create the new mesh
3774 # @param toCopyAll - if true, the whole initial mesh will be copied into
3775 # the new mesh else only boundary elements will be copied into the new mesh
3776 # @param groups - groups of elements to make boundary around
3777 # @retval tuple( long, mesh, groups )
3778 # long - number of added boundary elements
3779 # mesh - the mesh where elements were added to
3780 # group - the group of boundary elements or None
3782 # @ingroup l2_modif_add
3783 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3784 toCopyAll=False, groups=[]):
3785 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3787 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3788 return nb, mesh, group
3790 ## Renumber mesh nodes (Obsolete, does nothing)
3791 # @ingroup l2_modif_renumber
3792 def RenumberNodes(self):
3793 self.editor.RenumberNodes()
3795 ## Renumber mesh elements (Obsole, does nothing)
3796 # @ingroup l2_modif_renumber
3797 def RenumberElements(self):
3798 self.editor.RenumberElements()
3800 ## Private method converting \a arg into a list of SMESH_IdSource's
3801 def _getIdSourceList(self, arg, idType, unRegister):
3802 if arg and isinstance( arg, list ):
3803 if isinstance( arg[0], int ):
3804 arg = self.GetIDSource( arg, idType )
3805 unRegister.set( arg )
3806 elif isinstance( arg[0], Mesh ):
3807 arg[0] = arg[0].GetMesh()
3808 elif isinstance( arg, Mesh ):
3810 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3814 ## Generate new elements by rotation of the given elements and nodes around the axis
3815 # @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3816 # @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3817 # @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3818 # @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3819 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3820 # which defines angle in degrees
3821 # @param NbOfSteps the number of steps
3822 # @param Tolerance tolerance
3823 # @param MakeGroups forces the generation of new groups from existing ones
3824 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3825 # of all steps, else - size of each step
3826 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3827 # @ingroup l2_modif_extrurev
3828 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3829 MakeGroups=False, TotalAngle=False):
3830 unRegister = genObjUnRegister()
3831 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3832 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3833 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3835 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3836 Axis = self.smeshpyD.GetAxisStruct( Axis )
3837 if isinstance( Axis, list ):
3838 Axis = SMESH.AxisStruct( *Axis )
3840 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3841 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3842 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3843 self.mesh.SetParameters(Parameters)
3844 if TotalAngle and NbOfSteps:
3845 AngleInRadians /= NbOfSteps
3846 return self.editor.RotationSweepObjects( nodes, edges, faces,
3847 Axis, AngleInRadians,
3848 NbOfSteps, Tolerance, MakeGroups)
3850 ## Generate new elements by rotation of the elements around the axis
3851 # @param IDsOfElements the list of ids of elements to sweep
3852 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3853 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3854 # @param NbOfSteps the number of steps
3855 # @param Tolerance tolerance
3856 # @param MakeGroups forces the generation of new groups from existing ones
3857 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3858 # of all steps, else - size of each step
3859 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3860 # @ingroup l2_modif_extrurev
3861 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3862 MakeGroups=False, TotalAngle=False):
3863 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3864 AngleInRadians, NbOfSteps, Tolerance,
3865 MakeGroups, TotalAngle)
3867 ## Generate new elements by rotation of the elements of object around the axis
3868 # @param theObject object which elements should be sweeped.
3869 # It can be a mesh, a sub mesh or a group.
3870 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3871 # @param AngleInRadians the angle of Rotation
3872 # @param NbOfSteps number of steps
3873 # @param Tolerance tolerance
3874 # @param MakeGroups forces the generation of new groups from existing ones
3875 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3876 # of all steps, else - size of each step
3877 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3878 # @ingroup l2_modif_extrurev
3879 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3880 MakeGroups=False, TotalAngle=False):
3881 return self.RotationSweepObjects( [], theObject, theObject, Axis,
3882 AngleInRadians, NbOfSteps, Tolerance,
3883 MakeGroups, TotalAngle )
3885 ## Generate new elements by rotation of the elements of object around the axis
3886 # @param theObject object which elements should be sweeped.
3887 # It can be a mesh, a sub mesh or a group.
3888 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3889 # @param AngleInRadians the angle of Rotation
3890 # @param NbOfSteps number of steps
3891 # @param Tolerance tolerance
3892 # @param MakeGroups forces the generation of new groups from existing ones
3893 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3894 # of all steps, else - size of each step
3895 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3896 # @ingroup l2_modif_extrurev
3897 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3898 MakeGroups=False, TotalAngle=False):
3899 return self.RotationSweepObjects([],theObject,[], Axis,
3900 AngleInRadians, NbOfSteps, Tolerance,
3901 MakeGroups, TotalAngle)
3903 ## Generate new elements by rotation of the elements of object around the axis
3904 # @param theObject object which elements should be sweeped.
3905 # It can be a mesh, a sub mesh or a group.
3906 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3907 # @param AngleInRadians the angle of Rotation
3908 # @param NbOfSteps number of steps
3909 # @param Tolerance tolerance
3910 # @param MakeGroups forces the generation of new groups from existing ones
3911 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3912 # of all steps, else - size of each step
3913 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3914 # @ingroup l2_modif_extrurev
3915 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3916 MakeGroups=False, TotalAngle=False):
3917 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3918 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3920 ## Generate new elements by extrusion of the given elements and nodes
3921 # @param nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3922 # @param edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3923 # @param faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3924 # @param StepVector vector or DirStruct or 3 vector components, defining
3925 # the direction and value of extrusion for one step (the total extrusion
3926 # length will be NbOfSteps * ||StepVector||)
3927 # @param NbOfSteps the number of steps
3928 # @param MakeGroups forces the generation of new groups from existing ones
3929 # @param scaleFactors optional scale factors to apply during extrusion
3930 # @param linearVariation if @c True, scaleFactors are spread over all @a scaleFactors,
3931 # else scaleFactors[i] is applied to nodes at the i-th extrusion step
3932 # @param basePoint optional scaling center; if not provided, a gravity center of
3933 # nodes and elements being extruded is used as the scaling center.
3935 # - a list of tree components of the point or
3938 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3939 # @ingroup l2_modif_extrurev
3940 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False,
3941 scaleFactors=[], linearVariation=False, basePoint=[] ):
3942 unRegister = genObjUnRegister()
3943 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3944 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3945 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3947 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3948 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3949 if isinstance( StepVector, list ):
3950 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3952 if isinstance( basePoint, int):
3953 xyz = self.GetNodeXYZ( basePoint )
3955 raise RuntimeError, "Invalid node ID: %s" % basePoint
3957 if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
3958 basePoint = self.geompyD.PointCoordinates( basePoint )
3960 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3961 Parameters = StepVector.PS.parameters + var_separator + Parameters
3962 self.mesh.SetParameters(Parameters)
3964 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
3965 StepVector, NbOfSteps,
3966 scaleFactors, linearVariation, basePoint,
3970 ## Generate new elements by extrusion of the elements with given ids
3971 # @param IDsOfElements the list of ids of elements or nodes for extrusion
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 with given ids are nodes
3978 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3979 # @ingroup l2_modif_extrurev
3980 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3982 if IsNodes: n = IDsOfElements
3983 else : e,f, = IDsOfElements,IDsOfElements
3984 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3986 ## Generate new elements by extrusion along the normal to a discretized surface or wire
3987 # @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh.
3988 # Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
3989 # @param StepSize length of one extrusion step (the total extrusion
3990 # length will be \a NbOfSteps * \a StepSize ).
3991 # @param NbOfSteps number of extrusion steps.
3992 # @param ByAverageNormal if True each node is translated by \a StepSize
3993 # along the average of the normal vectors to the faces sharing the node;
3994 # else each node is translated along the same average normal till
3995 # intersection with the plane got by translation of the face sharing
3996 # the node along its own normal by \a StepSize.
3997 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3998 # for every node of \a Elements.
3999 # @param MakeGroups forces generation of new groups from existing ones.
4000 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
4001 # is not yet implemented. This parameter is used if \a Elements contains
4002 # both faces and edges, i.e. \a Elements is a Mesh.
4003 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
4004 # empty list otherwise.
4005 # @ingroup l2_modif_extrurev
4006 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
4007 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
4008 unRegister = genObjUnRegister()
4009 if isinstance( Elements, Mesh ):
4010 Elements = [ Elements.GetMesh() ]
4011 if isinstance( Elements, list ):
4013 raise RuntimeError, "Elements empty!"
4014 if isinstance( Elements[0], int ):
4015 Elements = self.GetIDSource( Elements, SMESH.ALL )
4016 unRegister.set( Elements )
4017 if not isinstance( Elements, list ):
4018 Elements = [ Elements ]
4019 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
4020 self.mesh.SetParameters(Parameters)
4021 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
4022 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
4024 ## Generate new elements by extrusion of the elements or nodes which belong to the object
4025 # @param theObject the object whose elements or nodes should be processed.
4026 # It can be a mesh, a sub-mesh or a group.
4027 # @param StepVector vector or DirStruct or 3 vector components, defining
4028 # the direction and value of extrusion for one step (the total extrusion
4029 # length will be NbOfSteps * ||StepVector||)
4030 # @param NbOfSteps the number of steps
4031 # @param MakeGroups forces the generation of new groups from existing ones
4032 # @param IsNodes is True if elements to extrude are nodes
4033 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4034 # @ingroup l2_modif_extrurev
4035 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
4037 if IsNodes: n = theObject
4038 else : e,f, = theObject,theObject
4039 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
4041 ## Generate new elements by extrusion of edges which belong to the object
4042 # @param theObject object whose 1D elements should be processed.
4043 # It can be a mesh, a sub-mesh or a group.
4044 # @param StepVector vector or DirStruct or 3 vector components, defining
4045 # the direction and value of extrusion for one step (the total extrusion
4046 # length will be NbOfSteps * ||StepVector||)
4047 # @param NbOfSteps the number of steps
4048 # @param MakeGroups to generate new groups from existing ones
4049 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4050 # @ingroup l2_modif_extrurev
4051 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
4052 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
4054 ## Generate new elements by extrusion of faces which belong to the object
4055 # @param theObject object whose 2D elements should be processed.
4056 # It can be a mesh, a sub-mesh or a group.
4057 # @param StepVector vector or DirStruct or 3 vector components, defining
4058 # the direction and value of extrusion for one step (the total extrusion
4059 # length will be NbOfSteps * ||StepVector||)
4060 # @param NbOfSteps the number of steps
4061 # @param MakeGroups forces the generation of new groups from existing ones
4062 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4063 # @ingroup l2_modif_extrurev
4064 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
4065 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
4067 ## Generate new elements by extrusion of the elements with given ids
4068 # @param IDsOfElements is ids of elements
4069 # @param StepVector vector or DirStruct or 3 vector components, defining
4070 # the direction and value of extrusion for one step (the total extrusion
4071 # length will be NbOfSteps * ||StepVector||)
4072 # @param NbOfSteps the number of steps
4073 # @param ExtrFlags sets flags for extrusion
4074 # @param SewTolerance uses for comparing locations of nodes if flag
4075 # EXTRUSION_FLAG_SEW is set
4076 # @param MakeGroups forces the generation of new groups from existing ones
4077 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4078 # @ingroup l2_modif_extrurev
4079 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
4080 ExtrFlags, SewTolerance, MakeGroups=False):
4081 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
4082 StepVector = self.smeshpyD.GetDirStruct(StepVector)
4083 if isinstance( StepVector, list ):
4084 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
4085 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
4086 ExtrFlags, SewTolerance, MakeGroups)
4088 ## Generate new elements by extrusion of the given elements and nodes along the path.
4089 # The path of extrusion must be a meshed edge.
4090 # @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
4091 # @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
4092 # @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
4093 # @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4094 # @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
4095 # contains not only path segments, else it can be None
4096 # @param NodeStart the first or the last node on the path. Defines the direction of extrusion
4097 # @param HasAngles allows the shape to be rotated around the path
4098 # to get the resulting mesh in a helical fashion
4099 # @param Angles list of angles
4100 # @param LinearVariation forces the computation of rotation angles as linear
4101 # variation of the given Angles along path steps
4102 # @param HasRefPoint allows using the reference point
4103 # @param RefPoint the point around which the shape is rotated (the mass center of the
4104 # shape by default). The User can specify any point as the Reference Point.
4105 # @param MakeGroups forces the generation of new groups from existing ones
4106 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
4107 # @ingroup l2_modif_extrurev
4108 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
4109 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
4110 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
4111 unRegister = genObjUnRegister()
4112 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
4113 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
4114 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
4116 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
4117 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4118 if isinstance( RefPoint, list ):
4119 if not RefPoint: RefPoint = [0,0,0]
4120 RefPoint = SMESH.PointStruct( *RefPoint )
4121 if isinstance( PathMesh, Mesh ):
4122 PathMesh = PathMesh.GetMesh()
4123 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4124 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4125 self.mesh.SetParameters(Parameters)
4126 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
4127 PathMesh, PathShape, NodeStart,
4128 HasAngles, Angles, LinearVariation,
4129 HasRefPoint, RefPoint, MakeGroups)
4131 ## Generate new elements by extrusion of the given elements
4132 # The path of extrusion must be a meshed edge.
4133 # @param Base mesh or group, or sub-mesh, or list of ids of elements for extrusion
4134 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4135 # @param NodeStart the start node from Path. Defines the direction of extrusion
4136 # @param HasAngles allows the shape to be rotated around the path
4137 # to get the resulting mesh in a helical fashion
4138 # @param Angles list of angles in radians
4139 # @param LinearVariation forces the computation of rotation angles as linear
4140 # variation of the given Angles along path steps
4141 # @param HasRefPoint allows using the reference point
4142 # @param RefPoint the point around which the elements are rotated (the mass
4143 # center of the elements by default).
4144 # The User can specify any point as the Reference Point.
4145 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
4146 # @param MakeGroups forces the generation of new groups from existing ones
4147 # @param ElemType type of elements for extrusion (if param Base is a mesh)
4148 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4149 # only SMESH::Extrusion_Error otherwise
4150 # @ingroup l2_modif_extrurev
4151 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
4152 HasAngles=False, Angles=[], LinearVariation=False,
4153 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
4154 ElemType=SMESH.FACE):
4156 if ElemType == SMESH.NODE: n = Base
4157 if ElemType == SMESH.EDGE: e = Base
4158 if ElemType == SMESH.FACE: f = Base
4159 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
4160 HasAngles, Angles, LinearVariation,
4161 HasRefPoint, RefPoint, MakeGroups)
4162 if MakeGroups: return gr,er
4165 ## Generate new elements by extrusion of the given elements
4166 # The path of extrusion must be a meshed edge.
4167 # @param IDsOfElements ids of elements
4168 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
4169 # @param PathShape shape(edge) defines the sub-mesh for the path
4170 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4171 # @param HasAngles allows the shape to be rotated around the path
4172 # to get the resulting mesh in a helical fashion
4173 # @param Angles list of angles in radians
4174 # @param HasRefPoint allows using the reference point
4175 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4176 # The User can specify any point as the Reference Point.
4177 # @param MakeGroups forces the generation of new groups from existing ones
4178 # @param LinearVariation forces the computation of rotation angles as linear
4179 # variation of the given Angles along path steps
4180 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4181 # only SMESH::Extrusion_Error otherwise
4182 # @ingroup l2_modif_extrurev
4183 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
4184 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4185 MakeGroups=False, LinearVariation=False):
4186 n,e,f = [],IDsOfElements,IDsOfElements
4187 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
4188 NodeStart, HasAngles, Angles,
4190 HasRefPoint, RefPoint, MakeGroups)
4191 if MakeGroups: return gr,er
4194 ## Generate new elements by extrusion of the elements which belong to the object
4195 # The path of extrusion must be a meshed edge.
4196 # @param theObject the object whose elements should be processed.
4197 # It can be a mesh, a sub-mesh or a group.
4198 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4199 # @param PathShape shape(edge) defines the sub-mesh for the path
4200 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4201 # @param HasAngles allows the shape to be rotated around the path
4202 # to get the resulting mesh in a helical fashion
4203 # @param Angles list of angles
4204 # @param HasRefPoint allows using the reference point
4205 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4206 # The User can specify any point as the Reference Point.
4207 # @param MakeGroups forces the generation of new groups from existing ones
4208 # @param LinearVariation forces the computation of rotation angles as linear
4209 # variation of the given Angles along path steps
4210 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4211 # only SMESH::Extrusion_Error otherwise
4212 # @ingroup l2_modif_extrurev
4213 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4214 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4215 MakeGroups=False, LinearVariation=False):
4216 n,e,f = [],theObject,theObject
4217 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4218 HasAngles, Angles, LinearVariation,
4219 HasRefPoint, RefPoint, MakeGroups)
4220 if MakeGroups: return gr,er
4223 ## Generate new elements by extrusion of mesh segments which belong to the object
4224 # The path of extrusion must be a meshed edge.
4225 # @param theObject the object whose 1D elements should be processed.
4226 # It can be a mesh, a sub-mesh or a group.
4227 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4228 # @param PathShape shape(edge) defines the sub-mesh for the path
4229 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4230 # @param HasAngles allows the shape to be rotated around the path
4231 # to get the resulting mesh in a helical fashion
4232 # @param Angles list of angles
4233 # @param HasRefPoint allows using the reference point
4234 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4235 # The User can specify any point as the Reference Point.
4236 # @param MakeGroups forces the generation of new groups from existing ones
4237 # @param LinearVariation forces the computation of rotation angles as linear
4238 # variation of the given Angles along path steps
4239 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4240 # only SMESH::Extrusion_Error otherwise
4241 # @ingroup l2_modif_extrurev
4242 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4243 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4244 MakeGroups=False, LinearVariation=False):
4245 n,e,f = [],theObject,[]
4246 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4247 HasAngles, Angles, LinearVariation,
4248 HasRefPoint, RefPoint, MakeGroups)
4249 if MakeGroups: return gr,er
4252 ## Generate new elements by extrusion of faces which belong to the object
4253 # The path of extrusion must be a meshed edge.
4254 # @param theObject the object whose 2D elements should be processed.
4255 # It can be a mesh, a sub-mesh or a group.
4256 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4257 # @param PathShape shape(edge) defines the sub-mesh for the path
4258 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4259 # @param HasAngles allows the shape to be rotated around the path
4260 # to get the resulting mesh in a helical fashion
4261 # @param Angles list of angles
4262 # @param HasRefPoint allows using the reference point
4263 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4264 # The User can specify any point as the Reference Point.
4265 # @param MakeGroups forces the generation of new groups from existing ones
4266 # @param LinearVariation forces the computation of rotation angles as linear
4267 # variation of the given Angles along path steps
4268 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4269 # only SMESH::Extrusion_Error otherwise
4270 # @ingroup l2_modif_extrurev
4271 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4272 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4273 MakeGroups=False, LinearVariation=False):
4274 n,e,f = [],[],theObject
4275 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4276 HasAngles, Angles, LinearVariation,
4277 HasRefPoint, RefPoint, MakeGroups)
4278 if MakeGroups: return gr,er
4281 ## Create a symmetrical copy of mesh elements
4282 # @param IDsOfElements list of elements ids
4283 # @param Mirror is AxisStruct or geom object(point, line, plane)
4284 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4285 # If the Mirror is a geom object this parameter is unnecessary
4286 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4287 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4288 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4289 # @ingroup l2_modif_trsf
4290 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4291 if IDsOfElements == []:
4292 IDsOfElements = self.GetElementsId()
4293 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4294 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4295 theMirrorType = Mirror._mirrorType
4297 self.mesh.SetParameters(Mirror.parameters)
4298 if Copy and MakeGroups:
4299 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4300 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4303 ## Create a new mesh by a symmetrical copy of mesh elements
4304 # @param IDsOfElements the list of elements ids
4305 # @param Mirror is AxisStruct or geom object (point, line, plane)
4306 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4307 # If the Mirror is a geom object this parameter is unnecessary
4308 # @param MakeGroups to generate new groups from existing ones
4309 # @param NewMeshName a name of the new mesh to create
4310 # @return instance of Mesh class
4311 # @ingroup l2_modif_trsf
4312 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4313 if IDsOfElements == []:
4314 IDsOfElements = self.GetElementsId()
4315 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4316 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4317 theMirrorType = Mirror._mirrorType
4319 self.mesh.SetParameters(Mirror.parameters)
4320 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4321 MakeGroups, NewMeshName)
4322 return Mesh(self.smeshpyD,self.geompyD,mesh)
4324 ## Create a symmetrical copy of the object
4325 # @param theObject mesh, submesh or group
4326 # @param Mirror AxisStruct or geom object (point, line, plane)
4327 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4328 # If the Mirror is a geom object this parameter is unnecessary
4329 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4330 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4331 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4332 # @ingroup l2_modif_trsf
4333 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4334 if ( isinstance( theObject, Mesh )):
4335 theObject = theObject.GetMesh()
4336 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4337 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4338 theMirrorType = Mirror._mirrorType
4340 self.mesh.SetParameters(Mirror.parameters)
4341 if Copy and MakeGroups:
4342 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4343 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4346 ## Create a new mesh by a symmetrical copy of the object
4347 # @param theObject mesh, submesh or group
4348 # @param Mirror AxisStruct or geom object (point, line, plane)
4349 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4350 # If the Mirror is a geom object this parameter is unnecessary
4351 # @param MakeGroups forces the generation of new groups from existing ones
4352 # @param NewMeshName the name of the new mesh to create
4353 # @return instance of Mesh class
4354 # @ingroup l2_modif_trsf
4355 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4356 if ( isinstance( theObject, Mesh )):
4357 theObject = theObject.GetMesh()
4358 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4359 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4360 theMirrorType = Mirror._mirrorType
4362 self.mesh.SetParameters(Mirror.parameters)
4363 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4364 MakeGroups, NewMeshName)
4365 return Mesh( self.smeshpyD,self.geompyD,mesh )
4367 ## Translate the elements
4368 # @param IDsOfElements list of elements ids
4369 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4370 # @param Copy allows copying the translated elements
4371 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4372 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4373 # @ingroup l2_modif_trsf
4374 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4375 if IDsOfElements == []:
4376 IDsOfElements = self.GetElementsId()
4377 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4378 Vector = self.smeshpyD.GetDirStruct(Vector)
4379 if isinstance( Vector, list ):
4380 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4381 self.mesh.SetParameters(Vector.PS.parameters)
4382 if Copy and MakeGroups:
4383 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4384 self.editor.Translate(IDsOfElements, Vector, Copy)
4387 ## Create a new mesh of translated elements
4388 # @param IDsOfElements list of elements ids
4389 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4390 # @param MakeGroups forces the generation of new groups from existing ones
4391 # @param NewMeshName the name of the newly created mesh
4392 # @return instance of Mesh class
4393 # @ingroup l2_modif_trsf
4394 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4395 if IDsOfElements == []:
4396 IDsOfElements = self.GetElementsId()
4397 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4398 Vector = self.smeshpyD.GetDirStruct(Vector)
4399 if isinstance( Vector, list ):
4400 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4401 self.mesh.SetParameters(Vector.PS.parameters)
4402 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4403 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4405 ## Translate the object
4406 # @param theObject the object to translate (mesh, submesh, or group)
4407 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4408 # @param Copy allows copying the translated elements
4409 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4410 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4411 # @ingroup l2_modif_trsf
4412 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4413 if ( isinstance( theObject, Mesh )):
4414 theObject = theObject.GetMesh()
4415 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4416 Vector = self.smeshpyD.GetDirStruct(Vector)
4417 if isinstance( Vector, list ):
4418 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4419 self.mesh.SetParameters(Vector.PS.parameters)
4420 if Copy and MakeGroups:
4421 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4422 self.editor.TranslateObject(theObject, Vector, Copy)
4425 ## Create a new mesh from the translated object
4426 # @param theObject the object to translate (mesh, submesh, or group)
4427 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4428 # @param MakeGroups forces the generation of new groups from existing ones
4429 # @param NewMeshName the name of the newly created mesh
4430 # @return instance of Mesh class
4431 # @ingroup l2_modif_trsf
4432 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4433 if isinstance( theObject, Mesh ):
4434 theObject = theObject.GetMesh()
4435 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4436 Vector = self.smeshpyD.GetDirStruct(Vector)
4437 if isinstance( Vector, list ):
4438 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4439 self.mesh.SetParameters(Vector.PS.parameters)
4440 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4441 return Mesh( self.smeshpyD, self.geompyD, mesh )
4446 # @param theObject - the object to translate (mesh, submesh, or group)
4447 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4448 # @param theScaleFact - list of 1-3 scale factors for axises
4449 # @param Copy - allows copying the translated elements
4450 # @param MakeGroups - forces the generation of new groups from existing
4452 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4453 # empty list otherwise
4454 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4455 unRegister = genObjUnRegister()
4456 if ( isinstance( theObject, Mesh )):
4457 theObject = theObject.GetMesh()
4458 if ( isinstance( theObject, list )):
4459 theObject = self.GetIDSource(theObject, SMESH.ALL)
4460 unRegister.set( theObject )
4461 if ( isinstance( thePoint, list )):
4462 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4463 if ( isinstance( theScaleFact, float )):
4464 theScaleFact = [theScaleFact]
4465 if ( isinstance( theScaleFact, int )):
4466 theScaleFact = [ float(theScaleFact)]
4468 self.mesh.SetParameters(thePoint.parameters)
4470 if Copy and MakeGroups:
4471 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4472 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4475 ## Create a new mesh from the translated object
4476 # @param theObject - the object to translate (mesh, submesh, or group)
4477 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4478 # @param theScaleFact - list of 1-3 scale factors for axises
4479 # @param MakeGroups - forces the generation of new groups from existing ones
4480 # @param NewMeshName - the name of the newly created mesh
4481 # @return instance of Mesh class
4482 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4483 unRegister = genObjUnRegister()
4484 if (isinstance(theObject, Mesh)):
4485 theObject = theObject.GetMesh()
4486 if ( isinstance( theObject, list )):
4487 theObject = self.GetIDSource(theObject,SMESH.ALL)
4488 unRegister.set( theObject )
4489 if ( isinstance( thePoint, list )):
4490 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4491 if ( isinstance( theScaleFact, float )):
4492 theScaleFact = [theScaleFact]
4493 if ( isinstance( theScaleFact, int )):
4494 theScaleFact = [ float(theScaleFact)]
4496 self.mesh.SetParameters(thePoint.parameters)
4497 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4498 MakeGroups, NewMeshName)
4499 return Mesh( self.smeshpyD, self.geompyD, mesh )
4503 ## Rotate the elements
4504 # @param IDsOfElements list of elements ids
4505 # @param Axis the axis of rotation (AxisStruct or geom line)
4506 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4507 # @param Copy allows copying the rotated elements
4508 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4509 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4510 # @ingroup l2_modif_trsf
4511 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4512 if IDsOfElements == []:
4513 IDsOfElements = self.GetElementsId()
4514 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4515 Axis = self.smeshpyD.GetAxisStruct(Axis)
4516 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4517 Parameters = Axis.parameters + var_separator + Parameters
4518 self.mesh.SetParameters(Parameters)
4519 if Copy and MakeGroups:
4520 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4521 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4524 ## Create a new mesh of rotated elements
4525 # @param IDsOfElements list of element ids
4526 # @param Axis the axis of rotation (AxisStruct or geom line)
4527 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4528 # @param MakeGroups forces the generation of new groups from existing ones
4529 # @param NewMeshName the name of the newly created mesh
4530 # @return instance of Mesh class
4531 # @ingroup l2_modif_trsf
4532 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4533 if IDsOfElements == []:
4534 IDsOfElements = self.GetElementsId()
4535 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4536 Axis = self.smeshpyD.GetAxisStruct(Axis)
4537 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4538 Parameters = Axis.parameters + var_separator + Parameters
4539 self.mesh.SetParameters(Parameters)
4540 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4541 MakeGroups, NewMeshName)
4542 return Mesh( self.smeshpyD, self.geompyD, mesh )
4544 ## Rotate the object
4545 # @param theObject the object to rotate( mesh, submesh, or group)
4546 # @param Axis the axis of rotation (AxisStruct or geom line)
4547 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4548 # @param Copy allows copying the rotated elements
4549 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4550 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4551 # @ingroup l2_modif_trsf
4552 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4553 if (isinstance(theObject, Mesh)):
4554 theObject = theObject.GetMesh()
4555 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4556 Axis = self.smeshpyD.GetAxisStruct(Axis)
4557 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4558 Parameters = Axis.parameters + ":" + Parameters
4559 self.mesh.SetParameters(Parameters)
4560 if Copy and MakeGroups:
4561 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4562 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4565 ## Create a new mesh from the rotated object
4566 # @param theObject the object to rotate (mesh, submesh, or group)
4567 # @param Axis the axis of rotation (AxisStruct or geom line)
4568 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4569 # @param MakeGroups forces the generation of new groups from existing ones
4570 # @param NewMeshName the name of the newly created mesh
4571 # @return instance of Mesh class
4572 # @ingroup l2_modif_trsf
4573 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4574 if (isinstance( theObject, Mesh )):
4575 theObject = theObject.GetMesh()
4576 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4577 Axis = self.smeshpyD.GetAxisStruct(Axis)
4578 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4579 Parameters = Axis.parameters + ":" + Parameters
4580 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4581 MakeGroups, NewMeshName)
4582 self.mesh.SetParameters(Parameters)
4583 return Mesh( self.smeshpyD, self.geompyD, mesh )
4585 ## Find groups of adjacent nodes within Tolerance.
4586 # @param Tolerance the value of tolerance
4587 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4588 # corner and medium nodes in separate groups thus preventing
4589 # their further merge.
4590 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4591 # @ingroup l2_modif_trsf
4592 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
4593 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
4595 ## Find groups of ajacent nodes within Tolerance.
4596 # @param Tolerance the value of tolerance
4597 # @param SubMeshOrGroup SubMesh, Group or Filter
4598 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4599 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4600 # corner and medium nodes in separate groups thus preventing
4601 # their further merge.
4602 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4603 # @ingroup l2_modif_trsf
4604 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
4605 exceptNodes=[], SeparateCornerAndMediumNodes=False):
4606 unRegister = genObjUnRegister()
4607 if (isinstance( SubMeshOrGroup, Mesh )):
4608 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4609 if not isinstance( exceptNodes, list ):
4610 exceptNodes = [ exceptNodes ]
4611 if exceptNodes and isinstance( exceptNodes[0], int ):
4612 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
4613 unRegister.set( exceptNodes )
4614 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
4615 exceptNodes, SeparateCornerAndMediumNodes)
4618 # @param GroupsOfNodes a list of groups of nodes IDs for merging
4619 # (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
4620 # by nodes 1 and 25 correspondingly in all elements and groups
4621 # @param NodesToKeep nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
4622 # If @a NodesToKeep does not include a node to keep for some group to merge,
4623 # then the first node in the group is kept.
4624 # @ingroup l2_modif_trsf
4625 def MergeNodes (self, GroupsOfNodes, NodesToKeep=[]):
4626 # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
4627 self.editor.MergeNodes(GroupsOfNodes,NodesToKeep)
4629 ## Find the elements built on the same nodes.
4630 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4631 # @return the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
4632 # @ingroup l2_modif_trsf
4633 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4634 if not MeshOrSubMeshOrGroup:
4635 MeshOrSubMeshOrGroup=self.mesh
4636 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4637 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4638 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4640 ## Merge elements in each given group.
4641 # @param GroupsOfElementsID a list of groups of elements IDs for merging
4642 # (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
4643 # replaced by elements 1 and 25 in all groups)
4644 # @ingroup l2_modif_trsf
4645 def MergeElements(self, GroupsOfElementsID):
4646 self.editor.MergeElements(GroupsOfElementsID)
4648 ## Leave one element and remove all other elements built on the same nodes.
4649 # @ingroup l2_modif_trsf
4650 def MergeEqualElements(self):
4651 self.editor.MergeEqualElements()
4653 ## Return groups of FreeBorder's coincident within the given tolerance.
4654 # @param tolerance the tolerance. If the tolerance <= 0.0 then one tenth of an average
4655 # size of elements adjacent to free borders being compared is used.
4656 # @return SMESH.CoincidentFreeBorders structure
4657 # @ingroup l2_modif_trsf
4658 def FindCoincidentFreeBorders (self, tolerance=0.):
4659 return self.editor.FindCoincidentFreeBorders( tolerance )
4661 ## Sew FreeBorder's of each group
4662 # @param freeBorders either a SMESH.CoincidentFreeBorders structure or a list of lists
4663 # where each enclosed list contains node IDs of a group of coincident free
4664 # borders such that each consequent triple of IDs within a group describes
4665 # a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
4666 # last node of a border.
4667 # For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
4668 # groups of coincident free borders, each group including two borders.
4669 # @param createPolygons if @c True faces adjacent to free borders are converted to
4670 # polygons if a node of opposite border falls on a face edge, else such
4671 # faces are split into several ones.
4672 # @param createPolyhedra if @c True volumes adjacent to free borders are converted to
4673 # polyhedra if a node of opposite border falls on a volume edge, else such
4674 # volumes, if any, remain intact and the mesh becomes non-conformal.
4675 # @return a number of successfully sewed groups
4676 # @ingroup l2_modif_trsf
4677 def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
4678 if freeBorders and isinstance( freeBorders, list ):
4679 # construct SMESH.CoincidentFreeBorders
4680 if isinstance( freeBorders[0], int ):
4681 freeBorders = [freeBorders]
4683 coincidentGroups = []
4684 for nodeList in freeBorders:
4685 if not nodeList or len( nodeList ) % 3:
4686 raise ValueError, "Wrong number of nodes in this group: %s" % nodeList
4689 group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
4690 borders.append( SMESH.FreeBorder( nodeList[:3] ))
4691 nodeList = nodeList[3:]
4693 coincidentGroups.append( group )
4695 freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
4697 return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
4700 # @return SMESH::Sew_Error
4701 # @ingroup l2_modif_trsf
4702 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4703 FirstNodeID2, SecondNodeID2, LastNodeID2,
4704 CreatePolygons, CreatePolyedrs):
4705 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4706 FirstNodeID2, SecondNodeID2, LastNodeID2,
4707 CreatePolygons, CreatePolyedrs)
4709 ## Sew conform free borders
4710 # @return SMESH::Sew_Error
4711 # @ingroup l2_modif_trsf
4712 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4713 FirstNodeID2, SecondNodeID2):
4714 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4715 FirstNodeID2, SecondNodeID2)
4717 ## Sew border to side
4718 # @return SMESH::Sew_Error
4719 # @ingroup l2_modif_trsf
4720 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4721 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4722 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4723 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4725 ## Sew two sides of a mesh. The nodes belonging to Side1 are
4726 # merged with the nodes of elements of Side2.
4727 # The number of elements in theSide1 and in theSide2 must be
4728 # equal and they should have similar nodal connectivity.
4729 # The nodes to merge should belong to side borders and
4730 # the first node should be linked to the second.
4731 # @return SMESH::Sew_Error
4732 # @ingroup l2_modif_trsf
4733 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4734 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4735 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4736 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4737 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4738 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4740 ## Set new nodes for the given element.
4741 # @param ide the element id
4742 # @param newIDs nodes ids
4743 # @return If the number of nodes does not correspond to the type of element - return false
4744 # @ingroup l2_modif_edit
4745 def ChangeElemNodes(self, ide, newIDs):
4746 return self.editor.ChangeElemNodes(ide, newIDs)
4748 ## If during the last operation of MeshEditor some nodes were
4749 # created, this method return the list of their IDs, \n
4750 # if new nodes were not created - return empty list
4751 # @return the list of integer values (can be empty)
4752 # @ingroup l2_modif_add
4753 def GetLastCreatedNodes(self):
4754 return self.editor.GetLastCreatedNodes()
4756 ## If during the last operation of MeshEditor some elements were
4757 # created this method return the list of their IDs, \n
4758 # if new elements were not created - return empty list
4759 # @return the list of integer values (can be empty)
4760 # @ingroup l2_modif_add
4761 def GetLastCreatedElems(self):
4762 return self.editor.GetLastCreatedElems()
4764 ## Forget what nodes and elements were created by the last mesh edition operation
4765 # @ingroup l2_modif_add
4766 def ClearLastCreated(self):
4767 self.editor.ClearLastCreated()
4769 ## Create duplicates of given elements, i.e. create new elements based on the
4770 # same nodes as the given ones.
4771 # @param theElements - container of elements to duplicate. It can be a Mesh,
4772 # sub-mesh, group, filter or a list of element IDs. If \a theElements is
4773 # a Mesh, elements of highest dimension are duplicated
4774 # @param theGroupName - a name of group to contain the generated elements.
4775 # If a group with such a name already exists, the new elements
4776 # are added to the existng group, else a new group is created.
4777 # If \a theGroupName is empty, new elements are not added
4779 # @return a group where the new elements are added. None if theGroupName == "".
4780 # @ingroup l2_modif_duplicat
4781 def DoubleElements(self, theElements, theGroupName=""):
4782 unRegister = genObjUnRegister()
4783 if isinstance( theElements, Mesh ):
4784 theElements = theElements.mesh
4785 elif isinstance( theElements, list ):
4786 theElements = self.GetIDSource( theElements, SMESH.ALL )
4787 unRegister.set( theElements )
4788 return self.editor.DoubleElements(theElements, theGroupName)
4790 ## Create a hole in a mesh by doubling the nodes of some particular elements
4791 # @param theNodes identifiers of nodes to be doubled
4792 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4793 # nodes. If list of element identifiers is empty then nodes are doubled but
4794 # they not assigned to elements
4795 # @return TRUE if operation has been completed successfully, FALSE otherwise
4796 # @ingroup l2_modif_duplicat
4797 def DoubleNodes(self, theNodes, theModifiedElems):
4798 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4800 ## Create a hole in a mesh by doubling the nodes of some particular elements
4801 # This method provided for convenience works as DoubleNodes() described above.
4802 # @param theNodeId identifiers of node to be doubled
4803 # @param theModifiedElems identifiers of elements to be updated
4804 # @return TRUE if operation has been completed successfully, FALSE otherwise
4805 # @ingroup l2_modif_duplicat
4806 def DoubleNode(self, theNodeId, theModifiedElems):
4807 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4809 ## Create a hole in a mesh by doubling the nodes of some particular elements
4810 # This method provided for convenience works as DoubleNodes() described above.
4811 # @param theNodes group of nodes to be doubled
4812 # @param theModifiedElems group of elements to be updated.
4813 # @param theMakeGroup forces the generation of a group containing new nodes.
4814 # @return TRUE or a created group if operation has been completed successfully,
4815 # FALSE or None otherwise
4816 # @ingroup l2_modif_duplicat
4817 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4819 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4820 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4822 ## Create a hole in a mesh by doubling the nodes of some particular elements
4823 # This method provided for convenience works as DoubleNodes() described above.
4824 # @param theNodes list of groups of nodes to be doubled
4825 # @param theModifiedElems list of groups of elements to be updated.
4826 # @param theMakeGroup forces the generation of a group containing new nodes.
4827 # @return TRUE if operation has been completed successfully, FALSE otherwise
4828 # @ingroup l2_modif_duplicat
4829 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4831 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4832 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4834 ## Create a hole in a mesh by doubling the nodes of some particular elements
4835 # @param theElems - the list of elements (edges or faces) to be replicated
4836 # The nodes for duplication could be found from these elements
4837 # @param theNodesNot - list of nodes to NOT replicate
4838 # @param theAffectedElems - the list of elements (cells and edges) to which the
4839 # replicated nodes should be associated to.
4840 # @return TRUE if operation has been completed successfully, FALSE otherwise
4841 # @ingroup l2_modif_duplicat
4842 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4843 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4845 ## Create a hole in a mesh by doubling the nodes of some particular elements
4846 # @param theElems - the list of elements (edges or faces) to be replicated
4847 # The nodes for duplication could be found from these elements
4848 # @param theNodesNot - list of nodes to NOT replicate
4849 # @param theShape - shape to detect affected elements (element which geometric center
4850 # located on or inside shape).
4851 # The replicated nodes should be associated to affected elements.
4852 # @return TRUE if operation has been completed successfully, FALSE otherwise
4853 # @ingroup l2_modif_duplicat
4854 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4855 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4857 ## Create a hole in a mesh by doubling the nodes of some particular elements
4858 # This method provided for convenience works as DoubleNodes() described above.
4859 # @param theElems - group of of elements (edges or faces) to be replicated
4860 # @param theNodesNot - group of nodes not to replicated
4861 # @param theAffectedElems - group of elements to which the replicated nodes
4862 # should be associated to.
4863 # @param theMakeGroup forces the generation of a group containing new elements.
4864 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4865 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4866 # FALSE or None otherwise
4867 # @ingroup l2_modif_duplicat
4868 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4869 theMakeGroup=False, theMakeNodeGroup=False):
4870 if theMakeGroup or theMakeNodeGroup:
4871 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4873 theMakeGroup, theMakeNodeGroup)
4874 if theMakeGroup and theMakeNodeGroup:
4877 return twoGroups[ int(theMakeNodeGroup) ]
4878 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4880 ## Create a hole in a mesh by doubling the nodes of some particular elements
4881 # This method provided for convenience works as DoubleNodes() described above.
4882 # @param theElems - group of of elements (edges or faces) to be replicated
4883 # @param theNodesNot - group of nodes not to replicated
4884 # @param theShape - shape to detect affected elements (element which geometric center
4885 # located on or inside shape).
4886 # The replicated nodes should be associated to affected elements.
4887 # @ingroup l2_modif_duplicat
4888 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4889 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4891 ## Create a hole in a mesh by doubling the nodes of some particular elements
4892 # This method provided for convenience works as DoubleNodes() described above.
4893 # @param theElems - list of groups of elements (edges or faces) to be replicated
4894 # @param theNodesNot - list of groups of nodes not to replicated
4895 # @param theAffectedElems - group of elements to which the replicated nodes
4896 # should be associated to.
4897 # @param theMakeGroup forces the generation of a group containing new elements.
4898 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4899 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4900 # FALSE or None otherwise
4901 # @ingroup l2_modif_duplicat
4902 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4903 theMakeGroup=False, theMakeNodeGroup=False):
4904 if theMakeGroup or theMakeNodeGroup:
4905 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4907 theMakeGroup, theMakeNodeGroup)
4908 if theMakeGroup and theMakeNodeGroup:
4911 return twoGroups[ int(theMakeNodeGroup) ]
4912 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4914 ## Create a hole in a mesh by doubling the nodes of some particular elements
4915 # This method provided for convenience works as DoubleNodes() described above.
4916 # @param theElems - list of groups of elements (edges or faces) to be replicated
4917 # @param theNodesNot - list of groups of nodes not to replicated
4918 # @param theShape - shape to detect affected elements (element which geometric center
4919 # located on or inside shape).
4920 # The replicated nodes should be associated to affected elements.
4921 # @return TRUE if operation has been completed successfully, FALSE otherwise
4922 # @ingroup l2_modif_duplicat
4923 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4924 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4926 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4927 # This method is the first step of DoubleNodeElemGroupsInRegion.
4928 # @param theElems - list of groups of elements (edges or faces) to be replicated
4929 # @param theNodesNot - list of groups of nodes not to replicated
4930 # @param theShape - shape to detect affected elements (element which geometric center
4931 # located on or inside shape).
4932 # The replicated nodes should be associated to affected elements.
4933 # @return groups of affected elements
4934 # @ingroup l2_modif_duplicat
4935 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4936 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4938 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4939 # The list of groups must describe a partition of the mesh volumes.
4940 # The nodes of the internal faces at the boundaries of the groups are doubled.
4941 # In option, the internal faces are replaced by flat elements.
4942 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4943 # @param theDomains - list of groups of volumes
4944 # @param createJointElems - if TRUE, create the elements
4945 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4946 # the boundary between \a theDomains and the rest mesh
4947 # @return TRUE if operation has been completed successfully, FALSE otherwise
4948 # @ingroup l2_modif_duplicat
4949 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4950 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4952 ## Double nodes on some external faces and create flat elements.
4953 # Flat elements are mainly used by some types of mechanic calculations.
4955 # Each group of the list must be constituted of faces.
4956 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4957 # @param theGroupsOfFaces - list of groups of faces
4958 # @return TRUE if operation has been completed successfully, FALSE otherwise
4959 # @ingroup l2_modif_duplicat
4960 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4961 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4963 ## identify all the elements around a geom shape, get the faces delimiting the hole
4965 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4966 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4968 def _getFunctor(self, funcType ):
4969 fn = self.functors[ funcType._v ]
4971 fn = self.smeshpyD.GetFunctor(funcType)
4972 fn.SetMesh(self.mesh)
4973 self.functors[ funcType._v ] = fn
4976 ## Return value of a functor for a given element
4977 # @param funcType an item of SMESH.FunctorType enum
4978 # Type "SMESH.FunctorType._items" in the Python Console to see all items.
4979 # @param elemId element or node ID
4980 # @param isElem @a elemId is ID of element or node
4981 # @return the functor value or zero in case of invalid arguments
4982 # @ingroup l1_measurements
4983 def FunctorValue(self, funcType, elemId, isElem=True):
4984 fn = self._getFunctor( funcType )
4985 if fn.GetElementType() == self.GetElementType(elemId, isElem):
4986 val = fn.GetValue(elemId)
4991 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4992 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4993 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4994 # @ingroup l1_measurements
4995 def GetLength(self, elemId=None):
4998 length = self.smeshpyD.GetLength(self)
5000 length = self.FunctorValue(SMESH.FT_Length, elemId)
5003 ## Get area of 2D element or sum of areas of all 2D mesh elements
5004 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
5005 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
5006 # @ingroup l1_measurements
5007 def GetArea(self, elemId=None):
5010 area = self.smeshpyD.GetArea(self)
5012 area = self.FunctorValue(SMESH.FT_Area, elemId)
5015 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
5016 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
5017 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
5018 # @ingroup l1_measurements
5019 def GetVolume(self, elemId=None):
5022 volume = self.smeshpyD.GetVolume(self)
5024 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
5027 ## Get maximum element length.
5028 # @param elemId mesh element ID
5029 # @return element's maximum length value
5030 # @ingroup l1_measurements
5031 def GetMaxElementLength(self, elemId):
5032 if self.GetElementType(elemId, True) == SMESH.VOLUME:
5033 ftype = SMESH.FT_MaxElementLength3D
5035 ftype = SMESH.FT_MaxElementLength2D
5036 return self.FunctorValue(ftype, elemId)
5038 ## Get aspect ratio of 2D or 3D element.
5039 # @param elemId mesh element ID
5040 # @return element's aspect ratio value
5041 # @ingroup l1_measurements
5042 def GetAspectRatio(self, elemId):
5043 if self.GetElementType(elemId, True) == SMESH.VOLUME:
5044 ftype = SMESH.FT_AspectRatio3D
5046 ftype = SMESH.FT_AspectRatio
5047 return self.FunctorValue(ftype, elemId)
5049 ## Get warping angle of 2D element.
5050 # @param elemId mesh element ID
5051 # @return element's warping angle value
5052 # @ingroup l1_measurements
5053 def GetWarping(self, elemId):
5054 return self.FunctorValue(SMESH.FT_Warping, elemId)
5056 ## Get minimum angle of 2D element.
5057 # @param elemId mesh element ID
5058 # @return element's minimum angle value
5059 # @ingroup l1_measurements
5060 def GetMinimumAngle(self, elemId):
5061 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
5063 ## Get taper of 2D element.
5064 # @param elemId mesh element ID
5065 # @return element's taper value
5066 # @ingroup l1_measurements
5067 def GetTaper(self, elemId):
5068 return self.FunctorValue(SMESH.FT_Taper, elemId)
5070 ## Get skew of 2D element.
5071 # @param elemId mesh element ID
5072 # @return element's skew value
5073 # @ingroup l1_measurements
5074 def GetSkew(self, elemId):
5075 return self.FunctorValue(SMESH.FT_Skew, elemId)
5077 ## Return minimal and maximal value of a given functor.
5078 # @param funType a functor type, an item of SMESH.FunctorType enum
5079 # (one of SMESH.FunctorType._items)
5080 # @param meshPart a part of mesh (group, sub-mesh) to treat
5081 # @return tuple (min,max)
5082 # @ingroup l1_measurements
5083 def GetMinMax(self, funType, meshPart=None):
5084 unRegister = genObjUnRegister()
5085 if isinstance( meshPart, list ):
5086 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
5087 unRegister.set( meshPart )
5088 if isinstance( meshPart, Mesh ):
5089 meshPart = meshPart.mesh
5090 fun = self._getFunctor( funType )
5093 if hasattr( meshPart, "SetMesh" ):
5094 meshPart.SetMesh( self.mesh ) # set mesh to filter
5095 hist = fun.GetLocalHistogram( 1, False, meshPart )
5097 hist = fun.GetHistogram( 1, False )
5099 return hist[0].min, hist[0].max
5102 pass # end of Mesh class
5105 ## Private class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
5106 # with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
5108 class meshProxy(SMESH._objref_SMESH_Mesh):
5110 SMESH._objref_SMESH_Mesh.__init__(self)
5111 def __deepcopy__(self, memo=None):
5112 new = self.__class__()
5114 def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
5115 if len( args ) == 3:
5116 args += SMESH.ALL_NODES, True
5117 return SMESH._objref_SMESH_Mesh.CreateDimGroup(self, *args)
5118 def ExportToMEDX(self, *args): # function removed
5119 print "WARNING: ExportToMEDX() is deprecated, use ExportMED() instead"
5120 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5121 SMESH._objref_SMESH_Mesh.ExportMED(self, *args)
5122 def ExportToMED(self, *args): # function removed
5123 print "WARNING: ExportToMED() is deprecated, use ExportMED() instead"
5124 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5125 while len(args) < 4: # !!!! nb of parameters for ExportToMED IDL's method
5127 SMESH._objref_SMESH_Mesh.ExportMED(self, *args)
5128 def ExportPartToMED(self, *args): # 'version' parameter removed
5129 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5130 SMESH._objref_SMESH_Mesh.ExportPartToMED(self, *args)
5131 def ExportMED(self, *args): # signature of method changed
5132 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5133 while len(args) < 4: # !!!! nb of parameters for ExportToMED IDL's method
5135 SMESH._objref_SMESH_Mesh.ExportMED(self, *args)
5137 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
5140 ## Private class wrapping SMESH.SMESH_SubMesh in order to add Compute()
5142 class submeshProxy(SMESH._objref_SMESH_subMesh):
5144 SMESH._objref_SMESH_subMesh.__init__(self)
5146 def __deepcopy__(self, memo=None):
5147 new = self.__class__()
5150 ## Compute the sub-mesh and return the status of the computation
5151 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
5152 # @return True or False
5154 # This is a method of SMESH.SMESH_submesh that can be obtained via Mesh.GetSubMesh() or
5155 # @ref smesh_algorithm.Mesh_Algorithm.GetSubMesh() "Mesh_Algorithm.GetSubMesh()".
5156 # @ingroup l2_submeshes
5157 def Compute(self,refresh=False):
5159 self.mesh = Mesh( smeshBuilder(), None, self.GetMesh())
5161 ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
5163 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
5164 smeshgui = salome.ImportComponentGUI("SMESH")
5165 smeshgui.Init(self.mesh.GetStudyId())
5166 smeshgui.SetMeshIcon( salome.ObjectToID( self ), ok, (self.GetNumberOfElements()==0) )
5167 if refresh: salome.sg.updateObjBrowser(True)
5172 omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy)
5175 ## Private class used to compensate change of CORBA API of SMESH_MeshEditor for backward
5176 # compatibility with old dump scripts which call SMESH_MeshEditor directly and not via
5179 class meshEditor(SMESH._objref_SMESH_MeshEditor):
5181 SMESH._objref_SMESH_MeshEditor.__init__(self)
5183 def __getattr__(self, name ): # method called if an attribute not found
5184 if not self.mesh: # look for name() method in Mesh class
5185 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
5186 if hasattr( self.mesh, name ):
5187 return getattr( self.mesh, name )
5188 if name == "ExtrusionAlongPathObjX":
5189 return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
5190 print "meshEditor: attribute '%s' NOT FOUND" % name
5192 def __deepcopy__(self, memo=None):
5193 new = self.__class__()
5195 def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
5196 if len( args ) == 1: args += False,
5197 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
5198 def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
5199 if len( args ) == 2: args += False,
5200 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
5201 def MergeNodes(self,*args): # a 2nd arg added (NodesToKeep)
5202 if len( args ) == 1:
5203 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [] )
5204 NodesToKeep = args[1]
5205 unRegister = genObjUnRegister()
5207 if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
5208 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
5209 if not isinstance( NodesToKeep, list ):
5210 NodesToKeep = [ NodesToKeep ]
5211 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep )
5213 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
5215 ## Private class wrapping SMESH.SMESH_Pattern CORBA class in order to treat Notebook
5216 # variables in some methods
5218 class Pattern(SMESH._objref_SMESH_Pattern):
5220 def LoadFromFile(self, patternTextOrFile ):
5221 text = patternTextOrFile
5222 if os.path.exists( text ):
5223 text = open( patternTextOrFile ).read()
5225 return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
5227 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
5228 decrFun = lambda i: i-1
5229 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
5230 theMesh.SetParameters(Parameters)
5231 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
5233 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
5234 decrFun = lambda i: i-1
5235 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
5236 theMesh.SetParameters(Parameters)
5237 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
5239 def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
5240 if isinstance( mesh, Mesh ):
5241 mesh = mesh.GetMesh()
5242 return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
5244 # Registering the new proxy for Pattern
5245 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
5247 ## Private class used to bind methods creating algorithms to the class Mesh
5252 self.defaultAlgoType = ""
5253 self.algoTypeToClass = {}
5255 # Store a python class of algorithm
5256 def add(self, algoClass):
5257 if type( algoClass ).__name__ == 'classobj' and \
5258 hasattr( algoClass, "algoType"):
5259 self.algoTypeToClass[ algoClass.algoType ] = algoClass
5260 if not self.defaultAlgoType and \
5261 hasattr( algoClass, "isDefault") and algoClass.isDefault:
5262 self.defaultAlgoType = algoClass.algoType
5263 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
5265 # Create a copy of self and assign mesh to the copy
5266 def copy(self, mesh):
5267 other = algoCreator()
5268 other.defaultAlgoType = self.defaultAlgoType
5269 other.algoTypeToClass = self.algoTypeToClass
5273 # Create an instance of algorithm
5274 def __call__(self,algo="",geom=0,*args):
5275 algoType = self.defaultAlgoType
5276 for arg in args + (algo,geom):
5277 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
5279 if isinstance( arg, str ) and arg:
5281 if not algoType and self.algoTypeToClass:
5282 algoType = self.algoTypeToClass.keys()[0]
5283 if self.algoTypeToClass.has_key( algoType ):
5284 #print "Create algo",algoType
5285 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
5286 raise RuntimeError, "No class found for algo type %s" % algoType
5289 ## Private class used to substitute and store variable parameters of hypotheses.
5291 class hypMethodWrapper:
5292 def __init__(self, hyp, method):
5294 self.method = method
5295 #print "REBIND:", method.__name__
5298 # call a method of hypothesis with calling SetVarParameter() before
5299 def __call__(self,*args):
5301 return self.method( self.hyp, *args ) # hypothesis method with no args
5303 #print "MethWrapper.__call__",self.method.__name__, args
5305 parsed = ParseParameters(*args) # replace variables with their values
5306 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
5307 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
5308 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
5309 # maybe there is a replaced string arg which is not variable
5310 result = self.method( self.hyp, *args )
5311 except ValueError, detail: # raised by ParseParameters()
5313 result = self.method( self.hyp, *args )
5314 except omniORB.CORBA.BAD_PARAM:
5315 raise ValueError, detail # wrong variable name
5320 ## A helper class that calls UnRegister() of SALOME.GenericObj'es stored in it
5322 class genObjUnRegister:
5324 def __init__(self, genObj=None):
5325 self.genObjList = []
5329 def set(self, genObj):
5330 "Store one or a list of of SALOME.GenericObj'es"
5331 if isinstance( genObj, list ):
5332 self.genObjList.extend( genObj )
5334 self.genObjList.append( genObj )
5338 for genObj in self.genObjList:
5339 if genObj and hasattr( genObj, "UnRegister" ):
5343 ## Bind methods creating mesher plug-ins to the Mesh class
5345 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
5347 #print "pluginName: ", pluginName
5348 pluginBuilderName = pluginName + "Builder"
5350 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
5351 except Exception, e:
5352 from salome_utils import verbose
5353 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
5355 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5356 plugin = eval( pluginBuilderName )
5357 #print " plugin:" , str(plugin)
5359 # add methods creating algorithms to Mesh
5360 for k in dir( plugin ):
5361 if k[0] == '_': continue
5362 algo = getattr( plugin, k )
5363 #print " algo:", str(algo)
5364 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
5365 #print " meshMethod:" , str(algo.meshMethod)
5366 if not hasattr( Mesh, algo.meshMethod ):
5367 setattr( Mesh, algo.meshMethod, algoCreator() )
5369 getattr( Mesh, algo.meshMethod ).add( algo )