1 # Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 # File : smeshBuilder.py
20 # Author : Francis KLOSS, OCC
23 ## @package smeshBuilder
24 # Python API for SALOME %Mesh module
26 ## @defgroup l1_auxiliary Auxiliary methods and structures
27 ## @defgroup l1_creating Creating meshes
29 ## @defgroup l2_impexp Importing and exporting meshes
32 ## These are methods of class \ref smeshBuilder.smeshBuilder "smeshBuilder"
34 ## @defgroup l2_construct Constructing meshes
35 ## @defgroup l2_algorithms Defining Algorithms
37 ## @defgroup l3_algos_basic Basic meshing algorithms
38 ## @defgroup l3_algos_proj Projection Algorithms
39 ## @defgroup l3_algos_segmarv Segments around Vertex
40 ## @defgroup l3_algos_3dextr 3D extrusion meshing algorithm
43 ## @defgroup l2_hypotheses Defining hypotheses
45 ## @defgroup l3_hypos_1dhyps 1D Meshing Hypotheses
46 ## @defgroup l3_hypos_2dhyps 2D Meshing Hypotheses
47 ## @defgroup l3_hypos_maxvol Max Element Volume hypothesis
48 ## @defgroup l3_hypos_quad Quadrangle Parameters hypothesis
49 ## @defgroup l3_hypos_additi Additional Hypotheses
52 ## @defgroup l2_submeshes Constructing sub-meshes
53 ## @defgroup l2_editing Editing Meshes
56 ## @defgroup l1_meshinfo Mesh Information
57 ## @defgroup l1_controls Quality controls and Filtering
58 ## @defgroup l1_grouping Grouping elements
60 ## @defgroup l2_grps_create Creating groups
61 ## @defgroup l2_grps_operon Using operations on groups
62 ## @defgroup l2_grps_delete Deleting Groups
65 ## @defgroup l1_modifying Modifying meshes
67 ## @defgroup l2_modif_add Adding nodes and elements
68 ## @defgroup l2_modif_del Removing nodes and elements
69 ## @defgroup l2_modif_edit Modifying nodes and elements
70 ## @defgroup l2_modif_renumber Renumbering nodes and elements
71 ## @defgroup l2_modif_trsf Transforming meshes (Translation, Rotation, Symmetry, Sewing, Merging)
72 ## @defgroup l2_modif_unitetri Uniting triangles
73 ## @defgroup l2_modif_cutquadr Cutting elements
74 ## @defgroup l2_modif_changori Changing orientation of elements
75 ## @defgroup l2_modif_smooth Smoothing
76 ## @defgroup l2_modif_extrurev Extrusion and Revolution
77 ## @defgroup l2_modif_tofromqu Convert to/from Quadratic Mesh
78 ## @defgroup l2_modif_duplicat Duplication of nodes and elements (to emulate cracks)
81 ## @defgroup l1_measurements Measurements
84 from salome.geom import geomBuilder
86 import SMESH # This is necessary for back compatibility
88 from salome.smesh.smesh_algorithm import Mesh_Algorithm
94 ## Private class used to workaround a problem that sometimes isinstance(m, Mesh) returns False
97 def __instancecheck__(cls, inst):
98 """Implement isinstance(inst, cls)."""
99 return any(cls.__subclasscheck__(c)
100 for c in {type(inst), inst.__class__})
102 def __subclasscheck__(cls, sub):
103 """Implement issubclass(sub, cls)."""
104 return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
106 ## @addtogroup l1_auxiliary
109 ## Convert an angle from degrees to radians
110 def DegreesToRadians(AngleInDegrees):
112 return AngleInDegrees * pi / 180.0
114 import salome_notebook
115 notebook = salome_notebook.notebook
116 # Salome notebook variable separator
119 ## Return list of variable values from salome notebook.
120 # The last argument, if is callable, is used to modify values got from notebook
121 def ParseParameters(*args):
126 if args and callable( args[-1] ):
127 args, varModifFun = args[:-1], args[-1]
128 for parameter in args:
130 Parameters += str(parameter) + var_separator
132 if isinstance(parameter,str):
133 # check if there is an inexistent variable name
134 if not notebook.isVariable(parameter):
135 raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
136 parameter = notebook.get(parameter)
139 parameter = varModifFun(parameter)
142 Result.append(parameter)
145 Parameters = Parameters[:-1]
146 Result.append( Parameters )
147 Result.append( hasVariables )
150 ## Parse parameters while converting variables to radians
151 def ParseAngles(*args):
152 return ParseParameters( *( args + (DegreesToRadians, )))
154 ## Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
155 # Parameters are stored in PointStruct.parameters attribute
156 def __initPointStruct(point,*args):
157 point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
159 SMESH.PointStruct.__init__ = __initPointStruct
161 ## Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
162 # Parameters are stored in AxisStruct.parameters attribute
163 def __initAxisStruct(ax,*args):
166 "Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args ))
167 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
169 SMESH.AxisStruct.__init__ = __initAxisStruct
171 smeshPrecisionConfusion = 1.e-07
172 ## Compare real values using smeshPrecisionConfusion as tolerance
173 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
174 if abs(val1 - val2) < tol:
180 ## Return object name
184 if isinstance(obj, SALOMEDS._objref_SObject):
188 ior = salome.orb.object_to_string(obj)
193 studies = salome.myStudyManager.GetOpenStudies()
194 for sname in studies:
195 s = salome.myStudyManager.GetStudyByName(sname)
197 sobj = s.FindObjectIOR(ior)
198 if not sobj: continue
199 return sobj.GetName()
200 if hasattr(obj, "GetName"):
201 # unknown CORBA object, having GetName() method
204 # unknown CORBA object, no GetName() method
207 if hasattr(obj, "GetName"):
208 # unknown non-CORBA object, having GetName() method
211 raise RuntimeError, "Null or invalid object"
213 ## Print error message if a hypothesis was not assigned.
214 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
216 hypType = "algorithm"
218 hypType = "hypothesis"
221 if hasattr( status, "__getitem__" ):
222 status,reason = status[0],status[1]
223 if status == HYP_UNKNOWN_FATAL :
224 reason = "for unknown reason"
225 elif status == HYP_INCOMPATIBLE :
226 reason = "this hypothesis mismatches the algorithm"
227 elif status == HYP_NOTCONFORM :
228 reason = "a non-conform mesh would be built"
229 elif status == HYP_ALREADY_EXIST :
230 if isAlgo: return # it does not influence anything
231 reason = hypType + " of the same dimension is already assigned to this shape"
232 elif status == HYP_BAD_DIM :
233 reason = hypType + " mismatches the shape"
234 elif status == HYP_CONCURENT :
235 reason = "there are concurrent hypotheses on sub-shapes"
236 elif status == HYP_BAD_SUBSHAPE :
237 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
238 elif status == HYP_BAD_GEOMETRY:
239 reason = "the algorithm is not applicable to this geometry"
240 elif status == HYP_HIDDEN_ALGO:
241 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
242 elif status == HYP_HIDING_ALGO:
243 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
244 elif status == HYP_NEED_SHAPE:
245 reason = "algorithm can't work without shape"
246 elif status == HYP_INCOMPAT_HYPS:
252 where = '"%s"' % geomName
254 meshName = GetName( mesh )
255 if meshName and meshName != NO_NAME:
256 where = '"%s" shape in "%s" mesh ' % ( geomName, meshName )
257 if status < HYP_UNKNOWN_FATAL and where:
258 print '"%s" was assigned to %s but %s' %( hypName, where, reason )
260 print '"%s" was not assigned to %s : %s' %( hypName, where, reason )
262 print '"%s" was not assigned : %s' %( hypName, reason )
265 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
266 def AssureGeomPublished(mesh, geom, name=''):
267 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
269 if not geom.GetStudyEntry() and \
270 mesh.smeshpyD.GetCurrentStudy():
272 studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
273 if studyID != mesh.geompyD.myStudyId:
274 mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
276 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
277 # for all groups SubShapeName() return "Compound_-1"
278 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
280 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
282 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
285 ## Return the first vertex of a geometrical edge by ignoring orientation
286 def FirstVertexOnCurve(mesh, edge):
287 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
289 raise TypeError, "Given object has no vertices"
290 if len( vv ) == 1: return vv[0]
291 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
292 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
293 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
294 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
297 dist1 += abs( xyz[i] - xyz1[i] )
298 dist2 += abs( xyz[i] - xyz2[i] )
304 # end of l1_auxiliary
308 # Warning: smeshInst is a singleton
314 ## This class allows to create, load or manipulate meshes.
315 # It has a set of methods to create, load or copy meshes, to combine several meshes, etc.
316 # It also has methods to get infos and measure meshes.
317 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
319 # MirrorType enumeration
320 POINT = SMESH_MeshEditor.POINT
321 AXIS = SMESH_MeshEditor.AXIS
322 PLANE = SMESH_MeshEditor.PLANE
324 # Smooth_Method enumeration
325 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
326 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
328 PrecisionConfusion = smeshPrecisionConfusion
330 # TopAbs_State enumeration
331 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
333 # Methods of splitting a hexahedron into tetrahedra
334 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
340 #print "==== __new__", engine, smeshInst, doLcc
342 if smeshInst is None:
343 # smesh engine is either retrieved from engine, or created
345 # Following test avoids a recursive loop
347 if smeshInst is not None:
348 # smesh engine not created: existing engine found
352 # FindOrLoadComponent called:
353 # 1. CORBA resolution of server
354 # 2. the __new__ method is called again
355 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
356 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
358 # FindOrLoadComponent not called
359 if smeshInst is None:
360 # smeshBuilder instance is created from lcc.FindOrLoadComponent
361 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
362 smeshInst = super(smeshBuilder,cls).__new__(cls)
364 # smesh engine not created: existing engine found
365 #print "==== existing ", engine, smeshInst, doLcc
367 #print "====1 ", smeshInst
370 #print "====2 ", smeshInst
375 #print "--------------- smeshbuilder __init__ ---", created
378 SMESH._objref_SMESH_Gen.__init__(self)
380 ## Dump component to the Python script
381 # This method overrides IDL function to allow default values for the parameters.
382 # @ingroup l1_auxiliary
383 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
384 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
386 ## Set mode of DumpPython(), \a historical or \a snapshot.
387 # In the \a historical mode, the Python Dump script includes all commands
388 # performed by SMESH engine. In the \a snapshot mode, commands
389 # relating to objects removed from the Study are excluded from the script
390 # as well as commands not influencing the current state of meshes
391 # @ingroup l1_auxiliary
392 def SetDumpPythonHistorical(self, isHistorical):
393 if isHistorical: val = "true"
395 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
397 ## Set the current study and Geometry component
398 # @ingroup l1_auxiliary
399 def init_smesh(self,theStudy,geompyD = None):
401 self.SetCurrentStudy(theStudy,geompyD)
404 notebook.myStudy = theStudy
406 ## Create a mesh. This can be either an empty mesh, possibly having an underlying geometry,
407 # or a mesh wrapping a CORBA mesh given as a parameter.
408 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
409 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
410 # (2) a Geometrical object for meshing or
412 # @param name the name for the new mesh.
413 # @return an instance of Mesh class.
414 # @ingroup l2_construct
415 def Mesh(self, obj=0, name=0):
416 if isinstance(obj,str):
418 return Mesh(self,self.geompyD,obj,name)
420 ## Return a long value from enumeration
421 # @ingroup l1_auxiliary
422 def EnumToLong(self,theItem):
425 ## Return a string representation of the color.
426 # To be used with filters.
427 # @param c color value (SALOMEDS.Color)
428 # @ingroup l1_auxiliary
429 def ColorToString(self,c):
431 if isinstance(c, SALOMEDS.Color):
432 val = "%s;%s;%s" % (c.R, c.G, c.B)
433 elif isinstance(c, str):
436 raise ValueError, "Color value should be of string or SALOMEDS.Color type"
439 ## Get PointStruct from vertex
440 # @param theVertex a GEOM object(vertex)
441 # @return SMESH.PointStruct
442 # @ingroup l1_auxiliary
443 def GetPointStruct(self,theVertex):
444 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
445 return PointStruct(x,y,z)
447 ## Get DirStruct from vector
448 # @param theVector a GEOM object(vector)
449 # @return SMESH.DirStruct
450 # @ingroup l1_auxiliary
451 def GetDirStruct(self,theVector):
452 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
453 if(len(vertices) != 2):
454 print "Error: vector object is incorrect."
456 p1 = self.geompyD.PointCoordinates(vertices[0])
457 p2 = self.geompyD.PointCoordinates(vertices[1])
458 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
459 dirst = DirStruct(pnt)
462 ## Make DirStruct from a triplet
463 # @param x,y,z vector components
464 # @return SMESH.DirStruct
465 # @ingroup l1_auxiliary
466 def MakeDirStruct(self,x,y,z):
467 pnt = PointStruct(x,y,z)
468 return DirStruct(pnt)
470 ## Get AxisStruct from object
471 # @param theObj a GEOM object (line or plane)
472 # @return SMESH.AxisStruct
473 # @ingroup l1_auxiliary
474 def GetAxisStruct(self,theObj):
476 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
479 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
480 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
481 vertex1 = self.geompyD.PointCoordinates(vertex1)
482 vertex2 = self.geompyD.PointCoordinates(vertex2)
483 vertex3 = self.geompyD.PointCoordinates(vertex3)
484 vertex4 = self.geompyD.PointCoordinates(vertex4)
485 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
486 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
487 normal = [ v1[1]*v2[2]-v2[1]*v1[2], v1[2]*v2[0]-v2[2]*v1[0], v1[0]*v2[1]-v2[0]*v1[1] ]
488 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
489 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
490 elif len(edges) == 1:
491 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
492 p1 = self.geompyD.PointCoordinates( vertex1 )
493 p2 = self.geompyD.PointCoordinates( vertex2 )
494 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
495 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
496 elif theObj.GetShapeType() == GEOM.VERTEX:
497 x,y,z = self.geompyD.PointCoordinates( theObj )
498 axis = AxisStruct( x,y,z, 1,0,0,)
499 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
502 # From SMESH_Gen interface:
503 # ------------------------
505 ## Set the given name to the object
506 # @param obj the object to rename
507 # @param name a new object name
508 # @ingroup l1_auxiliary
509 def SetName(self, obj, name):
510 if isinstance( obj, Mesh ):
512 elif isinstance( obj, Mesh_Algorithm ):
513 obj = obj.GetAlgorithm()
514 ior = salome.orb.object_to_string(obj)
515 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
517 ## Set the current mode
518 # @ingroup l1_auxiliary
519 def SetEmbeddedMode( self,theMode ):
520 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
522 ## Get the current mode
523 # @ingroup l1_auxiliary
524 def IsEmbeddedMode(self):
525 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
527 ## Set the current study. Calling SetCurrentStudy( None ) allows to
528 # switch OFF automatic pubilishing in the Study of mesh objects.
529 # @ingroup l1_auxiliary
530 def SetCurrentStudy( self, theStudy, geompyD = None ):
532 from salome.geom import geomBuilder
533 geompyD = geomBuilder.geom
536 self.SetGeomEngine(geompyD)
537 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
540 notebook = salome_notebook.NoteBook( theStudy )
542 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
544 sb = theStudy.NewBuilder()
545 sc = theStudy.FindComponent("SMESH")
546 if sc: sb.LoadWith(sc, self)
550 ## Get the current study
551 # @ingroup l1_auxiliary
552 def GetCurrentStudy(self):
553 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
555 ## Create a Mesh object importing data from the given UNV file
556 # @return an instance of Mesh class
558 def CreateMeshesFromUNV( self,theFileName ):
559 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
560 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
563 ## Create a Mesh object(s) importing data from the given MED file
564 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
566 def CreateMeshesFromMED( self,theFileName ):
567 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
568 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
569 return aMeshes, aStatus
571 ## Create a Mesh object(s) importing data from the given SAUV file
572 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
574 def CreateMeshesFromSAUV( self,theFileName ):
575 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
576 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
577 return aMeshes, aStatus
579 ## Create a Mesh object importing data from the given STL file
580 # @return an instance of Mesh class
582 def CreateMeshesFromSTL( self, theFileName ):
583 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
584 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
587 ## Create Mesh objects importing data from the given CGNS file
588 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
590 def CreateMeshesFromCGNS( self, theFileName ):
591 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
592 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
593 return aMeshes, aStatus
595 ## Create a Mesh object importing data from the given GMF file.
596 # GMF files must have .mesh extension for the ASCII format and .meshb for
598 # @return [ an instance of Mesh class, SMESH.ComputeError ]
600 def CreateMeshesFromGMF( self, theFileName ):
601 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
604 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
605 return Mesh(self, self.geompyD, aSmeshMesh), error
607 ## Concatenate the given meshes into one mesh. All groups of input meshes will be
608 # present in the new mesh.
609 # @param meshes the meshes, sub-meshes and groups to combine into one mesh
610 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
611 # @param mergeNodesAndElements if true, equal nodes and elements are merged
612 # @param mergeTolerance tolerance for merging nodes
613 # @param allGroups forces creation of groups corresponding to every input mesh
614 # @param name name of a new mesh
615 # @return an instance of Mesh class
616 # @ingroup l1_creating
617 def Concatenate( self, meshes, uniteIdenticalGroups,
618 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
620 if not meshes: return None
621 for i,m in enumerate(meshes):
622 if isinstance(m, Mesh):
623 meshes[i] = m.GetMesh()
624 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
625 meshes[0].SetParameters(Parameters)
627 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
628 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
630 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
631 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
632 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
635 ## Create a mesh by copying a part of another mesh.
636 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
637 # to copy nodes or elements not contained in any mesh object,
638 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
639 # @param meshName a name of the new mesh
640 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
641 # @param toKeepIDs to preserve order of the copied elements or not
642 # @return an instance of Mesh class
643 # @ingroup l1_creating
644 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
645 if (isinstance( meshPart, Mesh )):
646 meshPart = meshPart.GetMesh()
647 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
648 return Mesh(self, self.geompyD, mesh)
650 ## Return IDs of sub-shapes
651 # @return the list of integer values
652 # @ingroup l1_auxiliary
653 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
654 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
656 ## Create a pattern mapper.
657 # @return an instance of SMESH_Pattern
659 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
660 # @ingroup l1_modifying
661 def GetPattern(self):
662 return SMESH._objref_SMESH_Gen.GetPattern(self)
664 ## Set number of segments per diagonal of boundary box of geometry, by which
665 # default segment length of appropriate 1D hypotheses is defined in GUI.
666 # Default value is 10.
667 # @ingroup l1_auxiliary
668 def SetBoundaryBoxSegmentation(self, nbSegments):
669 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
671 # Filtering. Auxiliary functions:
672 # ------------------------------
674 ## Create an empty criterion
675 # @return SMESH.Filter.Criterion
676 # @ingroup l1_controls
677 def GetEmptyCriterion(self):
678 Type = self.EnumToLong(FT_Undefined)
679 Compare = self.EnumToLong(FT_Undefined)
683 UnaryOp = self.EnumToLong(FT_Undefined)
684 BinaryOp = self.EnumToLong(FT_Undefined)
687 Precision = -1 ##@1e-07
688 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
689 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
691 ## Create a criterion by the given parameters
692 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
693 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
694 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
695 # Type SMESH.FunctorType._items in the Python Console to see all values.
696 # Note that the items starting from FT_LessThan are not suitable for CritType.
697 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
698 # @param Threshold the threshold value (range of ids as string, shape, numeric)
699 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
700 # @param BinaryOp a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or
702 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
703 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
704 # @return SMESH.Filter.Criterion
706 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
707 # @ingroup l1_controls
708 def GetCriterion(self,elementType,
710 Compare = FT_EqualTo,
712 UnaryOp=FT_Undefined,
713 BinaryOp=FT_Undefined,
715 if not CritType in SMESH.FunctorType._items:
716 raise TypeError, "CritType should be of SMESH.FunctorType"
717 aCriterion = self.GetEmptyCriterion()
718 aCriterion.TypeOfElement = elementType
719 aCriterion.Type = self.EnumToLong(CritType)
720 aCriterion.Tolerance = Tolerance
722 aThreshold = Threshold
724 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
725 aCriterion.Compare = self.EnumToLong(Compare)
726 elif Compare == "=" or Compare == "==":
727 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
729 aCriterion.Compare = self.EnumToLong(FT_LessThan)
731 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
732 elif Compare != FT_Undefined:
733 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
736 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
737 FT_BelongToCylinder, FT_LyingOnGeom]:
738 # Check that Threshold is GEOM object
739 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
740 aCriterion.ThresholdStr = GetName(aThreshold)
741 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
742 if not aCriterion.ThresholdID:
743 name = aCriterion.ThresholdStr
745 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
746 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
747 # or a name of GEOM object
748 elif isinstance( aThreshold, str ):
749 aCriterion.ThresholdStr = aThreshold
751 raise TypeError, "The Threshold should be a shape."
752 if isinstance(UnaryOp,float):
753 aCriterion.Tolerance = UnaryOp
754 UnaryOp = FT_Undefined
756 elif CritType == FT_BelongToMeshGroup:
757 # Check that Threshold is a group
758 if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
759 if aThreshold.GetType() != elementType:
760 raise ValueError, "Group type mismatches Element type"
761 aCriterion.ThresholdStr = aThreshold.GetName()
762 aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
763 study = self.GetCurrentStudy()
765 so = study.FindObjectIOR( aCriterion.ThresholdID )
769 aCriterion.ThresholdID = entry
771 raise TypeError, "The Threshold should be a Mesh Group"
772 elif CritType == FT_RangeOfIds:
773 # Check that Threshold is string
774 if isinstance(aThreshold, str):
775 aCriterion.ThresholdStr = aThreshold
777 raise TypeError, "The Threshold should be a string."
778 elif CritType == FT_CoplanarFaces:
779 # Check the Threshold
780 if isinstance(aThreshold, int):
781 aCriterion.ThresholdID = str(aThreshold)
782 elif isinstance(aThreshold, str):
785 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
786 aCriterion.ThresholdID = aThreshold
789 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
790 elif CritType == FT_ConnectedElements:
791 # Check the Threshold
792 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
793 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
794 if not aCriterion.ThresholdID:
795 name = aThreshold.GetName()
797 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
798 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
799 elif isinstance(aThreshold, int): # node id
800 aCriterion.Threshold = aThreshold
801 elif isinstance(aThreshold, list): # 3 point coordinates
802 if len( aThreshold ) < 3:
803 raise ValueError, "too few point coordinates, must be 3"
804 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
805 elif isinstance(aThreshold, str):
806 if aThreshold.isdigit():
807 aCriterion.Threshold = aThreshold # node id
809 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
812 "The Threshold should either a VERTEX, or a node ID, "\
813 "or a list of point coordinates and not '%s'"%aThreshold
814 elif CritType == FT_ElemGeomType:
815 # Check the Threshold
817 aCriterion.Threshold = self.EnumToLong(aThreshold)
818 assert( aThreshold in SMESH.GeometryType._items )
820 if isinstance(aThreshold, int):
821 aCriterion.Threshold = aThreshold
823 raise TypeError, "The Threshold should be an integer or SMESH.GeometryType."
826 elif CritType == FT_EntityType:
827 # Check the Threshold
829 aCriterion.Threshold = self.EnumToLong(aThreshold)
830 assert( aThreshold in SMESH.EntityType._items )
832 if isinstance(aThreshold, int):
833 aCriterion.Threshold = aThreshold
835 raise TypeError, "The Threshold should be an integer or SMESH.EntityType."
839 elif CritType == FT_GroupColor:
840 # Check the Threshold
842 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
844 raise TypeError, "The threshold value should be of SALOMEDS.Color type"
846 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
847 FT_LinearOrQuadratic, FT_BadOrientedVolume,
848 FT_BareBorderFace, FT_BareBorderVolume,
849 FT_OverConstrainedFace, FT_OverConstrainedVolume,
850 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
851 # At this point the Threshold is unnecessary
852 if aThreshold == FT_LogicalNOT:
853 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
854 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
855 aCriterion.BinaryOp = aThreshold
859 aThreshold = float(aThreshold)
860 aCriterion.Threshold = aThreshold
862 raise TypeError, "The Threshold should be a number."
865 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
866 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
868 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
869 aCriterion.BinaryOp = self.EnumToLong(Threshold)
871 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
872 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
874 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
875 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
879 ## Create a filter with the given parameters
880 # @param elementType the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
881 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
882 # Type SMESH.FunctorType._items in the Python Console to see all values.
883 # Note that the items starting from FT_LessThan are not suitable for CritType.
884 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
885 # @param Threshold the threshold value (range of ids as string, shape, numeric)
886 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
887 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
888 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
889 # @param mesh the mesh to initialize the filter with
890 # @return SMESH_Filter
892 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
893 # @ingroup l1_controls
894 def GetFilter(self,elementType,
895 CritType=FT_Undefined,
898 UnaryOp=FT_Undefined,
901 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
902 aFilterMgr = self.CreateFilterManager()
903 aFilter = aFilterMgr.CreateFilter()
905 aCriteria.append(aCriterion)
906 aFilter.SetCriteria(aCriteria)
908 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
909 else : aFilter.SetMesh( mesh )
910 aFilterMgr.UnRegister()
913 ## Create a filter from criteria
914 # @param criteria a list of criteria
915 # @param binOp binary operator used when binary operator of criteria is undefined
916 # @return SMESH_Filter
918 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
919 # @ingroup l1_controls
920 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
921 for i in range( len( criteria ) - 1 ):
922 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
923 criteria[i].BinaryOp = self.EnumToLong( binOp )
924 aFilterMgr = self.CreateFilterManager()
925 aFilter = aFilterMgr.CreateFilter()
926 aFilter.SetCriteria(criteria)
927 aFilterMgr.UnRegister()
930 ## Create a numerical functor by its type
931 # @param theCriterion functor type - an item of SMESH.FunctorType enumeration.
932 # Type SMESH.FunctorType._items in the Python Console to see all items.
933 # Note that not all items correspond to numerical functors.
934 # @return SMESH_NumericalFunctor
935 # @ingroup l1_controls
936 def GetFunctor(self,theCriterion):
937 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
939 aFilterMgr = self.CreateFilterManager()
941 if theCriterion == FT_AspectRatio:
942 functor = aFilterMgr.CreateAspectRatio()
943 elif theCriterion == FT_AspectRatio3D:
944 functor = aFilterMgr.CreateAspectRatio3D()
945 elif theCriterion == FT_Warping:
946 functor = aFilterMgr.CreateWarping()
947 elif theCriterion == FT_MinimumAngle:
948 functor = aFilterMgr.CreateMinimumAngle()
949 elif theCriterion == FT_Taper:
950 functor = aFilterMgr.CreateTaper()
951 elif theCriterion == FT_Skew:
952 functor = aFilterMgr.CreateSkew()
953 elif theCriterion == FT_Area:
954 functor = aFilterMgr.CreateArea()
955 elif theCriterion == FT_Volume3D:
956 functor = aFilterMgr.CreateVolume3D()
957 elif theCriterion == FT_MaxElementLength2D:
958 functor = aFilterMgr.CreateMaxElementLength2D()
959 elif theCriterion == FT_MaxElementLength3D:
960 functor = aFilterMgr.CreateMaxElementLength3D()
961 elif theCriterion == FT_MultiConnection:
962 functor = aFilterMgr.CreateMultiConnection()
963 elif theCriterion == FT_MultiConnection2D:
964 functor = aFilterMgr.CreateMultiConnection2D()
965 elif theCriterion == FT_Length:
966 functor = aFilterMgr.CreateLength()
967 elif theCriterion == FT_Length2D:
968 functor = aFilterMgr.CreateLength2D()
969 elif theCriterion == FT_Deflection2D:
970 functor = aFilterMgr.CreateDeflection2D()
971 elif theCriterion == FT_NodeConnectivityNumber:
972 functor = aFilterMgr.CreateNodeConnectivityNumber()
973 elif theCriterion == FT_BallDiameter:
974 functor = aFilterMgr.CreateBallDiameter()
976 print "Error: given parameter is not numerical functor type."
977 aFilterMgr.UnRegister()
981 # @param theHType mesh hypothesis type (string)
982 # @param theLibName mesh plug-in library name
983 # @return created hypothesis instance
984 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
985 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
987 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
990 # wrap hypothesis methods
991 #print "HYPOTHESIS", theHType
992 for meth_name in dir( hyp.__class__ ):
993 if not meth_name.startswith("Get") and \
994 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
995 method = getattr ( hyp.__class__, meth_name )
997 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
1001 ## Get the mesh statistic
1002 # @return dictionary "element type" - "count of elements"
1003 # @ingroup l1_meshinfo
1004 def GetMeshInfo(self, obj):
1005 if isinstance( obj, Mesh ):
1008 if hasattr(obj, "GetMeshInfo"):
1009 values = obj.GetMeshInfo()
1010 for i in range(SMESH.Entity_Last._v):
1011 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1015 ## Get minimum distance between two objects
1017 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1018 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1020 # @param src1 first source object
1021 # @param src2 second source object
1022 # @param id1 node/element id from the first source
1023 # @param id2 node/element id from the second (or first) source
1024 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1025 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1026 # @return minimum distance value
1027 # @sa GetMinDistance()
1028 # @ingroup l1_measurements
1029 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1030 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1034 result = result.value
1037 ## Get measure structure specifying minimum distance data between two objects
1039 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1040 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1042 # @param src1 first source object
1043 # @param src2 second source object
1044 # @param id1 node/element id from the first source
1045 # @param id2 node/element id from the second (or first) source
1046 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1047 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1048 # @return Measure structure or None if input data is invalid
1050 # @ingroup l1_measurements
1051 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1052 if isinstance(src1, Mesh): src1 = src1.mesh
1053 if isinstance(src2, Mesh): src2 = src2.mesh
1054 if src2 is None and id2 != 0: src2 = src1
1055 if not hasattr(src1, "_narrow"): return None
1056 src1 = src1._narrow(SMESH.SMESH_IDSource)
1057 if not src1: return None
1058 unRegister = genObjUnRegister()
1061 e = m.GetMeshEditor()
1063 src1 = e.MakeIDSource([id1], SMESH.FACE)
1065 src1 = e.MakeIDSource([id1], SMESH.NODE)
1066 unRegister.set( src1 )
1068 if hasattr(src2, "_narrow"):
1069 src2 = src2._narrow(SMESH.SMESH_IDSource)
1070 if src2 and id2 != 0:
1072 e = m.GetMeshEditor()
1074 src2 = e.MakeIDSource([id2], SMESH.FACE)
1076 src2 = e.MakeIDSource([id2], SMESH.NODE)
1077 unRegister.set( src2 )
1080 aMeasurements = self.CreateMeasurements()
1081 unRegister.set( aMeasurements )
1082 result = aMeasurements.MinDistance(src1, src2)
1085 ## Get bounding box of the specified object(s)
1086 # @param objects single source object or list of source objects
1087 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1088 # @sa GetBoundingBox()
1089 # @ingroup l1_measurements
1090 def BoundingBox(self, objects):
1091 result = self.GetBoundingBox(objects)
1095 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1098 ## Get measure structure specifying bounding box data of the specified object(s)
1099 # @param objects single source object or list of source objects
1100 # @return Measure structure
1102 # @ingroup l1_measurements
1103 def GetBoundingBox(self, objects):
1104 if isinstance(objects, tuple):
1105 objects = list(objects)
1106 if not isinstance(objects, list):
1110 if isinstance(o, Mesh):
1111 srclist.append(o.mesh)
1112 elif hasattr(o, "_narrow"):
1113 src = o._narrow(SMESH.SMESH_IDSource)
1114 if src: srclist.append(src)
1117 aMeasurements = self.CreateMeasurements()
1118 result = aMeasurements.BoundingBox(srclist)
1119 aMeasurements.UnRegister()
1122 ## Get sum of lengths of all 1D elements in the mesh object.
1123 # @param obj mesh, submesh or group
1124 # @return sum of lengths of all 1D elements
1125 # @ingroup l1_measurements
1126 def GetLength(self, obj):
1127 if isinstance(obj, Mesh): obj = obj.mesh
1128 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1129 aMeasurements = self.CreateMeasurements()
1130 value = aMeasurements.Length(obj)
1131 aMeasurements.UnRegister()
1134 ## Get sum of areas of all 2D elements in the mesh object.
1135 # @param obj mesh, submesh or group
1136 # @return sum of areas of all 2D elements
1137 # @ingroup l1_measurements
1138 def GetArea(self, obj):
1139 if isinstance(obj, Mesh): obj = obj.mesh
1140 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1141 aMeasurements = self.CreateMeasurements()
1142 value = aMeasurements.Area(obj)
1143 aMeasurements.UnRegister()
1146 ## Get sum of volumes of all 3D elements in the mesh object.
1147 # @param obj mesh, submesh or group
1148 # @return sum of volumes of all 3D elements
1149 # @ingroup l1_measurements
1150 def GetVolume(self, obj):
1151 if isinstance(obj, Mesh): obj = obj.mesh
1152 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1153 aMeasurements = self.CreateMeasurements()
1154 value = aMeasurements.Volume(obj)
1155 aMeasurements.UnRegister()
1158 pass # end of class smeshBuilder
1161 #Registering the new proxy for SMESH_Gen
1162 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1164 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1165 # interface to create or load meshes.
1170 # salome.salome_init()
1171 # from salome.smesh import smeshBuilder
1172 # smesh = smeshBuilder.New(salome.myStudy)
1174 # @param study SALOME study, generally obtained by salome.myStudy.
1175 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1176 # @return smeshBuilder instance
1178 def New( study, instance=None):
1180 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1181 interface to create or load meshes.
1185 salome.salome_init()
1186 from salome.smesh import smeshBuilder
1187 smesh = smeshBuilder.New(salome.myStudy)
1190 study SALOME study, generally obtained by salome.myStudy.
1191 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1193 smeshBuilder instance
1201 smeshInst = smeshBuilder()
1202 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1203 smeshInst.init_smesh(study)
1207 # Public class: Mesh
1208 # ==================
1210 ## This class allows defining and managing a mesh.
1211 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1212 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1213 # new nodes and elements and by changing the existing entities), to get information
1214 # about a mesh and to export a mesh in different formats.
1216 __metaclass__ = MeshMeta
1224 # Create a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1225 # sets the GUI name of this mesh to \a name.
1226 # @param smeshpyD an instance of smeshBuilder class
1227 # @param geompyD an instance of geomBuilder class
1228 # @param obj Shape to be meshed or SMESH_Mesh object
1229 # @param name Study name of the mesh
1230 # @ingroup l2_construct
1231 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1232 self.smeshpyD=smeshpyD
1233 self.geompyD=geompyD
1238 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1241 # publish geom of mesh (issue 0021122)
1242 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1244 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1245 if studyID != geompyD.myStudyId:
1246 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1249 geo_name = name + " shape"
1251 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1252 geompyD.addToStudy( self.geom, geo_name )
1253 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1255 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1258 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1260 self.smeshpyD.SetName(self.mesh, name)
1262 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1265 self.geom = self.mesh.GetShapeToMesh()
1267 self.editor = self.mesh.GetMeshEditor()
1268 self.functors = [None] * SMESH.FT_Undefined._v
1270 # set self to algoCreator's
1271 for attrName in dir(self):
1272 attr = getattr( self, attrName )
1273 if isinstance( attr, algoCreator ):
1274 setattr( self, attrName, attr.copy( self ))
1279 ## Destructor. Clean-up resources
1282 #self.mesh.UnRegister()
1286 ## Initialize the Mesh object from an instance of SMESH_Mesh interface
1287 # @param theMesh a SMESH_Mesh object
1288 # @ingroup l2_construct
1289 def SetMesh(self, theMesh):
1290 # do not call Register() as this prevents mesh servant deletion at closing study
1291 #if self.mesh: self.mesh.UnRegister()
1294 #self.mesh.Register()
1295 self.geom = self.mesh.GetShapeToMesh()
1298 ## Return the mesh, that is an instance of SMESH_Mesh interface
1299 # @return a SMESH_Mesh object
1300 # @ingroup l2_construct
1304 ## Get the name of the mesh
1305 # @return the name of the mesh as a string
1306 # @ingroup l2_construct
1308 name = GetName(self.GetMesh())
1311 ## Set a name to the mesh
1312 # @param name a new name of the mesh
1313 # @ingroup l2_construct
1314 def SetName(self, name):
1315 self.smeshpyD.SetName(self.GetMesh(), name)
1317 ## Get a sub-mesh object associated to a \a geom geometrical object.
1318 # @param geom a geometrical object (shape)
1319 # @param name a name for the sub-mesh in the Object Browser
1320 # @return an object of type SMESH.SMESH_subMesh, representing a part of mesh,
1321 # which lies on the given shape
1323 # The sub-mesh object gives access to the IDs of nodes and elements.
1324 # The sub-mesh object has the following methods:
1325 # - SMESH.SMESH_subMesh.GetNumberOfElements()
1326 # - SMESH.SMESH_subMesh.GetNumberOfNodes( all )
1327 # - SMESH.SMESH_subMesh.GetElementsId()
1328 # - SMESH.SMESH_subMesh.GetElementsByType( ElementType )
1329 # - SMESH.SMESH_subMesh.GetNodesId()
1330 # - SMESH.SMESH_subMesh.GetSubShape()
1331 # - SMESH.SMESH_subMesh.GetFather()
1332 # - SMESH.SMESH_subMesh.GetId()
1333 # @note A sub-mesh is implicitly created when a sub-shape is specified at
1334 # creating an algorithm, for example: <code>algo1D = mesh.Segment(geom=Edge_1) </code>
1335 # creates a sub-mesh on @c Edge_1 and assign Wire Discretization algorithm to it.
1336 # The created sub-mesh can be retrieved from the algorithm:
1337 # <code>submesh = algo1D.GetSubMesh()</code>
1338 # @ingroup l2_submeshes
1339 def GetSubMesh(self, geom, name):
1340 AssureGeomPublished( self, geom, name )
1341 submesh = self.mesh.GetSubMesh( geom, name )
1344 ## Return the shape associated to the mesh
1345 # @return a GEOM_Object
1346 # @ingroup l2_construct
1350 ## Associate the given shape to the mesh (entails the recreation of the mesh)
1351 # @param geom the shape to be meshed (GEOM_Object)
1352 # @ingroup l2_construct
1353 def SetShape(self, geom):
1354 self.mesh = self.smeshpyD.CreateMesh(geom)
1356 ## Load mesh from the study after opening the study
1360 ## Return true if the hypotheses are defined well
1361 # @param theSubObject a sub-shape of a mesh shape
1362 # @return True or False
1363 # @ingroup l2_construct
1364 def IsReadyToCompute(self, theSubObject):
1365 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1367 ## Return errors of hypotheses definition.
1368 # The list of errors is empty if everything is OK.
1369 # @param theSubObject a sub-shape of a mesh shape
1370 # @return a list of errors
1371 # @ingroup l2_construct
1372 def GetAlgoState(self, theSubObject):
1373 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1375 ## Return a geometrical object on which the given element was built.
1376 # The returned geometrical object, if not nil, is either found in the
1377 # study or published by this method with the given name
1378 # @param theElementID the id of the mesh element
1379 # @param theGeomName the user-defined name of the geometrical object
1380 # @return GEOM::GEOM_Object instance
1381 # @ingroup l1_meshinfo
1382 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1383 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1385 ## Return the mesh dimension depending on the dimension of the underlying shape
1386 # or, if the mesh is not based on any shape, basing on deimension of elements
1387 # @return mesh dimension as an integer value [0,3]
1388 # @ingroup l1_meshinfo
1389 def MeshDimension(self):
1390 if self.mesh.HasShapeToMesh():
1391 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1392 if len( shells ) > 0 :
1394 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1396 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1401 if self.NbVolumes() > 0: return 3
1402 if self.NbFaces() > 0: return 2
1403 if self.NbEdges() > 0: return 1
1406 ## Evaluate size of prospective mesh on a shape
1407 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1408 # To know predicted number of e.g. edges, inquire it this way
1409 # Evaluate()[ EnumToLong( Entity_Edge )]
1410 # @ingroup l2_construct
1411 def Evaluate(self, geom=0):
1412 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1414 geom = self.mesh.GetShapeToMesh()
1417 return self.smeshpyD.Evaluate(self.mesh, geom)
1420 ## Compute the mesh and return the status of the computation
1421 # @param geom geomtrical shape on which mesh data should be computed
1422 # @param discardModifs if True and the mesh has been edited since
1423 # a last total re-compute and that may prevent successful partial re-compute,
1424 # then the mesh is cleaned before Compute()
1425 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1426 # @return True or False
1427 # @ingroup l2_construct
1428 def Compute(self, geom=0, discardModifs=False, refresh=False):
1429 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1431 geom = self.mesh.GetShapeToMesh()
1436 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1438 ok = self.smeshpyD.Compute(self.mesh, geom)
1439 except SALOME.SALOME_Exception, ex:
1440 print "Mesh computation failed, exception caught:"
1441 print " ", ex.details.text
1444 print "Mesh computation failed, exception caught:"
1445 traceback.print_exc()
1449 # Treat compute errors
1450 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1452 for err in computeErrors:
1453 if self.mesh.HasShapeToMesh():
1454 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1456 stdErrors = ["OK", #COMPERR_OK
1457 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1458 "std::exception", #COMPERR_STD_EXCEPTION
1459 "OCC exception", #COMPERR_OCC_EXCEPTION
1460 "..", #COMPERR_SLM_EXCEPTION
1461 "Unknown exception", #COMPERR_EXCEPTION
1462 "Memory allocation problem", #COMPERR_MEMORY_PB
1463 "Algorithm failed", #COMPERR_ALGO_FAILED
1464 "Unexpected geometry", #COMPERR_BAD_SHAPE
1465 "Warning", #COMPERR_WARNING
1466 "Computation cancelled",#COMPERR_CANCELED
1467 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1469 if err.code < len(stdErrors): errText = stdErrors[err.code]
1471 errText = "code %s" % -err.code
1472 if errText: errText += ". "
1473 errText += err.comment
1474 if allReasons: allReasons += "\n"
1476 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1478 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1482 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1484 if err.isGlobalAlgo:
1492 reason = '%s %sD algorithm is missing' % (glob, dim)
1493 elif err.state == HYP_MISSING:
1494 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1495 % (glob, dim, name, dim))
1496 elif err.state == HYP_NOTCONFORM:
1497 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1498 elif err.state == HYP_BAD_PARAMETER:
1499 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1500 % ( glob, dim, name ))
1501 elif err.state == HYP_BAD_GEOMETRY:
1502 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1503 'geometry' % ( glob, dim, name ))
1504 elif err.state == HYP_HIDDEN_ALGO:
1505 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1506 'algorithm of upper dimension generating %sD mesh'
1507 % ( glob, dim, name, glob, dim ))
1509 reason = ("For unknown reason. "
1510 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1512 if allReasons: allReasons += "\n"
1513 allReasons += "- " + reason
1515 if not ok or allReasons != "":
1516 msg = '"' + GetName(self.mesh) + '"'
1517 if ok: msg += " has been computed with warnings"
1518 else: msg += " has not been computed"
1519 if allReasons != "": msg += ":"
1524 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1525 if not isinstance( refresh, list): # not a call from subMesh.Compute()
1526 smeshgui = salome.ImportComponentGUI("SMESH")
1527 smeshgui.Init(self.mesh.GetStudyId())
1528 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1529 if refresh: salome.sg.updateObjBrowser(True)
1533 ## Return a list of error messages (SMESH.ComputeError) of the last Compute()
1534 # @ingroup l2_construct
1535 def GetComputeErrors(self, shape=0 ):
1537 shape = self.mesh.GetShapeToMesh()
1538 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1540 ## Return a name of a sub-shape by its ID
1541 # @param subShapeID a unique ID of a sub-shape
1542 # @return a string describing the sub-shape; possible variants:
1543 # - "Face_12" (published sub-shape)
1544 # - FACE #3 (not published sub-shape)
1545 # - sub-shape #3 (invalid sub-shape ID)
1546 # - #3 (error in this function)
1547 # @ingroup l1_auxiliary
1548 def GetSubShapeName(self, subShapeID ):
1549 if not self.mesh.HasShapeToMesh():
1553 mainIOR = salome.orb.object_to_string( self.GetShape() )
1554 for sname in salome.myStudyManager.GetOpenStudies():
1555 s = salome.myStudyManager.GetStudyByName(sname)
1557 mainSO = s.FindObjectIOR(mainIOR)
1558 if not mainSO: continue
1560 shapeText = '"%s"' % mainSO.GetName()
1561 subIt = s.NewChildIterator(mainSO)
1563 subSO = subIt.Value()
1565 obj = subSO.GetObject()
1566 if not obj: continue
1567 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1570 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1573 if ids == subShapeID:
1574 shapeText = '"%s"' % subSO.GetName()
1577 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1579 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1581 shapeText = 'sub-shape #%s' % (subShapeID)
1583 shapeText = "#%s" % (subShapeID)
1586 ## Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1587 # error of an algorithm
1588 # @param publish if @c True, the returned groups will be published in the study
1589 # @return a list of GEOM groups each named after a failed algorithm
1590 # @ingroup l2_construct
1591 def GetFailedShapes(self, publish=False):
1594 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1595 for err in computeErrors:
1596 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1597 if not shape: continue
1598 if err.algoName in algo2shapes:
1599 algo2shapes[ err.algoName ].append( shape )
1601 algo2shapes[ err.algoName ] = [ shape ]
1605 for algoName, shapes in algo2shapes.items():
1607 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1608 otherTypeShapes = []
1610 group = self.geompyD.CreateGroup( self.geom, groupType )
1611 for shape in shapes:
1612 if shape.GetShapeType() == shapes[0].GetShapeType():
1613 sameTypeShapes.append( shape )
1615 otherTypeShapes.append( shape )
1616 self.geompyD.UnionList( group, sameTypeShapes )
1618 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1620 group.SetName( algoName )
1621 groups.append( group )
1622 shapes = otherTypeShapes
1625 for group in groups:
1626 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1629 ## Return sub-mesh objects list in meshing order
1630 # @return list of lists of sub-meshes
1631 # @ingroup l2_construct
1632 def GetMeshOrder(self):
1633 return self.mesh.GetMeshOrder()
1635 ## Set order in which concurrent sub-meshes should be meshed
1636 # @param submeshes list of lists of sub-meshes
1637 # @ingroup l2_construct
1638 def SetMeshOrder(self, submeshes):
1639 return self.mesh.SetMeshOrder(submeshes)
1641 ## Remove all nodes and elements generated on geometry. Imported elements remain.
1642 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1643 # @ingroup l2_construct
1644 def Clear(self, refresh=False):
1646 if ( salome.sg.hasDesktop() and
1647 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1648 smeshgui = salome.ImportComponentGUI("SMESH")
1649 smeshgui.Init(self.mesh.GetStudyId())
1650 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1651 if refresh: salome.sg.updateObjBrowser(True)
1653 ## Remove all nodes and elements of indicated shape
1654 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1655 # @param geomId the ID of a sub-shape to remove elements on
1656 # @ingroup l2_submeshes
1657 def ClearSubMesh(self, geomId, refresh=False):
1658 self.mesh.ClearSubMesh(geomId)
1659 if salome.sg.hasDesktop():
1660 smeshgui = salome.ImportComponentGUI("SMESH")
1661 smeshgui.Init(self.mesh.GetStudyId())
1662 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1663 if refresh: salome.sg.updateObjBrowser(True)
1665 ## Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1666 # @param fineness [0.0,1.0] defines mesh fineness
1667 # @return True or False
1668 # @ingroup l3_algos_basic
1669 def AutomaticTetrahedralization(self, fineness=0):
1670 dim = self.MeshDimension()
1672 self.RemoveGlobalHypotheses()
1673 self.Segment().AutomaticLength(fineness)
1675 self.Triangle().LengthFromEdges()
1680 return self.Compute()
1682 ## Compute an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1683 # @param fineness [0.0, 1.0] defines mesh fineness
1684 # @return True or False
1685 # @ingroup l3_algos_basic
1686 def AutomaticHexahedralization(self, fineness=0):
1687 dim = self.MeshDimension()
1688 # assign the hypotheses
1689 self.RemoveGlobalHypotheses()
1690 self.Segment().AutomaticLength(fineness)
1697 return self.Compute()
1699 ## Assign a hypothesis
1700 # @param hyp a hypothesis to assign
1701 # @param geom a subhape of mesh geometry
1702 # @return SMESH.Hypothesis_Status
1703 # @ingroup l2_editing
1704 def AddHypothesis(self, hyp, geom=0):
1705 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1706 hyp, geom = geom, hyp
1707 if isinstance( hyp, Mesh_Algorithm ):
1708 hyp = hyp.GetAlgorithm()
1713 geom = self.mesh.GetShapeToMesh()
1716 if self.mesh.HasShapeToMesh():
1717 hyp_type = hyp.GetName()
1718 lib_name = hyp.GetLibName()
1719 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1720 # if checkAll and geom:
1721 # checkAll = geom.GetType() == 37
1723 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1725 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1726 status = self.mesh.AddHypothesis(geom, hyp)
1728 status = HYP_BAD_GEOMETRY,""
1729 hyp_name = GetName( hyp )
1732 geom_name = geom.GetName()
1733 isAlgo = hyp._narrow( SMESH_Algo )
1734 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1737 ## Return True if an algorithm of hypothesis is assigned to a given shape
1738 # @param hyp a hypothesis to check
1739 # @param geom a subhape of mesh geometry
1740 # @return True of False
1741 # @ingroup l2_editing
1742 def IsUsedHypothesis(self, hyp, geom):
1743 if not hyp: # or not geom
1745 if isinstance( hyp, Mesh_Algorithm ):
1746 hyp = hyp.GetAlgorithm()
1748 hyps = self.GetHypothesisList(geom)
1750 if h.GetId() == hyp.GetId():
1754 ## Unassign a hypothesis
1755 # @param hyp a hypothesis to unassign
1756 # @param geom a sub-shape of mesh geometry
1757 # @return SMESH.Hypothesis_Status
1758 # @ingroup l2_editing
1759 def RemoveHypothesis(self, hyp, geom=0):
1762 if isinstance( hyp, Mesh_Algorithm ):
1763 hyp = hyp.GetAlgorithm()
1769 if self.IsUsedHypothesis( hyp, shape ):
1770 return self.mesh.RemoveHypothesis( shape, hyp )
1771 hypName = GetName( hyp )
1772 geoName = GetName( shape )
1773 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1776 ## Get the list of hypotheses added on a geometry
1777 # @param geom a sub-shape of mesh geometry
1778 # @return the sequence of SMESH_Hypothesis
1779 # @ingroup l2_editing
1780 def GetHypothesisList(self, geom):
1781 return self.mesh.GetHypothesisList( geom )
1783 ## Remove all global hypotheses
1784 # @ingroup l2_editing
1785 def RemoveGlobalHypotheses(self):
1786 current_hyps = self.mesh.GetHypothesisList( self.geom )
1787 for hyp in current_hyps:
1788 self.mesh.RemoveHypothesis( self.geom, hyp )
1792 ## Export the mesh in a file in MED format
1793 ## allowing to overwrite the file if it exists or add the exported data to its contents
1794 # @param f is the file name
1795 # @param auto_groups boolean parameter for creating/not creating
1796 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1797 # the typical use is auto_groups=False.
1798 # @param version MED format version (MED_V2_1 or MED_V2_2,
1799 # the latter meaning any current version). The parameter is
1800 # obsolete since MED_V2_1 is no longer supported.
1801 # @param overwrite boolean parameter for overwriting/not overwriting the file
1802 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1803 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1804 # - 1D if all mesh nodes lie on OX coordinate axis, or
1805 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1806 # - 3D in the rest cases.<br>
1807 # If @a autoDimension is @c False, the space dimension is always 3.
1808 # @param fields list of GEOM fields defined on the shape to mesh.
1809 # @param geomAssocFields each character of this string means a need to export a
1810 # corresponding field; correspondence between fields and characters is following:
1811 # - 'v' stands for "_vertices _" field;
1812 # - 'e' stands for "_edges _" field;
1813 # - 'f' stands for "_faces _" field;
1814 # - 's' stands for "_solids _" field.
1815 # @ingroup l2_impexp
1816 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1817 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1818 if meshPart or fields or geomAssocFields:
1819 unRegister = genObjUnRegister()
1820 if isinstance( meshPart, list ):
1821 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1822 unRegister.set( meshPart )
1823 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1824 fields, geomAssocFields)
1826 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1828 ## Export the mesh in a file in SAUV format
1829 # @param f is the file name
1830 # @param auto_groups boolean parameter for creating/not creating
1831 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1832 # the typical use is auto_groups=false.
1833 # @ingroup l2_impexp
1834 def ExportSAUV(self, f, auto_groups=0):
1835 self.mesh.ExportSAUV(f, auto_groups)
1837 ## Export the mesh in a file in DAT format
1838 # @param f the file name
1839 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1840 # @ingroup l2_impexp
1841 def ExportDAT(self, f, meshPart=None):
1843 unRegister = genObjUnRegister()
1844 if isinstance( meshPart, list ):
1845 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1846 unRegister.set( meshPart )
1847 self.mesh.ExportPartToDAT( meshPart, f )
1849 self.mesh.ExportDAT(f)
1851 ## Export the mesh in a file in UNV format
1852 # @param f the file name
1853 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1854 # @ingroup l2_impexp
1855 def ExportUNV(self, f, meshPart=None):
1857 unRegister = genObjUnRegister()
1858 if isinstance( meshPart, list ):
1859 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1860 unRegister.set( meshPart )
1861 self.mesh.ExportPartToUNV( meshPart, f )
1863 self.mesh.ExportUNV(f)
1865 ## Export the mesh in a file in STL format
1866 # @param f the file name
1867 # @param ascii defines the file encoding
1868 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1869 # @ingroup l2_impexp
1870 def ExportSTL(self, f, ascii=1, meshPart=None):
1872 unRegister = genObjUnRegister()
1873 if isinstance( meshPart, list ):
1874 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1875 unRegister.set( meshPart )
1876 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1878 self.mesh.ExportSTL(f, ascii)
1880 ## Export the mesh in a file in CGNS format
1881 # @param f is the file name
1882 # @param overwrite boolean parameter for overwriting/not overwriting the file
1883 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1884 # @param groupElemsByType if true all elements of same entity type are exported at ones,
1885 # else elements are exported in order of their IDs which can cause creation
1886 # of multiple cgns sections
1887 # @ingroup l2_impexp
1888 def ExportCGNS(self, f, overwrite=1, meshPart=None, groupElemsByType=False):
1889 unRegister = genObjUnRegister()
1890 if isinstance( meshPart, list ):
1891 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1892 unRegister.set( meshPart )
1893 if isinstance( meshPart, Mesh ):
1894 meshPart = meshPart.mesh
1896 meshPart = self.mesh
1897 self.mesh.ExportCGNS(meshPart, f, overwrite, groupElemsByType)
1899 ## Export the mesh in a file in GMF format.
1900 # GMF files must have .mesh extension for the ASCII format and .meshb for
1901 # the bynary format. Other extensions are not allowed.
1902 # @param f is the file name
1903 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1904 # @ingroup l2_impexp
1905 def ExportGMF(self, f, meshPart=None):
1906 unRegister = genObjUnRegister()
1907 if isinstance( meshPart, list ):
1908 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1909 unRegister.set( meshPart )
1910 if isinstance( meshPart, Mesh ):
1911 meshPart = meshPart.mesh
1913 meshPart = self.mesh
1914 self.mesh.ExportGMF(meshPart, f, True)
1916 ## Deprecated, used only for compatibility! Please, use ExportMED() method instead.
1917 # Export the mesh in a file in MED format
1918 # allowing to overwrite the file if it exists or add the exported data to its contents
1919 # @param f the file name
1920 # @param version MED format version (MED_V2_1 or MED_V2_2,
1921 # the latter meaning any current version). The parameter is
1922 # obsolete since MED_V2_1 is no longer supported.
1923 # @param opt boolean parameter for creating/not creating
1924 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1925 # @param overwrite boolean parameter for overwriting/not overwriting the file
1926 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1927 # - 1D if all mesh nodes lie on OX coordinate axis, or
1928 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1929 # - 3D in the rest cases.<br>
1930 # If @a autoDimension is @c False, the space dimension is always 3.
1931 # @ingroup l2_impexp
1932 def ExportToMED(self, f, version=MED_V2_2, opt=0, overwrite=1, autoDimension=True):
1933 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1935 # Operations with groups:
1936 # ----------------------
1938 ## Create an empty mesh group
1939 # @param elementType the type of elements in the group; either of
1940 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1941 # @param name the name of the mesh group
1942 # @return SMESH_Group
1943 # @ingroup l2_grps_create
1944 def CreateEmptyGroup(self, elementType, name):
1945 return self.mesh.CreateGroup(elementType, name)
1947 ## Create a mesh group based on the geometric object \a grp
1948 # and gives a \a name, \n if this parameter is not defined
1949 # the name is the same as the geometric group name \n
1950 # Note: Works like GroupOnGeom().
1951 # @param grp a geometric group, a vertex, an edge, a face or a solid
1952 # @param name the name of the mesh group
1953 # @return SMESH_GroupOnGeom
1954 # @ingroup l2_grps_create
1955 def Group(self, grp, name=""):
1956 return self.GroupOnGeom(grp, name)
1958 ## Create a mesh group based on the geometrical object \a grp
1959 # and gives a \a name, \n if this parameter is not defined
1960 # the name is the same as the geometrical group name
1961 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1962 # @param name the name of the mesh group
1963 # @param typ the type of elements in the group; either of
1964 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
1965 # automatically detected by the type of the geometry
1966 # @return SMESH_GroupOnGeom
1967 # @ingroup l2_grps_create
1968 def GroupOnGeom(self, grp, name="", typ=None):
1969 AssureGeomPublished( self, grp, name )
1971 name = grp.GetName()
1973 typ = self._groupTypeFromShape( grp )
1974 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1976 ## Pivate method to get a type of group on geometry
1977 def _groupTypeFromShape( self, shape ):
1978 tgeo = str(shape.GetShapeType())
1979 if tgeo == "VERTEX":
1981 elif tgeo == "EDGE":
1983 elif tgeo == "FACE" or tgeo == "SHELL":
1985 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1987 elif tgeo == "COMPOUND":
1988 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1990 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1991 return self._groupTypeFromShape( sub[0] )
1994 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1997 ## Create a mesh group with given \a name based on the \a filter which
1998 ## is a special type of group dynamically updating it's contents during
1999 ## mesh modification
2000 # @param typ the type of elements in the group; either of
2001 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2002 # @param name the name of the mesh group
2003 # @param filter the filter defining group contents
2004 # @return SMESH_GroupOnFilter
2005 # @ingroup l2_grps_create
2006 def GroupOnFilter(self, typ, name, filter):
2007 return self.mesh.CreateGroupFromFilter(typ, name, filter)
2009 ## Create a mesh group by the given ids of elements
2010 # @param groupName the name of the mesh group
2011 # @param elementType the type of elements in the group; either of
2012 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2013 # @param elemIDs either the list of ids, group, sub-mesh, or filter
2014 # @return SMESH_Group
2015 # @ingroup l2_grps_create
2016 def MakeGroupByIds(self, groupName, elementType, elemIDs):
2017 group = self.mesh.CreateGroup(elementType, groupName)
2018 if isinstance( elemIDs, Mesh ):
2019 elemIDs = elemIDs.GetMesh()
2020 if hasattr( elemIDs, "GetIDs" ):
2021 if hasattr( elemIDs, "SetMesh" ):
2022 elemIDs.SetMesh( self.GetMesh() )
2023 group.AddFrom( elemIDs )
2028 ## Create a mesh group by the given conditions
2029 # @param groupName the name of the mesh group
2030 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2031 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
2032 # Type SMESH.FunctorType._items in the Python Console to see all values.
2033 # Note that the items starting from FT_LessThan are not suitable for CritType.
2034 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
2035 # @param Threshold the threshold value (range of ids as string, shape, numeric)
2036 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2037 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2038 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2039 # @return SMESH_GroupOnFilter
2040 # @ingroup l2_grps_create
2044 CritType=FT_Undefined,
2047 UnaryOp=FT_Undefined,
2049 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2050 group = self.MakeGroupByCriterion(groupName, aCriterion)
2053 ## Create a mesh group by the given criterion
2054 # @param groupName the name of the mesh group
2055 # @param Criterion the instance of Criterion class
2056 # @return SMESH_GroupOnFilter
2057 # @ingroup l2_grps_create
2058 def MakeGroupByCriterion(self, groupName, Criterion):
2059 return self.MakeGroupByCriteria( groupName, [Criterion] )
2061 ## Create a mesh group by the given criteria (list of criteria)
2062 # @param groupName the name of the mesh group
2063 # @param theCriteria the list of criteria
2064 # @param binOp binary operator used when binary operator of criteria is undefined
2065 # @return SMESH_GroupOnFilter
2066 # @ingroup l2_grps_create
2067 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2068 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2069 group = self.MakeGroupByFilter(groupName, aFilter)
2072 ## Create a mesh group by the given filter
2073 # @param groupName the name of the mesh group
2074 # @param theFilter the instance of Filter class
2075 # @return SMESH_GroupOnFilter
2076 # @ingroup l2_grps_create
2077 def MakeGroupByFilter(self, groupName, theFilter):
2078 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2079 #theFilter.SetMesh( self.mesh )
2080 #group.AddFrom( theFilter )
2081 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2085 # @ingroup l2_grps_delete
2086 def RemoveGroup(self, group):
2087 self.mesh.RemoveGroup(group)
2089 ## Remove a group with its contents
2090 # @ingroup l2_grps_delete
2091 def RemoveGroupWithContents(self, group):
2092 self.mesh.RemoveGroupWithContents(group)
2094 ## Get the list of groups existing in the mesh in the order
2095 # of creation (starting from the oldest one)
2096 # @param elemType type of elements the groups contain; either of
2097 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2098 # by default groups of elements of all types are returned
2099 # @return a sequence of SMESH_GroupBase
2100 # @ingroup l2_grps_create
2101 def GetGroups(self, elemType = SMESH.ALL):
2102 groups = self.mesh.GetGroups()
2103 if elemType == SMESH.ALL:
2107 if g.GetType() == elemType:
2108 typedGroups.append( g )
2113 ## Get the number of groups existing in the mesh
2114 # @return the quantity of groups as an integer value
2115 # @ingroup l2_grps_create
2117 return self.mesh.NbGroups()
2119 ## Get the list of names of groups existing in the mesh
2120 # @return list of strings
2121 # @ingroup l2_grps_create
2122 def GetGroupNames(self):
2123 groups = self.GetGroups()
2125 for group in groups:
2126 names.append(group.GetName())
2129 ## Find groups by name and type
2130 # @param name name of the group of interest
2131 # @param elemType type of elements the groups contain; either of
2132 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2133 # by default one group of any type of elements is returned
2134 # if elemType == SMESH.ALL then all groups of any type are returned
2135 # @return a list of SMESH_GroupBase's
2136 # @ingroup l2_grps_create
2137 def GetGroupByName(self, name, elemType = None):
2139 for group in self.GetGroups():
2140 if group.GetName() == name:
2141 if elemType is None:
2143 if ( elemType == SMESH.ALL or
2144 group.GetType() == elemType ):
2145 groups.append( group )
2148 ## Produce a union of two groups.
2149 # A new group is created. All mesh elements that are
2150 # present in the initial groups are added to the new one
2151 # @return an instance of SMESH_Group
2152 # @ingroup l2_grps_operon
2153 def UnionGroups(self, group1, group2, name):
2154 return self.mesh.UnionGroups(group1, group2, name)
2156 ## Produce a union list of groups.
2157 # New group is created. All mesh elements that are present in
2158 # initial groups are added to the new one
2159 # @return an instance of SMESH_Group
2160 # @ingroup l2_grps_operon
2161 def UnionListOfGroups(self, groups, name):
2162 return self.mesh.UnionListOfGroups(groups, name)
2164 ## Prodice an intersection of two groups.
2165 # A new group is created. All mesh elements that are common
2166 # for the two initial groups are added to the new one.
2167 # @return an instance of SMESH_Group
2168 # @ingroup l2_grps_operon
2169 def IntersectGroups(self, group1, group2, name):
2170 return self.mesh.IntersectGroups(group1, group2, name)
2172 ## Produce an intersection of groups.
2173 # New group is created. All mesh elements that are present in all
2174 # initial groups simultaneously are added to the new one
2175 # @return an instance of SMESH_Group
2176 # @ingroup l2_grps_operon
2177 def IntersectListOfGroups(self, groups, name):
2178 return self.mesh.IntersectListOfGroups(groups, name)
2180 ## Produce a cut of two groups.
2181 # A new group is created. All mesh elements that are present in
2182 # the main group but are not present in the tool group are added to the new one
2183 # @return an instance of SMESH_Group
2184 # @ingroup l2_grps_operon
2185 def CutGroups(self, main_group, tool_group, name):
2186 return self.mesh.CutGroups(main_group, tool_group, name)
2188 ## Produce a cut of groups.
2189 # A new group is created. All mesh elements that are present in main groups
2190 # but do not present in tool groups are added to the new one
2191 # @return an instance of SMESH_Group
2192 # @ingroup l2_grps_operon
2193 def CutListOfGroups(self, main_groups, tool_groups, name):
2194 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2197 # Create a standalone group of entities basing on nodes of other groups.
2198 # \param groups - list of reference groups, sub-meshes or filters, of any type.
2199 # \param elemType - a type of elements to include to the new group; either of
2200 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2201 # \param name - a name of the new group.
2202 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2203 # basing on number of element nodes common with reference \a groups.
2204 # Meaning of possible values are:
2205 # - SMESH.ALL_NODES - include if all nodes are common,
2206 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2207 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2208 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2209 # \param underlyingOnly - if \c True (default), an element is included to the
2210 # new group provided that it is based on nodes of an element of \a groups;
2211 # in this case the reference \a groups are supposed to be of higher dimension
2212 # than \a elemType, which can be useful for example to get all faces lying on
2213 # volumes of the reference \a groups.
2214 # @return an instance of SMESH_Group
2215 # @ingroup l2_grps_operon
2216 def CreateDimGroup(self, groups, elemType, name,
2217 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2218 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2220 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2223 ## Convert group on geom into standalone group
2224 # @ingroup l2_grps_operon
2225 def ConvertToStandalone(self, group):
2226 return self.mesh.ConvertToStandalone(group)
2228 # Get some info about mesh:
2229 # ------------------------
2231 ## Return the log of nodes and elements added or removed
2232 # since the previous clear of the log.
2233 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2234 # @return list of log_block structures:
2239 # @ingroup l1_auxiliary
2240 def GetLog(self, clearAfterGet):
2241 return self.mesh.GetLog(clearAfterGet)
2243 ## Clear the log of nodes and elements added or removed since the previous
2244 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2245 # @ingroup l1_auxiliary
2247 self.mesh.ClearLog()
2249 ## Toggle auto color mode on the object.
2250 # @param theAutoColor the flag which toggles auto color mode.
2252 # If switched on, a default color of a new group in Create Group dialog is chosen randomly.
2253 # @ingroup l1_grouping
2254 def SetAutoColor(self, theAutoColor):
2255 self.mesh.SetAutoColor(theAutoColor)
2257 ## Get flag of object auto color mode.
2258 # @return True or False
2259 # @ingroup l1_grouping
2260 def GetAutoColor(self):
2261 return self.mesh.GetAutoColor()
2263 ## Get the internal ID
2264 # @return integer value, which is the internal Id of the mesh
2265 # @ingroup l1_auxiliary
2267 return self.mesh.GetId()
2270 # @return integer value, which is the study Id of the mesh
2271 # @ingroup l1_auxiliary
2272 def GetStudyId(self):
2273 return self.mesh.GetStudyId()
2275 ## Check the group names for duplications.
2276 # Consider the maximum group name length stored in MED file.
2277 # @return True or False
2278 # @ingroup l1_grouping
2279 def HasDuplicatedGroupNamesMED(self):
2280 return self.mesh.HasDuplicatedGroupNamesMED()
2282 ## Obtain the mesh editor tool
2283 # @return an instance of SMESH_MeshEditor
2284 # @ingroup l1_modifying
2285 def GetMeshEditor(self):
2288 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2289 # can be passed as argument to a method accepting mesh, group or sub-mesh
2290 # @param ids list of IDs
2291 # @param elemType type of elements; this parameter is used to distinguish
2292 # IDs of nodes from IDs of elements; by default ids are treated as
2293 # IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2294 # @return an instance of SMESH_IDSource
2295 # @warning call UnRegister() for the returned object as soon as it is no more useful:
2296 # idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2297 # mesh.DoSomething( idSrc )
2298 # idSrc.UnRegister()
2299 # @ingroup l1_auxiliary
2300 def GetIDSource(self, ids, elemType = SMESH.ALL):
2301 if isinstance( ids, int ):
2303 return self.editor.MakeIDSource(ids, elemType)
2306 # Get information about mesh contents:
2307 # ------------------------------------
2309 ## Get the mesh statistic
2310 # @return dictionary type element - count of elements
2311 # @ingroup l1_meshinfo
2312 def GetMeshInfo(self, obj = None):
2313 if not obj: obj = self.mesh
2314 return self.smeshpyD.GetMeshInfo(obj)
2316 ## Return the number of nodes in the mesh
2317 # @return an integer value
2318 # @ingroup l1_meshinfo
2320 return self.mesh.NbNodes()
2322 ## Return the number of elements in the mesh
2323 # @return an integer value
2324 # @ingroup l1_meshinfo
2325 def NbElements(self):
2326 return self.mesh.NbElements()
2328 ## Return the number of 0d elements in the mesh
2329 # @return an integer value
2330 # @ingroup l1_meshinfo
2331 def Nb0DElements(self):
2332 return self.mesh.Nb0DElements()
2334 ## Return the number of ball discrete elements in the mesh
2335 # @return an integer value
2336 # @ingroup l1_meshinfo
2338 return self.mesh.NbBalls()
2340 ## Return the number of edges in the mesh
2341 # @return an integer value
2342 # @ingroup l1_meshinfo
2344 return self.mesh.NbEdges()
2346 ## Return the number of edges with the given order in the mesh
2347 # @param elementOrder the order of elements:
2348 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2349 # @return an integer value
2350 # @ingroup l1_meshinfo
2351 def NbEdgesOfOrder(self, elementOrder):
2352 return self.mesh.NbEdgesOfOrder(elementOrder)
2354 ## Return the number of faces in the mesh
2355 # @return an integer value
2356 # @ingroup l1_meshinfo
2358 return self.mesh.NbFaces()
2360 ## Return the number of faces with the given order in the mesh
2361 # @param elementOrder the order of elements:
2362 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2363 # @return an integer value
2364 # @ingroup l1_meshinfo
2365 def NbFacesOfOrder(self, elementOrder):
2366 return self.mesh.NbFacesOfOrder(elementOrder)
2368 ## Return the number of triangles in the mesh
2369 # @return an integer value
2370 # @ingroup l1_meshinfo
2371 def NbTriangles(self):
2372 return self.mesh.NbTriangles()
2374 ## Return the number of triangles with the given order in the mesh
2375 # @param elementOrder is the order of elements:
2376 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2377 # @return an integer value
2378 # @ingroup l1_meshinfo
2379 def NbTrianglesOfOrder(self, elementOrder):
2380 return self.mesh.NbTrianglesOfOrder(elementOrder)
2382 ## Return the number of biquadratic triangles in the mesh
2383 # @return an integer value
2384 # @ingroup l1_meshinfo
2385 def NbBiQuadTriangles(self):
2386 return self.mesh.NbBiQuadTriangles()
2388 ## Return the number of quadrangles in the mesh
2389 # @return an integer value
2390 # @ingroup l1_meshinfo
2391 def NbQuadrangles(self):
2392 return self.mesh.NbQuadrangles()
2394 ## Return the number of quadrangles 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 NbQuadranglesOfOrder(self, elementOrder):
2400 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2402 ## Return the number of biquadratic quadrangles in the mesh
2403 # @return an integer value
2404 # @ingroup l1_meshinfo
2405 def NbBiQuadQuadrangles(self):
2406 return self.mesh.NbBiQuadQuadrangles()
2408 ## Return the number of polygons of 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 NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2414 return self.mesh.NbPolygonsOfOrder(elementOrder)
2416 ## Return the number of volumes in the mesh
2417 # @return an integer value
2418 # @ingroup l1_meshinfo
2419 def NbVolumes(self):
2420 return self.mesh.NbVolumes()
2422 ## Return the number of volumes with the given order in the mesh
2423 # @param elementOrder 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 NbVolumesOfOrder(self, elementOrder):
2428 return self.mesh.NbVolumesOfOrder(elementOrder)
2430 ## Return the number of tetrahedrons in the mesh
2431 # @return an integer value
2432 # @ingroup l1_meshinfo
2434 return self.mesh.NbTetras()
2436 ## Return the number of tetrahedrons with the given order in the mesh
2437 # @param elementOrder the order of elements:
2438 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2439 # @return an integer value
2440 # @ingroup l1_meshinfo
2441 def NbTetrasOfOrder(self, elementOrder):
2442 return self.mesh.NbTetrasOfOrder(elementOrder)
2444 ## Return the number of hexahedrons in the mesh
2445 # @return an integer value
2446 # @ingroup l1_meshinfo
2448 return self.mesh.NbHexas()
2450 ## Return the number of hexahedrons with the given order in the mesh
2451 # @param elementOrder the order of elements:
2452 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2453 # @return an integer value
2454 # @ingroup l1_meshinfo
2455 def NbHexasOfOrder(self, elementOrder):
2456 return self.mesh.NbHexasOfOrder(elementOrder)
2458 ## Return the number of triquadratic hexahedrons in the mesh
2459 # @return an integer value
2460 # @ingroup l1_meshinfo
2461 def NbTriQuadraticHexas(self):
2462 return self.mesh.NbTriQuadraticHexas()
2464 ## Return the number of pyramids in the mesh
2465 # @return an integer value
2466 # @ingroup l1_meshinfo
2467 def NbPyramids(self):
2468 return self.mesh.NbPyramids()
2470 ## Return the number of pyramids 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 NbPyramidsOfOrder(self, elementOrder):
2476 return self.mesh.NbPyramidsOfOrder(elementOrder)
2478 ## Return the number of prisms in the mesh
2479 # @return an integer value
2480 # @ingroup l1_meshinfo
2482 return self.mesh.NbPrisms()
2484 ## Return the number of prisms 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 NbPrismsOfOrder(self, elementOrder):
2490 return self.mesh.NbPrismsOfOrder(elementOrder)
2492 ## Return the number of hexagonal prisms in the mesh
2493 # @return an integer value
2494 # @ingroup l1_meshinfo
2495 def NbHexagonalPrisms(self):
2496 return self.mesh.NbHexagonalPrisms()
2498 ## Return the number of polyhedrons in the mesh
2499 # @return an integer value
2500 # @ingroup l1_meshinfo
2501 def NbPolyhedrons(self):
2502 return self.mesh.NbPolyhedrons()
2504 ## Return the number of submeshes in the mesh
2505 # @return an integer value
2506 # @ingroup l1_meshinfo
2507 def NbSubMesh(self):
2508 return self.mesh.NbSubMesh()
2510 ## Return the list of mesh elements IDs
2511 # @return the list of integer values
2512 # @ingroup l1_meshinfo
2513 def GetElementsId(self):
2514 return self.mesh.GetElementsId()
2516 ## Return the list of IDs of mesh elements with the given type
2517 # @param elementType the required type of elements, either of
2518 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2519 # @return list of integer values
2520 # @ingroup l1_meshinfo
2521 def GetElementsByType(self, elementType):
2522 return self.mesh.GetElementsByType(elementType)
2524 ## Return the list of mesh nodes IDs
2525 # @return the list of integer values
2526 # @ingroup l1_meshinfo
2527 def GetNodesId(self):
2528 return self.mesh.GetNodesId()
2530 # Get the information about mesh elements:
2531 # ------------------------------------
2533 ## Return the type of mesh element
2534 # @return the value from SMESH::ElementType enumeration
2535 # Type SMESH.ElementType._items in the Python Console to see all possible values.
2536 # @ingroup l1_meshinfo
2537 def GetElementType(self, id, iselem=True):
2538 return self.mesh.GetElementType(id, iselem)
2540 ## Return the geometric type of mesh element
2541 # @return the value from SMESH::EntityType enumeration
2542 # Type SMESH.EntityType._items in the Python Console to see all possible values.
2543 # @ingroup l1_meshinfo
2544 def GetElementGeomType(self, id):
2545 return self.mesh.GetElementGeomType(id)
2547 ## Return the shape type of mesh element
2548 # @return the value from SMESH::GeometryType enumeration.
2549 # Type SMESH.GeometryType._items in the Python Console to see all possible values.
2550 # @ingroup l1_meshinfo
2551 def GetElementShape(self, id):
2552 return self.mesh.GetElementShape(id)
2554 ## Return the list of submesh elements IDs
2555 # @param Shape a geom object(sub-shape)
2556 # Shape must be the sub-shape of a ShapeToMesh()
2557 # @return the list of integer values
2558 # @ingroup l1_meshinfo
2559 def GetSubMeshElementsId(self, Shape):
2560 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2561 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2564 return self.mesh.GetSubMeshElementsId(ShapeID)
2566 ## Return the list of submesh nodes IDs
2567 # @param Shape a geom object(sub-shape)
2568 # Shape must be the sub-shape of a ShapeToMesh()
2569 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2570 # @return the list of integer values
2571 # @ingroup l1_meshinfo
2572 def GetSubMeshNodesId(self, Shape, all):
2573 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2574 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2577 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2579 ## Return type of elements on given shape
2580 # @param Shape a geom object(sub-shape)
2581 # Shape must be a sub-shape of a ShapeToMesh()
2582 # @return element type
2583 # @ingroup l1_meshinfo
2584 def GetSubMeshElementType(self, Shape):
2585 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2586 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2589 return self.mesh.GetSubMeshElementType(ShapeID)
2591 ## Get the mesh description
2592 # @return string value
2593 # @ingroup l1_meshinfo
2595 return self.mesh.Dump()
2598 # Get the information about nodes and elements of a mesh by its IDs:
2599 # -----------------------------------------------------------
2601 ## Get XYZ coordinates of a node
2602 # \n If there is no nodes for the given ID - return an empty list
2603 # @return a list of double precision values
2604 # @ingroup l1_meshinfo
2605 def GetNodeXYZ(self, id):
2606 return self.mesh.GetNodeXYZ(id)
2608 ## Return list of IDs of inverse elements for the given node
2609 # \n If there is no node for the given ID - return an empty list
2610 # @return a list of integer values
2611 # @ingroup l1_meshinfo
2612 def GetNodeInverseElements(self, id):
2613 return self.mesh.GetNodeInverseElements(id)
2615 ## Return the position of a node on the shape
2616 # @return SMESH::NodePosition
2617 # @ingroup l1_meshinfo
2618 def GetNodePosition(self,NodeID):
2619 return self.mesh.GetNodePosition(NodeID)
2621 ## Return the position of an element on the shape
2622 # @return SMESH::ElementPosition
2623 # @ingroup l1_meshinfo
2624 def GetElementPosition(self,ElemID):
2625 return self.mesh.GetElementPosition(ElemID)
2627 ## Return the ID of the shape, on which the given node was generated.
2628 # @return an integer value > 0 or -1 if there is no node for the given
2629 # ID or the node is not assigned to any geometry
2630 # @ingroup l1_meshinfo
2631 def GetShapeID(self, id):
2632 return self.mesh.GetShapeID(id)
2634 ## Return the ID of the shape, on which the given element was generated.
2635 # @return an integer value > 0 or -1 if there is no element for the given
2636 # ID or the element is not assigned to any geometry
2637 # @ingroup l1_meshinfo
2638 def GetShapeIDForElem(self,id):
2639 return self.mesh.GetShapeIDForElem(id)
2641 ## Return the number of nodes of the given element
2642 # @return an integer value > 0 or -1 if there is no element for the given ID
2643 # @ingroup l1_meshinfo
2644 def GetElemNbNodes(self, id):
2645 return self.mesh.GetElemNbNodes(id)
2647 ## Return the node ID the given (zero based) index for the given element
2648 # \n If there is no element for the given ID - return -1
2649 # \n If there is no node for the given index - return -2
2650 # @return an integer value
2651 # @ingroup l1_meshinfo
2652 def GetElemNode(self, id, index):
2653 return self.mesh.GetElemNode(id, index)
2655 ## Return the IDs of nodes of the given element
2656 # @return a list of integer values
2657 # @ingroup l1_meshinfo
2658 def GetElemNodes(self, id):
2659 return self.mesh.GetElemNodes(id)
2661 ## Return true if the given node is the medium node in the given quadratic element
2662 # @ingroup l1_meshinfo
2663 def IsMediumNode(self, elementID, nodeID):
2664 return self.mesh.IsMediumNode(elementID, nodeID)
2666 ## Return true if the given node is the medium node in one of quadratic elements
2667 # @param nodeID ID of the node
2668 # @param elementType the type of elements to check a state of the node, either of
2669 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2670 # @ingroup l1_meshinfo
2671 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2672 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2674 ## Return the number of edges for the given element
2675 # @ingroup l1_meshinfo
2676 def ElemNbEdges(self, id):
2677 return self.mesh.ElemNbEdges(id)
2679 ## Return the number of faces for the given element
2680 # @ingroup l1_meshinfo
2681 def ElemNbFaces(self, id):
2682 return self.mesh.ElemNbFaces(id)
2684 ## Return nodes of given face (counted from zero) for given volumic element.
2685 # @ingroup l1_meshinfo
2686 def GetElemFaceNodes(self,elemId, faceIndex):
2687 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2689 ## Return three components of normal of given mesh face
2690 # (or an empty array in KO case)
2691 # @ingroup l1_meshinfo
2692 def GetFaceNormal(self, faceId, normalized=False):
2693 return self.mesh.GetFaceNormal(faceId,normalized)
2695 ## Return an element based on all given nodes.
2696 # @ingroup l1_meshinfo
2697 def FindElementByNodes(self, nodes):
2698 return self.mesh.FindElementByNodes(nodes)
2700 ## Return elements including all given nodes.
2701 # @ingroup l1_meshinfo
2702 def GetElementsByNodes(self, nodes, elemType=SMESH.ALL):
2703 return self.mesh.GetElementsByNodes( nodes, elemType )
2705 ## Return true if the given element is a polygon
2706 # @ingroup l1_meshinfo
2707 def IsPoly(self, id):
2708 return self.mesh.IsPoly(id)
2710 ## Return true if the given element is quadratic
2711 # @ingroup l1_meshinfo
2712 def IsQuadratic(self, id):
2713 return self.mesh.IsQuadratic(id)
2715 ## Return diameter of a ball discrete element or zero in case of an invalid \a id
2716 # @ingroup l1_meshinfo
2717 def GetBallDiameter(self, id):
2718 return self.mesh.GetBallDiameter(id)
2720 ## Return XYZ coordinates of the barycenter of the given element
2721 # \n If there is no element for the given ID - return an empty list
2722 # @return a list of three double values
2723 # @ingroup l1_meshinfo
2724 def BaryCenter(self, id):
2725 return self.mesh.BaryCenter(id)
2727 ## Pass mesh elements through the given filter and return IDs of fitting elements
2728 # @param theFilter SMESH_Filter
2729 # @return a list of ids
2730 # @ingroup l1_controls
2731 def GetIdsFromFilter(self, theFilter):
2732 theFilter.SetMesh( self.mesh )
2733 return theFilter.GetIDs()
2735 # Get mesh measurements information:
2736 # ------------------------------------
2738 ## Verify whether a 2D mesh element has free edges (edges connected to one face only)\n
2739 # Return a list of special structures (borders).
2740 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2741 # @ingroup l1_measurements
2742 def GetFreeBorders(self):
2743 aFilterMgr = self.smeshpyD.CreateFilterManager()
2744 aPredicate = aFilterMgr.CreateFreeEdges()
2745 aPredicate.SetMesh(self.mesh)
2746 aBorders = aPredicate.GetBorders()
2747 aFilterMgr.UnRegister()
2750 ## Get minimum distance between two nodes, elements or distance to the origin
2751 # @param id1 first node/element id
2752 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2753 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2754 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2755 # @return minimum distance value
2756 # @sa GetMinDistance()
2757 # @ingroup l1_measurements
2758 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2759 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2760 return aMeasure.value
2762 ## Get measure structure specifying minimum distance data between two objects
2763 # @param id1 first node/element id
2764 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2765 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2766 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2767 # @return Measure structure
2769 # @ingroup l1_measurements
2770 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2772 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2774 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2777 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2779 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2784 aMeasurements = self.smeshpyD.CreateMeasurements()
2785 aMeasure = aMeasurements.MinDistance(id1, id2)
2786 genObjUnRegister([aMeasurements,id1, id2])
2789 ## Get bounding box of the specified object(s)
2790 # @param objects single source object or list of source objects or list of nodes/elements IDs
2791 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2792 # @c False specifies that @a objects are nodes
2793 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2794 # @sa GetBoundingBox()
2795 # @ingroup l1_measurements
2796 def BoundingBox(self, objects=None, isElem=False):
2797 result = self.GetBoundingBox(objects, isElem)
2801 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2804 ## Get measure structure specifying bounding box data of the specified object(s)
2805 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2806 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2807 # @c False specifies that @a objects are nodes
2808 # @return Measure structure
2810 # @ingroup l1_measurements
2811 def GetBoundingBox(self, IDs=None, isElem=False):
2814 elif isinstance(IDs, tuple):
2816 if not isinstance(IDs, list):
2818 if len(IDs) > 0 and isinstance(IDs[0], int):
2821 unRegister = genObjUnRegister()
2823 if isinstance(o, Mesh):
2824 srclist.append(o.mesh)
2825 elif hasattr(o, "_narrow"):
2826 src = o._narrow(SMESH.SMESH_IDSource)
2827 if src: srclist.append(src)
2829 elif isinstance(o, list):
2831 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2833 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2834 unRegister.set( srclist[-1] )
2837 aMeasurements = self.smeshpyD.CreateMeasurements()
2838 unRegister.set( aMeasurements )
2839 aMeasure = aMeasurements.BoundingBox(srclist)
2842 # Mesh edition (SMESH_MeshEditor functionality):
2843 # ---------------------------------------------
2845 ## Remove the elements from the mesh by ids
2846 # @param IDsOfElements is a list of ids of elements to remove
2847 # @return True or False
2848 # @ingroup l2_modif_del
2849 def RemoveElements(self, IDsOfElements):
2850 return self.editor.RemoveElements(IDsOfElements)
2852 ## Remove nodes from mesh by ids
2853 # @param IDsOfNodes is a list of ids of nodes to remove
2854 # @return True or False
2855 # @ingroup l2_modif_del
2856 def RemoveNodes(self, IDsOfNodes):
2857 return self.editor.RemoveNodes(IDsOfNodes)
2859 ## Remove all orphan (free) nodes from mesh
2860 # @return number of the removed nodes
2861 # @ingroup l2_modif_del
2862 def RemoveOrphanNodes(self):
2863 return self.editor.RemoveOrphanNodes()
2865 ## Add a node to the mesh by coordinates
2866 # @return Id of the new node
2867 # @ingroup l2_modif_add
2868 def AddNode(self, x, y, z):
2869 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2870 if hasVars: self.mesh.SetParameters(Parameters)
2871 return self.editor.AddNode( x, y, z)
2873 ## Create a 0D element on a node with given number.
2874 # @param IDOfNode the ID of node for creation of the element.
2875 # @param DuplicateElements to add one more 0D element to a node or not
2876 # @return the Id of the new 0D element
2877 # @ingroup l2_modif_add
2878 def Add0DElement( self, IDOfNode, DuplicateElements=True ):
2879 return self.editor.Add0DElement( IDOfNode, DuplicateElements )
2881 ## Create 0D elements on all nodes of the given elements except those
2882 # nodes on which a 0D element already exists.
2883 # @param theObject an object on whose nodes 0D elements will be created.
2884 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2885 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2886 # @param theGroupName optional name of a group to add 0D elements created
2887 # and/or found on nodes of \a theObject.
2888 # @param DuplicateElements to add one more 0D element to a node or not
2889 # @return an object (a new group or a temporary SMESH_IDSource) holding
2890 # IDs of new and/or found 0D elements. IDs of 0D elements
2891 # can be retrieved from the returned object by calling GetIDs()
2892 # @ingroup l2_modif_add
2893 def Add0DElementsToAllNodes(self, theObject, theGroupName="", DuplicateElements=False):
2894 unRegister = genObjUnRegister()
2895 if isinstance( theObject, Mesh ):
2896 theObject = theObject.GetMesh()
2897 elif isinstance( theObject, list ):
2898 theObject = self.GetIDSource( theObject, SMESH.ALL )
2899 unRegister.set( theObject )
2900 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName, DuplicateElements )
2902 ## Create a ball element on a node with given ID.
2903 # @param IDOfNode the ID of node for creation of the element.
2904 # @param diameter the bal diameter.
2905 # @return the Id of the new ball element
2906 # @ingroup l2_modif_add
2907 def AddBall(self, IDOfNode, diameter):
2908 return self.editor.AddBall( IDOfNode, diameter )
2910 ## Create a linear or quadratic edge (this is determined
2911 # by the number of given nodes).
2912 # @param IDsOfNodes the list of node IDs for creation of the element.
2913 # The order of nodes in this list should correspond to the description
2914 # of MED. \n This description is located by the following link:
2915 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2916 # @return the Id of the new edge
2917 # @ingroup l2_modif_add
2918 def AddEdge(self, IDsOfNodes):
2919 return self.editor.AddEdge(IDsOfNodes)
2921 ## Create a linear or quadratic face (this is determined
2922 # by the number of given nodes).
2923 # @param IDsOfNodes the list of node IDs for creation of the element.
2924 # The order of nodes in this list should correspond to the description
2925 # of MED. \n This description is located by the following link:
2926 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2927 # @return the Id of the new face
2928 # @ingroup l2_modif_add
2929 def AddFace(self, IDsOfNodes):
2930 return self.editor.AddFace(IDsOfNodes)
2932 ## Add a polygonal face to the mesh by the list of node IDs
2933 # @param IdsOfNodes the list of node IDs for creation of the element.
2934 # @return the Id of the new face
2935 # @ingroup l2_modif_add
2936 def AddPolygonalFace(self, IdsOfNodes):
2937 return self.editor.AddPolygonalFace(IdsOfNodes)
2939 ## Add a quadratic polygonal face to the mesh by the list of node IDs
2940 # @param IdsOfNodes the list of node IDs for creation of the element;
2941 # corner nodes follow first.
2942 # @return the Id of the new face
2943 # @ingroup l2_modif_add
2944 def AddQuadPolygonalFace(self, IdsOfNodes):
2945 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
2947 ## Create both simple and quadratic volume (this is determined
2948 # by the number of given nodes).
2949 # @param IDsOfNodes the list of node IDs for creation of the element.
2950 # The order of nodes in this list should correspond to the description
2951 # of MED. \n This description is located by the following link:
2952 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2953 # @return the Id of the new volumic element
2954 # @ingroup l2_modif_add
2955 def AddVolume(self, IDsOfNodes):
2956 return self.editor.AddVolume(IDsOfNodes)
2958 ## Create a volume of many faces, giving nodes for each face.
2959 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2960 # @param Quantities the list of integer values, Quantities[i]
2961 # gives the quantity of nodes in face number i.
2962 # @return the Id of the new volumic element
2963 # @ingroup l2_modif_add
2964 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2965 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2967 ## Create a volume of many faces, giving the IDs of the existing faces.
2968 # @param IdsOfFaces the list of face IDs for volume creation.
2970 # Note: The created volume will refer only to the nodes
2971 # of the given faces, not to the faces themselves.
2972 # @return the Id of the new volumic element
2973 # @ingroup l2_modif_add
2974 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2975 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2978 ## @brief Binds a node to a vertex
2979 # @param NodeID a node ID
2980 # @param Vertex a vertex or vertex ID
2981 # @return True if succeed else raises an exception
2982 # @ingroup l2_modif_add
2983 def SetNodeOnVertex(self, NodeID, Vertex):
2984 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2985 VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
2989 self.editor.SetNodeOnVertex(NodeID, VertexID)
2990 except SALOME.SALOME_Exception, inst:
2991 raise ValueError, inst.details.text
2995 ## @brief Stores the node position on an edge
2996 # @param NodeID a node ID
2997 # @param Edge an edge or edge ID
2998 # @param paramOnEdge a parameter on the edge where the node is located
2999 # @return True if succeed else raises an exception
3000 # @ingroup l2_modif_add
3001 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
3002 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
3003 EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
3007 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
3008 except SALOME.SALOME_Exception, inst:
3009 raise ValueError, inst.details.text
3012 ## @brief Stores node position on a face
3013 # @param NodeID a node ID
3014 # @param Face a face or face ID
3015 # @param u U parameter on the face where the node is located
3016 # @param v V parameter on the face where the node is located
3017 # @return True if succeed else raises an exception
3018 # @ingroup l2_modif_add
3019 def SetNodeOnFace(self, NodeID, Face, u, v):
3020 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
3021 FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
3025 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
3026 except SALOME.SALOME_Exception, inst:
3027 raise ValueError, inst.details.text
3030 ## @brief Binds a node to a solid
3031 # @param NodeID a node ID
3032 # @param Solid a solid or solid ID
3033 # @return True if succeed else raises an exception
3034 # @ingroup l2_modif_add
3035 def SetNodeInVolume(self, NodeID, Solid):
3036 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
3037 SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
3041 self.editor.SetNodeInVolume(NodeID, SolidID)
3042 except SALOME.SALOME_Exception, inst:
3043 raise ValueError, inst.details.text
3046 ## @brief Bind an element to a shape
3047 # @param ElementID an element ID
3048 # @param Shape a shape or shape ID
3049 # @return True if succeed else raises an exception
3050 # @ingroup l2_modif_add
3051 def SetMeshElementOnShape(self, ElementID, Shape):
3052 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
3053 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3057 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
3058 except SALOME.SALOME_Exception, inst:
3059 raise ValueError, inst.details.text
3063 ## Move the node with the given id
3064 # @param NodeID the id of the node
3065 # @param x a new X coordinate
3066 # @param y a new Y coordinate
3067 # @param z a new Z coordinate
3068 # @return True if succeed else False
3069 # @ingroup l2_modif_edit
3070 def MoveNode(self, NodeID, x, y, z):
3071 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3072 if hasVars: self.mesh.SetParameters(Parameters)
3073 return self.editor.MoveNode(NodeID, x, y, z)
3075 ## Find the node closest to a point and moves it to a point location
3076 # @param x the X coordinate of a point
3077 # @param y the Y coordinate of a point
3078 # @param z the Z coordinate of a point
3079 # @param NodeID if specified (>0), the node with this ID is moved,
3080 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
3081 # @return the ID of a node
3082 # @ingroup l2_modif_edit
3083 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3084 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3085 if hasVars: self.mesh.SetParameters(Parameters)
3086 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3088 ## Find the node closest to a point
3089 # @param x the X coordinate of a point
3090 # @param y the Y coordinate of a point
3091 # @param z the Z coordinate of a point
3092 # @return the ID of a node
3093 # @ingroup l1_meshinfo
3094 def FindNodeClosestTo(self, x, y, z):
3095 #preview = self.mesh.GetMeshEditPreviewer()
3096 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3097 return self.editor.FindNodeClosestTo(x, y, z)
3099 ## Find the elements where a point lays IN or ON
3100 # @param x the X coordinate of a point
3101 # @param y the Y coordinate of a point
3102 # @param z the Z coordinate of a point
3103 # @param elementType type of elements to find; either of
3104 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3105 # means elements of any type excluding nodes, discrete and 0D elements.
3106 # @param meshPart a part of mesh (group, sub-mesh) to search within
3107 # @return list of IDs of found elements
3108 # @ingroup l1_meshinfo
3109 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3111 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
3113 return self.editor.FindElementsByPoint(x, y, z, elementType)
3115 ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
3116 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
3117 # UNKNOWN state means that either mesh is wrong or the analysis fails.
3118 # @ingroup l1_meshinfo
3119 def GetPointState(self, x, y, z):
3120 return self.editor.GetPointState(x, y, z)
3122 ## Check if a 2D mesh is manifold
3123 # @ingroup l1_controls
3124 def IsManifold(self):
3125 return self.editor.IsManifold()
3127 ## Check if orientation of 2D elements is coherent
3128 # @ingroup l1_controls
3129 def IsCoherentOrientation2D(self):
3130 return self.editor.IsCoherentOrientation2D()
3132 ## Find the node closest to a point and moves it to a point location
3133 # @param x the X coordinate of a point
3134 # @param y the Y coordinate of a point
3135 # @param z the Z coordinate of a point
3136 # @return the ID of a moved node
3137 # @ingroup l2_modif_edit
3138 def MeshToPassThroughAPoint(self, x, y, z):
3139 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3141 ## Replace two neighbour triangles sharing Node1-Node2 link
3142 # with the triangles built on the same 4 nodes but having other common link.
3143 # @param NodeID1 the ID of the first node
3144 # @param NodeID2 the ID of the second node
3145 # @return false if proper faces were not found
3146 # @ingroup l2_modif_cutquadr
3147 def InverseDiag(self, NodeID1, NodeID2):
3148 return self.editor.InverseDiag(NodeID1, NodeID2)
3150 ## Replace two neighbour triangles sharing Node1-Node2 link
3151 # with a quadrangle built on the same 4 nodes.
3152 # @param NodeID1 the ID of the first node
3153 # @param NodeID2 the ID of the second node
3154 # @return false if proper faces were not found
3155 # @ingroup l2_modif_unitetri
3156 def DeleteDiag(self, NodeID1, NodeID2):
3157 return self.editor.DeleteDiag(NodeID1, NodeID2)
3159 ## Reorient elements by ids
3160 # @param IDsOfElements if undefined reorients all mesh elements
3161 # @return True if succeed else False
3162 # @ingroup l2_modif_changori
3163 def Reorient(self, IDsOfElements=None):
3164 if IDsOfElements == None:
3165 IDsOfElements = self.GetElementsId()
3166 return self.editor.Reorient(IDsOfElements)
3168 ## Reorient all elements of the object
3169 # @param theObject mesh, submesh or group
3170 # @return True if succeed else False
3171 # @ingroup l2_modif_changori
3172 def ReorientObject(self, theObject):
3173 if ( isinstance( theObject, Mesh )):
3174 theObject = theObject.GetMesh()
3175 return self.editor.ReorientObject(theObject)
3177 ## Reorient faces contained in \a the2DObject.
3178 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3179 # @param theDirection is a desired direction of normal of \a theFace.
3180 # It can be either a GEOM vector or a list of coordinates [x,y,z].
3181 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3182 # compared with theDirection. It can be either ID of face or a point
3183 # by which the face will be found. The point can be given as either
3184 # a GEOM vertex or a list of point coordinates.
3185 # @return number of reoriented faces
3186 # @ingroup l2_modif_changori
3187 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3188 unRegister = genObjUnRegister()
3190 if isinstance( the2DObject, Mesh ):
3191 the2DObject = the2DObject.GetMesh()
3192 if isinstance( the2DObject, list ):
3193 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3194 unRegister.set( the2DObject )
3195 # check theDirection
3196 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3197 theDirection = self.smeshpyD.GetDirStruct( theDirection )
3198 if isinstance( theDirection, list ):
3199 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
3200 # prepare theFace and thePoint
3201 theFace = theFaceOrPoint
3202 thePoint = PointStruct(0,0,0)
3203 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3204 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3206 if isinstance( theFaceOrPoint, list ):
3207 thePoint = PointStruct( *theFaceOrPoint )
3209 if isinstance( theFaceOrPoint, PointStruct ):
3210 thePoint = theFaceOrPoint
3212 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3214 ## Reorient faces according to adjacent volumes.
3215 # @param the2DObject is a mesh, sub-mesh, group or list of
3216 # either IDs of faces or face groups.
3217 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3218 # @param theOutsideNormal to orient faces to have their normals
3219 # pointing either \a outside or \a inside the adjacent volumes.
3220 # @return number of reoriented faces.
3221 # @ingroup l2_modif_changori
3222 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3223 unRegister = genObjUnRegister()
3225 if not isinstance( the2DObject, list ):
3226 the2DObject = [ the2DObject ]
3227 elif the2DObject and isinstance( the2DObject[0], int ):
3228 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3229 unRegister.set( the2DObject )
3230 the2DObject = [ the2DObject ]
3231 for i,obj2D in enumerate( the2DObject ):
3232 if isinstance( obj2D, Mesh ):
3233 the2DObject[i] = obj2D.GetMesh()
3234 if isinstance( obj2D, list ):
3235 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3236 unRegister.set( the2DObject[i] )
3238 if isinstance( the3DObject, Mesh ):
3239 the3DObject = the3DObject.GetMesh()
3240 if isinstance( the3DObject, list ):
3241 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3242 unRegister.set( the3DObject )
3243 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3245 ## Fuse the neighbouring triangles into quadrangles.
3246 # @param IDsOfElements The triangles to be fused.
3247 # @param theCriterion a numerical functor, in terms of enum SMESH.FunctorType, used to
3248 # applied to possible quadrangles to choose a neighbour to fuse with.
3249 # Type SMESH.FunctorType._items in the Python Console to see all items.
3250 # Note that not all items correspond to numerical functors.
3251 # @param MaxAngle is the maximum angle between element normals at which the fusion
3252 # is still performed; theMaxAngle is measured in radians.
3253 # Also it could be a name of variable which defines angle in degrees.
3254 # @return TRUE in case of success, FALSE otherwise.
3255 # @ingroup l2_modif_unitetri
3256 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3257 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3258 self.mesh.SetParameters(Parameters)
3259 if not IDsOfElements:
3260 IDsOfElements = self.GetElementsId()
3261 Functor = self.smeshpyD.GetFunctor(theCriterion)
3262 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3264 ## Fuse the neighbouring triangles of the object into quadrangles
3265 # @param theObject is mesh, submesh or group
3266 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType,
3267 # applied to possible quadrangles to choose a neighbour to fuse with.
3268 # Type SMESH.FunctorType._items in the Python Console to see all items.
3269 # Note that not all items correspond to numerical functors.
3270 # @param MaxAngle a max angle between element normals at which the fusion
3271 # is still performed; theMaxAngle is measured in radians.
3272 # @return TRUE in case of success, FALSE otherwise.
3273 # @ingroup l2_modif_unitetri
3274 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3275 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3276 self.mesh.SetParameters(Parameters)
3277 if isinstance( theObject, Mesh ):
3278 theObject = theObject.GetMesh()
3279 Functor = self.smeshpyD.GetFunctor(theCriterion)
3280 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3282 ## Split quadrangles into triangles.
3283 # @param IDsOfElements the faces to be splitted.
3284 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3285 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3286 # value, then quadrangles will be split by the smallest diagonal.
3287 # Type SMESH.FunctorType._items in the Python Console to see all items.
3288 # Note that not all items correspond to numerical functors.
3289 # @return TRUE in case of success, FALSE otherwise.
3290 # @ingroup l2_modif_cutquadr
3291 def QuadToTri (self, IDsOfElements, theCriterion = None):
3292 if IDsOfElements == []:
3293 IDsOfElements = self.GetElementsId()
3294 if theCriterion is None:
3295 theCriterion = FT_MaxElementLength2D
3296 Functor = self.smeshpyD.GetFunctor(theCriterion)
3297 return self.editor.QuadToTri(IDsOfElements, Functor)
3299 ## Split quadrangles into triangles.
3300 # @param theObject the object from which the list of elements is taken,
3301 # this is mesh, submesh or group
3302 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3303 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3304 # value, then quadrangles will be split by the smallest diagonal.
3305 # Type SMESH.FunctorType._items in the Python Console to see all items.
3306 # Note that not all items correspond to numerical functors.
3307 # @return TRUE in case of success, FALSE otherwise.
3308 # @ingroup l2_modif_cutquadr
3309 def QuadToTriObject (self, theObject, theCriterion = None):
3310 if ( isinstance( theObject, Mesh )):
3311 theObject = theObject.GetMesh()
3312 if theCriterion is None:
3313 theCriterion = FT_MaxElementLength2D
3314 Functor = self.smeshpyD.GetFunctor(theCriterion)
3315 return self.editor.QuadToTriObject(theObject, Functor)
3317 ## Split each of given quadrangles into 4 triangles. A node is added at the center of
3319 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3320 # group or a list of face IDs. By default all quadrangles are split
3321 # @ingroup l2_modif_cutquadr
3322 def QuadTo4Tri (self, theElements=[]):
3323 unRegister = genObjUnRegister()
3324 if isinstance( theElements, Mesh ):
3325 theElements = theElements.mesh
3326 elif not theElements:
3327 theElements = self.mesh
3328 elif isinstance( theElements, list ):
3329 theElements = self.GetIDSource( theElements, SMESH.FACE )
3330 unRegister.set( theElements )
3331 return self.editor.QuadTo4Tri( theElements )
3333 ## Split quadrangles into triangles.
3334 # @param IDsOfElements the faces to be splitted
3335 # @param Diag13 is used to choose a diagonal for splitting.
3336 # @return TRUE in case of success, FALSE otherwise.
3337 # @ingroup l2_modif_cutquadr
3338 def SplitQuad (self, IDsOfElements, Diag13):
3339 if IDsOfElements == []:
3340 IDsOfElements = self.GetElementsId()
3341 return self.editor.SplitQuad(IDsOfElements, Diag13)
3343 ## Split quadrangles into triangles.
3344 # @param theObject the object from which the list of elements is taken,
3345 # this is mesh, submesh or group
3346 # @param Diag13 is used to choose a diagonal for splitting.
3347 # @return TRUE in case of success, FALSE otherwise.
3348 # @ingroup l2_modif_cutquadr
3349 def SplitQuadObject (self, theObject, Diag13):
3350 if ( isinstance( theObject, Mesh )):
3351 theObject = theObject.GetMesh()
3352 return self.editor.SplitQuadObject(theObject, Diag13)
3354 ## Find a better splitting of the given quadrangle.
3355 # @param IDOfQuad the ID of the quadrangle to be splitted.
3356 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3357 # choose a diagonal for splitting.
3358 # Type SMESH.FunctorType._items in the Python Console to see all items.
3359 # Note that not all items correspond to numerical functors.
3360 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3361 # diagonal is better, 0 if error occurs.
3362 # @ingroup l2_modif_cutquadr
3363 def BestSplit (self, IDOfQuad, theCriterion):
3364 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3366 ## Split volumic elements into tetrahedrons
3367 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3368 # @param method flags passing splitting method:
3369 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3370 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3371 # @ingroup l2_modif_cutquadr
3372 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3373 unRegister = genObjUnRegister()
3374 if isinstance( elems, Mesh ):
3375 elems = elems.GetMesh()
3376 if ( isinstance( elems, list )):
3377 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3378 unRegister.set( elems )
3379 self.editor.SplitVolumesIntoTetra(elems, method)
3382 ## Split bi-quadratic elements into linear ones without creation of additional nodes:
3383 # - bi-quadratic triangle will be split into 3 linear quadrangles;
3384 # - bi-quadratic quadrangle will be split into 4 linear quadrangles;
3385 # - tri-quadratic hexahedron will be split into 8 linear hexahedra.
3386 # Quadratic elements of lower dimension adjacent to the split bi-quadratic element
3387 # will be split in order to keep the mesh conformal.
3388 # @param elems - elements to split: sub-meshes, groups, filters or element IDs;
3389 # if None (default), all bi-quadratic elements will be split
3390 # @ingroup l2_modif_cutquadr
3391 def SplitBiQuadraticIntoLinear(self, elems=None):
3392 unRegister = genObjUnRegister()
3393 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
3394 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
3395 unRegister.set( elems )
3397 elems = [ self.GetMesh() ]
3398 if isinstance( elems, Mesh ):
3399 elems = [ elems.GetMesh() ]
3400 if not isinstance( elems, list ):
3402 self.editor.SplitBiQuadraticIntoLinear( elems )
3404 ## Split hexahedra into prisms
3405 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3406 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3407 # gives a normal vector defining facets to split into triangles.
3408 # @a startHexPoint can be either a triple of coordinates or a vertex.
3409 # @param facetNormal a normal to a facet to split into triangles of a
3410 # hexahedron found by @a startHexPoint.
3411 # @a facetNormal can be either a triple of coordinates or an edge.
3412 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3413 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3414 # @param allDomains if @c False, only hexahedra adjacent to one closest
3415 # to @a startHexPoint are split, else @a startHexPoint
3416 # is used to find the facet to split in all domains present in @a elems.
3417 # @ingroup l2_modif_cutquadr
3418 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3419 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3421 unRegister = genObjUnRegister()
3422 if isinstance( elems, Mesh ):
3423 elems = elems.GetMesh()
3424 if ( isinstance( elems, list )):
3425 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3426 unRegister.set( elems )
3429 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3430 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3431 elif isinstance( startHexPoint, list ):
3432 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3435 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3436 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3437 elif isinstance( facetNormal, list ):
3438 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3441 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3443 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3445 ## Split quadrangle faces near triangular facets of volumes
3447 # @ingroup l2_modif_cutquadr
3448 def SplitQuadsNearTriangularFacets(self):
3449 faces_array = self.GetElementsByType(SMESH.FACE)
3450 for face_id in faces_array:
3451 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3452 quad_nodes = self.mesh.GetElemNodes(face_id)
3453 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3454 isVolumeFound = False
3455 for node1_elem in node1_elems:
3456 if not isVolumeFound:
3457 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3458 nb_nodes = self.GetElemNbNodes(node1_elem)
3459 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3460 volume_elem = node1_elem
3461 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3462 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3463 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3464 isVolumeFound = True
3465 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3466 self.SplitQuad([face_id], False) # diagonal 2-4
3467 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3468 isVolumeFound = True
3469 self.SplitQuad([face_id], True) # diagonal 1-3
3470 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3471 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3472 isVolumeFound = True
3473 self.SplitQuad([face_id], True) # diagonal 1-3
3475 ## @brief Splits hexahedrons into tetrahedrons.
3477 # This operation uses pattern mapping functionality for splitting.
3478 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3479 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3480 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3481 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3482 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3483 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3484 # @return TRUE in case of success, FALSE otherwise.
3485 # @ingroup l2_modif_cutquadr
3486 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3487 # Pattern: 5.---------.6
3492 # (0,0,1) 4.---------.7 * |
3499 # (0,0,0) 0.---------.3
3500 pattern_tetra = "!!! Nb of points: \n 8 \n\
3510 !!! Indices of points of 6 tetras: \n\
3518 pattern = self.smeshpyD.GetPattern()
3519 isDone = pattern.LoadFromFile(pattern_tetra)
3521 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3524 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3525 isDone = pattern.MakeMesh(self.mesh, False, False)
3526 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3528 # split quafrangle faces near triangular facets of volumes
3529 self.SplitQuadsNearTriangularFacets()
3533 ## @brief Split hexahedrons into prisms.
3535 # Uses the pattern mapping functionality for splitting.
3536 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3537 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3538 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3539 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3540 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3541 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3542 # @return TRUE in case of success, FALSE otherwise.
3543 # @ingroup l2_modif_cutquadr
3544 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3545 # Pattern: 5.---------.6
3550 # (0,0,1) 4.---------.7 |
3557 # (0,0,0) 0.---------.3
3558 pattern_prism = "!!! Nb of points: \n 8 \n\
3568 !!! Indices of points of 2 prisms: \n\
3572 pattern = self.smeshpyD.GetPattern()
3573 isDone = pattern.LoadFromFile(pattern_prism)
3575 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3578 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3579 isDone = pattern.MakeMesh(self.mesh, False, False)
3580 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3582 # Split quafrangle faces near triangular facets of volumes
3583 self.SplitQuadsNearTriangularFacets()
3588 # @param IDsOfElements the list if ids of elements to smooth
3589 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3590 # Note that nodes built on edges and boundary nodes are always fixed.
3591 # @param MaxNbOfIterations the maximum number of iterations
3592 # @param MaxAspectRatio varies in range [1.0, inf]
3593 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3594 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3595 # @return TRUE in case of success, FALSE otherwise.
3596 # @ingroup l2_modif_smooth
3597 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3598 MaxNbOfIterations, MaxAspectRatio, Method):
3599 if IDsOfElements == []:
3600 IDsOfElements = self.GetElementsId()
3601 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3602 self.mesh.SetParameters(Parameters)
3603 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3604 MaxNbOfIterations, MaxAspectRatio, Method)
3606 ## Smooth elements which belong to the given object
3607 # @param theObject the object to smooth
3608 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3609 # Note that nodes built on edges and boundary nodes are always fixed.
3610 # @param MaxNbOfIterations the maximum number of iterations
3611 # @param MaxAspectRatio varies in range [1.0, inf]
3612 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3613 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3614 # @return TRUE in case of success, FALSE otherwise.
3615 # @ingroup l2_modif_smooth
3616 def SmoothObject(self, theObject, IDsOfFixedNodes,
3617 MaxNbOfIterations, MaxAspectRatio, Method):
3618 if ( isinstance( theObject, Mesh )):
3619 theObject = theObject.GetMesh()
3620 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3621 MaxNbOfIterations, MaxAspectRatio, Method)
3623 ## Parametrically smooth the given elements
3624 # @param IDsOfElements the list if ids of elements to smooth
3625 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3626 # Note that nodes built on edges and boundary nodes are always fixed.
3627 # @param MaxNbOfIterations the maximum number of iterations
3628 # @param MaxAspectRatio varies in range [1.0, inf]
3629 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3630 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3631 # @return TRUE in case of success, FALSE otherwise.
3632 # @ingroup l2_modif_smooth
3633 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3634 MaxNbOfIterations, MaxAspectRatio, Method):
3635 if IDsOfElements == []:
3636 IDsOfElements = self.GetElementsId()
3637 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3638 self.mesh.SetParameters(Parameters)
3639 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3640 MaxNbOfIterations, MaxAspectRatio, Method)
3642 ## Parametrically smooth the elements which belong to the given object
3643 # @param theObject the object to smooth
3644 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3645 # Note that nodes built on edges and boundary nodes are always fixed.
3646 # @param MaxNbOfIterations the maximum number of iterations
3647 # @param MaxAspectRatio varies in range [1.0, inf]
3648 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3649 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3650 # @return TRUE in case of success, FALSE otherwise.
3651 # @ingroup l2_modif_smooth
3652 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3653 MaxNbOfIterations, MaxAspectRatio, Method):
3654 if ( isinstance( theObject, Mesh )):
3655 theObject = theObject.GetMesh()
3656 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3657 MaxNbOfIterations, MaxAspectRatio, Method)
3659 ## Convert the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3660 # them with quadratic with the same id.
3661 # @param theForce3d new node creation method:
3662 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3663 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3664 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3665 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3666 # @return SMESH.ComputeError which can hold a warning
3667 # @ingroup l2_modif_tofromqu
3668 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3669 if isinstance( theSubMesh, Mesh ):
3670 theSubMesh = theSubMesh.mesh
3672 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3675 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3677 self.editor.ConvertToQuadratic(theForce3d)
3678 error = self.editor.GetLastError()
3679 if error and error.comment:
3683 ## Convert the mesh from quadratic to ordinary,
3684 # deletes old quadratic elements, \n replacing
3685 # them with ordinary mesh elements with the same id.
3686 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3687 # @ingroup l2_modif_tofromqu
3688 def ConvertFromQuadratic(self, theSubMesh=None):
3690 self.editor.ConvertFromQuadraticObject(theSubMesh)
3692 return self.editor.ConvertFromQuadratic()
3694 ## Create 2D mesh as skin on boundary faces of a 3D mesh
3695 # @return TRUE if operation has been completed successfully, FALSE otherwise
3696 # @ingroup l2_modif_add
3697 def Make2DMeshFrom3D(self):
3698 return self.editor.Make2DMeshFrom3D()
3700 ## Create missing boundary elements
3701 # @param elements - elements whose boundary is to be checked:
3702 # mesh, group, sub-mesh or list of elements
3703 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3704 # @param dimension - defines type of boundary elements to create, either of
3705 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3706 # SMESH.BND_1DFROM3D create mesh edges on all borders of free facets of 3D cells
3707 # @param groupName - a name of group to store created boundary elements in,
3708 # "" means not to create the group
3709 # @param meshName - a name of new mesh to store created boundary elements in,
3710 # "" means not to create the new mesh
3711 # @param toCopyElements - if true, the checked elements will be copied into
3712 # the new mesh else only boundary elements will be copied into the new mesh
3713 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3714 # boundary elements will be copied into the new mesh
3715 # @return tuple (mesh, group) where boundary elements were added to
3716 # @ingroup l2_modif_add
3717 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3718 toCopyElements=False, toCopyExistingBondary=False):
3719 unRegister = genObjUnRegister()
3720 if isinstance( elements, Mesh ):
3721 elements = elements.GetMesh()
3722 if ( isinstance( elements, list )):
3723 elemType = SMESH.ALL
3724 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3725 elements = self.editor.MakeIDSource(elements, elemType)
3726 unRegister.set( elements )
3727 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3728 toCopyElements,toCopyExistingBondary)
3729 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3733 # @brief Create missing boundary elements around either the whole mesh or
3734 # groups of elements
3735 # @param dimension - defines type of boundary elements to create, either of
3736 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3737 # @param groupName - a name of group to store all boundary elements in,
3738 # "" means not to create the group
3739 # @param meshName - a name of a new mesh, which is a copy of the initial
3740 # mesh + created boundary elements; "" means not to create the new mesh
3741 # @param toCopyAll - if true, the whole initial mesh will be copied into
3742 # the new mesh else only boundary elements will be copied into the new mesh
3743 # @param groups - groups of elements to make boundary around
3744 # @retval tuple( long, mesh, groups )
3745 # long - number of added boundary elements
3746 # mesh - the mesh where elements were added to
3747 # group - the group of boundary elements or None
3749 # @ingroup l2_modif_add
3750 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3751 toCopyAll=False, groups=[]):
3752 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3754 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3755 return nb, mesh, group
3757 ## Renumber mesh nodes (Obsolete, does nothing)
3758 # @ingroup l2_modif_renumber
3759 def RenumberNodes(self):
3760 self.editor.RenumberNodes()
3762 ## Renumber mesh elements (Obsole, does nothing)
3763 # @ingroup l2_modif_renumber
3764 def RenumberElements(self):
3765 self.editor.RenumberElements()
3767 ## Private method converting \a arg into a list of SMESH_IdSource's
3768 def _getIdSourceList(self, arg, idType, unRegister):
3769 if arg and isinstance( arg, list ):
3770 if isinstance( arg[0], int ):
3771 arg = self.GetIDSource( arg, idType )
3772 unRegister.set( arg )
3773 elif isinstance( arg[0], Mesh ):
3774 arg[0] = arg[0].GetMesh()
3775 elif isinstance( arg, Mesh ):
3777 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3781 ## Generate new elements by rotation of the given elements and nodes around the axis
3782 # @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3783 # @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3784 # @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3785 # @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3786 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3787 # which defines angle in degrees
3788 # @param NbOfSteps the number of steps
3789 # @param Tolerance tolerance
3790 # @param MakeGroups forces the generation of new groups from existing ones
3791 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3792 # of all steps, else - size of each step
3793 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3794 # @ingroup l2_modif_extrurev
3795 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3796 MakeGroups=False, TotalAngle=False):
3797 unRegister = genObjUnRegister()
3798 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3799 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3800 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3802 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3803 Axis = self.smeshpyD.GetAxisStruct( Axis )
3804 if isinstance( Axis, list ):
3805 Axis = SMESH.AxisStruct( *Axis )
3807 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3808 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3809 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3810 self.mesh.SetParameters(Parameters)
3811 if TotalAngle and NbOfSteps:
3812 AngleInRadians /= NbOfSteps
3813 return self.editor.RotationSweepObjects( nodes, edges, faces,
3814 Axis, AngleInRadians,
3815 NbOfSteps, Tolerance, MakeGroups)
3817 ## Generate new elements by rotation of the elements around the axis
3818 # @param IDsOfElements the list of ids of elements to sweep
3819 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3820 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable 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 RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3829 MakeGroups=False, TotalAngle=False):
3830 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3831 AngleInRadians, NbOfSteps, Tolerance,
3832 MakeGroups, TotalAngle)
3834 ## Generate new elements by rotation of the elements of object around the axis
3835 # @param theObject object which elements should be sweeped.
3836 # It can be a mesh, a sub mesh or a group.
3837 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3838 # @param AngleInRadians the angle of Rotation
3839 # @param NbOfSteps number of steps
3840 # @param Tolerance tolerance
3841 # @param MakeGroups forces the generation of new groups from existing ones
3842 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3843 # of all steps, else - size of each step
3844 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3845 # @ingroup l2_modif_extrurev
3846 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3847 MakeGroups=False, TotalAngle=False):
3848 return self.RotationSweepObjects( [], theObject, theObject, Axis,
3849 AngleInRadians, NbOfSteps, Tolerance,
3850 MakeGroups, TotalAngle )
3852 ## Generate new elements by rotation of the elements of object around the axis
3853 # @param theObject object which elements should be sweeped.
3854 # It can be a mesh, a sub mesh or a group.
3855 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3856 # @param AngleInRadians the angle of Rotation
3857 # @param NbOfSteps number of steps
3858 # @param Tolerance tolerance
3859 # @param MakeGroups forces the generation of new groups from existing ones
3860 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3861 # of all steps, else - size of each step
3862 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3863 # @ingroup l2_modif_extrurev
3864 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3865 MakeGroups=False, TotalAngle=False):
3866 return self.RotationSweepObjects([],theObject,[], Axis,
3867 AngleInRadians, NbOfSteps, Tolerance,
3868 MakeGroups, TotalAngle)
3870 ## Generate new elements by rotation of the elements of object around the axis
3871 # @param theObject object which elements should be sweeped.
3872 # It can be a mesh, a sub mesh or a group.
3873 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3874 # @param AngleInRadians the angle of Rotation
3875 # @param NbOfSteps number of steps
3876 # @param Tolerance tolerance
3877 # @param MakeGroups forces the generation of new groups from existing ones
3878 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3879 # of all steps, else - size of each step
3880 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3881 # @ingroup l2_modif_extrurev
3882 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3883 MakeGroups=False, TotalAngle=False):
3884 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3885 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3887 ## Generate new elements by extrusion of the given elements and nodes
3888 # @param nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3889 # @param edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3890 # @param faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3891 # @param StepVector vector or DirStruct or 3 vector components, defining
3892 # the direction and value of extrusion for one step (the total extrusion
3893 # length will be NbOfSteps * ||StepVector||)
3894 # @param NbOfSteps the number of steps
3895 # @param MakeGroups forces the generation of new groups from existing ones
3896 # @param scaleFactors optional scale factors to apply during extrusion
3897 # @param linearVariation if @c True, scaleFactors are spread over all @a scaleFactors,
3898 # else scaleFactors[i] is applied to nodes at the i-th extrusion step
3899 # @param basePoint optional scaling center; if not provided, a gravity center of
3900 # nodes and elements being extruded is used as the scaling center.
3902 # - a list of tree components of the point or
3905 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3906 # @ingroup l2_modif_extrurev
3907 # @ref tui_extrusion example
3908 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False,
3909 scaleFactors=[], linearVariation=False, basePoint=[] ):
3910 unRegister = genObjUnRegister()
3911 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3912 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3913 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3915 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3916 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3917 if isinstance( StepVector, list ):
3918 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3920 if isinstance( basePoint, int):
3921 xyz = self.GetNodeXYZ( basePoint )
3923 raise RuntimeError, "Invalid node ID: %s" % basePoint
3925 if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
3926 basePoint = self.geompyD.PointCoordinates( basePoint )
3928 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3929 Parameters = StepVector.PS.parameters + var_separator + Parameters
3930 self.mesh.SetParameters(Parameters)
3932 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
3933 StepVector, NbOfSteps,
3934 scaleFactors, linearVariation, basePoint,
3938 ## Generate new elements by extrusion of the elements with given ids
3939 # @param IDsOfElements the list of ids of elements or nodes for extrusion
3940 # @param StepVector vector or DirStruct or 3 vector components, defining
3941 # the direction and value of extrusion for one step (the total extrusion
3942 # length will be NbOfSteps * ||StepVector||)
3943 # @param NbOfSteps the number of steps
3944 # @param MakeGroups forces the generation of new groups from existing ones
3945 # @param IsNodes is True if elements with given ids are nodes
3946 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3947 # @ingroup l2_modif_extrurev
3948 # @ref tui_extrusion example
3949 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3951 if IsNodes: n = IDsOfElements
3952 else : e,f, = IDsOfElements,IDsOfElements
3953 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3955 ## Generate new elements by extrusion along the normal to a discretized surface or wire
3956 # @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh.
3957 # Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
3958 # @param StepSize length of one extrusion step (the total extrusion
3959 # length will be \a NbOfSteps * \a StepSize ).
3960 # @param NbOfSteps number of extrusion steps.
3961 # @param ByAverageNormal if True each node is translated by \a StepSize
3962 # along the average of the normal vectors to the faces sharing the node;
3963 # else each node is translated along the same average normal till
3964 # intersection with the plane got by translation of the face sharing
3965 # the node along its own normal by \a StepSize.
3966 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3967 # for every node of \a Elements.
3968 # @param MakeGroups forces generation of new groups from existing ones.
3969 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
3970 # is not yet implemented. This parameter is used if \a Elements contains
3971 # both faces and edges, i.e. \a Elements is a Mesh.
3972 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
3973 # empty list otherwise.
3974 # @ingroup l2_modif_extrurev
3975 # @ref tui_extrusion example
3976 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
3977 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
3978 unRegister = genObjUnRegister()
3979 if isinstance( Elements, Mesh ):
3980 Elements = [ Elements.GetMesh() ]
3981 if isinstance( Elements, list ):
3983 raise RuntimeError, "Elements empty!"
3984 if isinstance( Elements[0], int ):
3985 Elements = self.GetIDSource( Elements, SMESH.ALL )
3986 unRegister.set( Elements )
3987 if not isinstance( Elements, list ):
3988 Elements = [ Elements ]
3989 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
3990 self.mesh.SetParameters(Parameters)
3991 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
3992 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
3994 ## Generate new elements by extrusion of the elements or nodes which belong to the object
3995 # @param theObject the object whose elements or nodes should be processed.
3996 # It can be a mesh, a sub-mesh or a group.
3997 # @param StepVector vector or DirStruct or 3 vector components, defining
3998 # the direction and value of extrusion for one step (the total extrusion
3999 # length will be NbOfSteps * ||StepVector||)
4000 # @param NbOfSteps the number of steps
4001 # @param MakeGroups forces the generation of new groups from existing ones
4002 # @param IsNodes is True if elements to extrude are nodes
4003 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4004 # @ingroup l2_modif_extrurev
4005 # @ref tui_extrusion example
4006 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
4008 if IsNodes: n = theObject
4009 else : e,f, = theObject,theObject
4010 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
4012 ## Generate new elements by extrusion of edges which belong to the object
4013 # @param theObject object whose 1D elements should be processed.
4014 # It can be a mesh, a sub-mesh or a group.
4015 # @param StepVector vector or DirStruct or 3 vector components, defining
4016 # the direction and value of extrusion for one step (the total extrusion
4017 # length will be NbOfSteps * ||StepVector||)
4018 # @param NbOfSteps the number of steps
4019 # @param MakeGroups to generate new groups from existing ones
4020 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4021 # @ingroup l2_modif_extrurev
4022 # @ref tui_extrusion example
4023 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
4024 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
4026 ## Generate new elements by extrusion of faces which belong to the object
4027 # @param theObject object whose 2D elements should be processed.
4028 # It can be a mesh, a sub-mesh or a group.
4029 # @param StepVector vector or DirStruct or 3 vector components, defining
4030 # the direction and value of extrusion for one step (the total extrusion
4031 # length will be NbOfSteps * ||StepVector||)
4032 # @param NbOfSteps the number of steps
4033 # @param MakeGroups forces the generation of new groups from existing ones
4034 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4035 # @ingroup l2_modif_extrurev
4036 # @ref tui_extrusion example
4037 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
4038 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
4040 ## Generate new elements by extrusion of the elements with given ids
4041 # @param IDsOfElements is ids of elements
4042 # @param StepVector vector or DirStruct or 3 vector components, defining
4043 # the direction and value of extrusion for one step (the total extrusion
4044 # length will be NbOfSteps * ||StepVector||)
4045 # @param NbOfSteps the number of steps
4046 # @param ExtrFlags sets flags for extrusion
4047 # @param SewTolerance uses for comparing locations of nodes if flag
4048 # EXTRUSION_FLAG_SEW is set
4049 # @param MakeGroups forces the generation of new groups from existing ones
4050 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4051 # @ingroup l2_modif_extrurev
4052 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
4053 ExtrFlags, SewTolerance, MakeGroups=False):
4054 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
4055 StepVector = self.smeshpyD.GetDirStruct(StepVector)
4056 if isinstance( StepVector, list ):
4057 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
4058 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
4059 ExtrFlags, SewTolerance, MakeGroups)
4061 ## Generate new elements by extrusion of the given elements and nodes along the path.
4062 # The path of extrusion must be a meshed edge.
4063 # @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
4064 # @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
4065 # @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
4066 # @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4067 # @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
4068 # contains not only path segments, else it can be None
4069 # @param NodeStart the first or the last node on the path. Defines the direction of extrusion
4070 # @param HasAngles allows the shape to be rotated around the path
4071 # to get the resulting mesh in a helical fashion
4072 # @param Angles list of angles
4073 # @param LinearVariation forces the computation of rotation angles as linear
4074 # variation of the given Angles along path steps
4075 # @param HasRefPoint allows using the reference point
4076 # @param RefPoint the point around which the shape is rotated (the mass center of the
4077 # shape by default). The User can specify any point as the Reference Point.
4078 # @param MakeGroups forces the generation of new groups from existing ones
4079 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
4080 # @ingroup l2_modif_extrurev
4081 # @ref tui_extrusion_along_path example
4082 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
4083 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
4084 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
4085 unRegister = genObjUnRegister()
4086 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
4087 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
4088 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
4090 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
4091 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4092 if isinstance( RefPoint, list ):
4093 if not RefPoint: RefPoint = [0,0,0]
4094 RefPoint = SMESH.PointStruct( *RefPoint )
4095 if isinstance( PathMesh, Mesh ):
4096 PathMesh = PathMesh.GetMesh()
4097 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4098 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4099 self.mesh.SetParameters(Parameters)
4100 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
4101 PathMesh, PathShape, NodeStart,
4102 HasAngles, Angles, LinearVariation,
4103 HasRefPoint, RefPoint, MakeGroups)
4105 ## Generate new elements by extrusion of the given elements
4106 # The path of extrusion must be a meshed edge.
4107 # @param Base mesh or group, or sub-mesh, or list of ids of elements for extrusion
4108 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4109 # @param NodeStart the start node from Path. Defines the direction of extrusion
4110 # @param HasAngles allows the shape to be rotated around the path
4111 # to get the resulting mesh in a helical fashion
4112 # @param Angles list of angles in radians
4113 # @param LinearVariation forces the computation of rotation angles as linear
4114 # variation of the given Angles along path steps
4115 # @param HasRefPoint allows using the reference point
4116 # @param RefPoint the point around which the elements are rotated (the mass
4117 # center of the elements by default).
4118 # The User can specify any point as the Reference Point.
4119 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
4120 # @param MakeGroups forces the generation of new groups from existing ones
4121 # @param ElemType type of elements for extrusion (if param Base is a mesh)
4122 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4123 # only SMESH::Extrusion_Error otherwise
4124 # @ingroup l2_modif_extrurev
4125 # @ref tui_extrusion_along_path example
4126 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
4127 HasAngles=False, Angles=[], LinearVariation=False,
4128 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
4129 ElemType=SMESH.FACE):
4131 if ElemType == SMESH.NODE: n = Base
4132 if ElemType == SMESH.EDGE: e = Base
4133 if ElemType == SMESH.FACE: f = Base
4134 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
4135 HasAngles, Angles, LinearVariation,
4136 HasRefPoint, RefPoint, MakeGroups)
4137 if MakeGroups: return gr,er
4140 ## Generate new elements by extrusion of the given elements
4141 # The path of extrusion must be a meshed edge.
4142 # @param IDsOfElements ids of elements
4143 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
4144 # @param PathShape shape(edge) defines the sub-mesh for the path
4145 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4146 # @param HasAngles allows the shape to be rotated around the path
4147 # to get the resulting mesh in a helical fashion
4148 # @param Angles list of angles in radians
4149 # @param HasRefPoint allows using the reference point
4150 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4151 # The User can specify any point as the Reference Point.
4152 # @param MakeGroups forces the generation of new groups from existing ones
4153 # @param LinearVariation forces the computation of rotation angles as linear
4154 # variation of the given Angles along path steps
4155 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4156 # only SMESH::Extrusion_Error otherwise
4157 # @ingroup l2_modif_extrurev
4158 # @ref tui_extrusion_along_path example
4159 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
4160 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4161 MakeGroups=False, LinearVariation=False):
4162 n,e,f = [],IDsOfElements,IDsOfElements
4163 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
4164 NodeStart, HasAngles, Angles,
4166 HasRefPoint, RefPoint, MakeGroups)
4167 if MakeGroups: return gr,er
4170 ## Generate new elements by extrusion of the elements which belong to the object
4171 # The path of extrusion must be a meshed edge.
4172 # @param theObject the object whose elements should be processed.
4173 # It can be a mesh, a sub-mesh or a group.
4174 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4175 # @param PathShape shape(edge) defines the sub-mesh for the path
4176 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4177 # @param HasAngles allows the shape to be rotated around the path
4178 # to get the resulting mesh in a helical fashion
4179 # @param Angles list of angles
4180 # @param HasRefPoint allows using the reference point
4181 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4182 # The User can specify any point as the Reference Point.
4183 # @param MakeGroups forces the generation of new groups from existing ones
4184 # @param LinearVariation forces the computation of rotation angles as linear
4185 # variation of the given Angles along path steps
4186 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4187 # only SMESH::Extrusion_Error otherwise
4188 # @ingroup l2_modif_extrurev
4189 # @ref tui_extrusion_along_path example
4190 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4191 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4192 MakeGroups=False, LinearVariation=False):
4193 n,e,f = [],theObject,theObject
4194 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4195 HasAngles, Angles, LinearVariation,
4196 HasRefPoint, RefPoint, MakeGroups)
4197 if MakeGroups: return gr,er
4200 ## Generate new elements by extrusion of mesh segments which belong to the object
4201 # The path of extrusion must be a meshed edge.
4202 # @param theObject the object whose 1D elements should be processed.
4203 # It can be a mesh, a sub-mesh or a group.
4204 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4205 # @param PathShape shape(edge) defines the sub-mesh for the path
4206 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4207 # @param HasAngles allows the shape to be rotated around the path
4208 # to get the resulting mesh in a helical fashion
4209 # @param Angles list of angles
4210 # @param HasRefPoint allows using the reference point
4211 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4212 # The User can specify any point as the Reference Point.
4213 # @param MakeGroups forces the generation of new groups from existing ones
4214 # @param LinearVariation forces the computation of rotation angles as linear
4215 # variation of the given Angles along path steps
4216 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4217 # only SMESH::Extrusion_Error otherwise
4218 # @ingroup l2_modif_extrurev
4219 # @ref tui_extrusion_along_path example
4220 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4221 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4222 MakeGroups=False, LinearVariation=False):
4223 n,e,f = [],theObject,[]
4224 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4225 HasAngles, Angles, LinearVariation,
4226 HasRefPoint, RefPoint, MakeGroups)
4227 if MakeGroups: return gr,er
4230 ## Generate new elements by extrusion of faces which belong to the object
4231 # The path of extrusion must be a meshed edge.
4232 # @param theObject the object whose 2D elements should be processed.
4233 # It can be a mesh, a sub-mesh or a group.
4234 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4235 # @param PathShape shape(edge) defines the sub-mesh for the path
4236 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4237 # @param HasAngles allows the shape to be rotated around the path
4238 # to get the resulting mesh in a helical fashion
4239 # @param Angles list of angles
4240 # @param HasRefPoint allows using the reference point
4241 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4242 # The User can specify any point as the Reference Point.
4243 # @param MakeGroups forces the generation of new groups from existing ones
4244 # @param LinearVariation forces the computation of rotation angles as linear
4245 # variation of the given Angles along path steps
4246 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4247 # only SMESH::Extrusion_Error otherwise
4248 # @ingroup l2_modif_extrurev
4249 # @ref tui_extrusion_along_path example
4250 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4251 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4252 MakeGroups=False, LinearVariation=False):
4253 n,e,f = [],[],theObject
4254 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4255 HasAngles, Angles, LinearVariation,
4256 HasRefPoint, RefPoint, MakeGroups)
4257 if MakeGroups: return gr,er
4260 ## Create a symmetrical copy of mesh elements
4261 # @param IDsOfElements list of elements ids
4262 # @param Mirror is AxisStruct or geom object(point, line, plane)
4263 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4264 # If the Mirror is a geom object this parameter is unnecessary
4265 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4266 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4267 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4268 # @ingroup l2_modif_trsf
4269 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4270 if IDsOfElements == []:
4271 IDsOfElements = self.GetElementsId()
4272 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4273 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4274 theMirrorType = Mirror._mirrorType
4276 self.mesh.SetParameters(Mirror.parameters)
4277 if Copy and MakeGroups:
4278 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4279 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4282 ## Create a new mesh by a symmetrical copy of mesh elements
4283 # @param IDsOfElements the list of elements ids
4284 # @param Mirror is AxisStruct or geom object (point, line, plane)
4285 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4286 # If the Mirror is a geom object this parameter is unnecessary
4287 # @param MakeGroups to generate new groups from existing ones
4288 # @param NewMeshName a name of the new mesh to create
4289 # @return instance of Mesh class
4290 # @ingroup l2_modif_trsf
4291 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4292 if IDsOfElements == []:
4293 IDsOfElements = self.GetElementsId()
4294 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4295 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4296 theMirrorType = Mirror._mirrorType
4298 self.mesh.SetParameters(Mirror.parameters)
4299 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4300 MakeGroups, NewMeshName)
4301 return Mesh(self.smeshpyD,self.geompyD,mesh)
4303 ## Create a symmetrical copy of the object
4304 # @param theObject mesh, submesh or group
4305 # @param Mirror 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 Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4309 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4310 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4311 # @ingroup l2_modif_trsf
4312 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4313 if ( isinstance( theObject, Mesh )):
4314 theObject = theObject.GetMesh()
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 if Copy and MakeGroups:
4321 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4322 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4325 ## Create a new mesh by a symmetrical copy of the object
4326 # @param theObject mesh, submesh or group
4327 # @param Mirror AxisStruct or geom object (point, line, plane)
4328 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4329 # If the Mirror is a geom object this parameter is unnecessary
4330 # @param MakeGroups forces the generation of new groups from existing ones
4331 # @param NewMeshName the name of the new mesh to create
4332 # @return instance of Mesh class
4333 # @ingroup l2_modif_trsf
4334 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4335 if ( isinstance( theObject, Mesh )):
4336 theObject = theObject.GetMesh()
4337 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4338 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4339 theMirrorType = Mirror._mirrorType
4341 self.mesh.SetParameters(Mirror.parameters)
4342 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4343 MakeGroups, NewMeshName)
4344 return Mesh( self.smeshpyD,self.geompyD,mesh )
4346 ## Translate the elements
4347 # @param IDsOfElements list of elements ids
4348 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4349 # @param Copy allows copying the translated elements
4350 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4351 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4352 # @ingroup l2_modif_trsf
4353 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4354 if IDsOfElements == []:
4355 IDsOfElements = self.GetElementsId()
4356 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4357 Vector = self.smeshpyD.GetDirStruct(Vector)
4358 if isinstance( Vector, list ):
4359 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4360 self.mesh.SetParameters(Vector.PS.parameters)
4361 if Copy and MakeGroups:
4362 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4363 self.editor.Translate(IDsOfElements, Vector, Copy)
4366 ## Create a new mesh of translated elements
4367 # @param IDsOfElements list of elements ids
4368 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4369 # @param MakeGroups forces the generation of new groups from existing ones
4370 # @param NewMeshName the name of the newly created mesh
4371 # @return instance of Mesh class
4372 # @ingroup l2_modif_trsf
4373 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4374 if IDsOfElements == []:
4375 IDsOfElements = self.GetElementsId()
4376 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4377 Vector = self.smeshpyD.GetDirStruct(Vector)
4378 if isinstance( Vector, list ):
4379 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4380 self.mesh.SetParameters(Vector.PS.parameters)
4381 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4382 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4384 ## Translate the object
4385 # @param theObject the object to translate (mesh, submesh, or group)
4386 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4387 # @param Copy allows copying the translated elements
4388 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4389 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4390 # @ingroup l2_modif_trsf
4391 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4392 if ( isinstance( theObject, Mesh )):
4393 theObject = theObject.GetMesh()
4394 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4395 Vector = self.smeshpyD.GetDirStruct(Vector)
4396 if isinstance( Vector, list ):
4397 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4398 self.mesh.SetParameters(Vector.PS.parameters)
4399 if Copy and MakeGroups:
4400 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4401 self.editor.TranslateObject(theObject, Vector, Copy)
4404 ## Create a new mesh from the translated object
4405 # @param theObject the object to translate (mesh, submesh, or group)
4406 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4407 # @param MakeGroups forces the generation of new groups from existing ones
4408 # @param NewMeshName the name of the newly created mesh
4409 # @return instance of Mesh class
4410 # @ingroup l2_modif_trsf
4411 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4412 if isinstance( theObject, Mesh ):
4413 theObject = theObject.GetMesh()
4414 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4415 Vector = self.smeshpyD.GetDirStruct(Vector)
4416 if isinstance( Vector, list ):
4417 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4418 self.mesh.SetParameters(Vector.PS.parameters)
4419 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4420 return Mesh( self.smeshpyD, self.geompyD, mesh )
4425 # @param theObject - the object to translate (mesh, submesh, or group)
4426 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4427 # @param theScaleFact - list of 1-3 scale factors for axises
4428 # @param Copy - allows copying the translated elements
4429 # @param MakeGroups - forces the generation of new groups from existing
4431 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4432 # empty list otherwise
4433 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4434 unRegister = genObjUnRegister()
4435 if ( isinstance( theObject, Mesh )):
4436 theObject = theObject.GetMesh()
4437 if ( isinstance( theObject, list )):
4438 theObject = self.GetIDSource(theObject, SMESH.ALL)
4439 unRegister.set( theObject )
4440 if ( isinstance( thePoint, list )):
4441 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4442 if ( isinstance( theScaleFact, float )):
4443 theScaleFact = [theScaleFact]
4444 if ( isinstance( theScaleFact, int )):
4445 theScaleFact = [ float(theScaleFact)]
4447 self.mesh.SetParameters(thePoint.parameters)
4449 if Copy and MakeGroups:
4450 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4451 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4454 ## Create a new mesh from the translated object
4455 # @param theObject - the object to translate (mesh, submesh, or group)
4456 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4457 # @param theScaleFact - list of 1-3 scale factors for axises
4458 # @param MakeGroups - forces the generation of new groups from existing ones
4459 # @param NewMeshName - the name of the newly created mesh
4460 # @return instance of Mesh class
4461 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4462 unRegister = genObjUnRegister()
4463 if (isinstance(theObject, Mesh)):
4464 theObject = theObject.GetMesh()
4465 if ( isinstance( theObject, list )):
4466 theObject = self.GetIDSource(theObject,SMESH.ALL)
4467 unRegister.set( theObject )
4468 if ( isinstance( thePoint, list )):
4469 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4470 if ( isinstance( theScaleFact, float )):
4471 theScaleFact = [theScaleFact]
4472 if ( isinstance( theScaleFact, int )):
4473 theScaleFact = [ float(theScaleFact)]
4475 self.mesh.SetParameters(thePoint.parameters)
4476 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4477 MakeGroups, NewMeshName)
4478 return Mesh( self.smeshpyD, self.geompyD, mesh )
4482 ## Rotate the elements
4483 # @param IDsOfElements list of elements ids
4484 # @param Axis the axis of rotation (AxisStruct or geom line)
4485 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4486 # @param Copy allows copying the rotated elements
4487 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4488 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4489 # @ingroup l2_modif_trsf
4490 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4491 if IDsOfElements == []:
4492 IDsOfElements = self.GetElementsId()
4493 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4494 Axis = self.smeshpyD.GetAxisStruct(Axis)
4495 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4496 Parameters = Axis.parameters + var_separator + Parameters
4497 self.mesh.SetParameters(Parameters)
4498 if Copy and MakeGroups:
4499 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4500 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4503 ## Create a new mesh of rotated elements
4504 # @param IDsOfElements list of element 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 MakeGroups forces the generation of new groups from existing ones
4508 # @param NewMeshName the name of the newly created mesh
4509 # @return instance of Mesh class
4510 # @ingroup l2_modif_trsf
4511 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
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 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4520 MakeGroups, NewMeshName)
4521 return Mesh( self.smeshpyD, self.geompyD, mesh )
4523 ## Rotate the object
4524 # @param theObject the object to rotate( mesh, submesh, or group)
4525 # @param Axis the axis of rotation (AxisStruct or geom line)
4526 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4527 # @param Copy allows copying the rotated elements
4528 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4529 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4530 # @ingroup l2_modif_trsf
4531 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4532 if (isinstance(theObject, Mesh)):
4533 theObject = theObject.GetMesh()
4534 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4535 Axis = self.smeshpyD.GetAxisStruct(Axis)
4536 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4537 Parameters = Axis.parameters + ":" + Parameters
4538 self.mesh.SetParameters(Parameters)
4539 if Copy and MakeGroups:
4540 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4541 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4544 ## Create a new mesh from the rotated 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 MakeGroups forces the generation of new groups from existing ones
4549 # @param NewMeshName the name of the newly created mesh
4550 # @return instance of Mesh class
4551 # @ingroup l2_modif_trsf
4552 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
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 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4560 MakeGroups, NewMeshName)
4561 self.mesh.SetParameters(Parameters)
4562 return Mesh( self.smeshpyD, self.geompyD, mesh )
4564 ## Find groups of adjacent nodes within Tolerance.
4565 # @param Tolerance the value of tolerance
4566 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4567 # corner and medium nodes in separate groups thus preventing
4568 # their further merge.
4569 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4570 # @ingroup l2_modif_trsf
4571 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
4572 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
4574 ## Find groups of ajacent nodes within Tolerance.
4575 # @param Tolerance the value of tolerance
4576 # @param SubMeshOrGroup SubMesh, Group or Filter
4577 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4578 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4579 # corner and medium nodes in separate groups thus preventing
4580 # their further merge.
4581 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4582 # @ingroup l2_modif_trsf
4583 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
4584 exceptNodes=[], SeparateCornerAndMediumNodes=False):
4585 unRegister = genObjUnRegister()
4586 if (isinstance( SubMeshOrGroup, Mesh )):
4587 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4588 if not isinstance( exceptNodes, list ):
4589 exceptNodes = [ exceptNodes ]
4590 if exceptNodes and isinstance( exceptNodes[0], int ):
4591 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
4592 unRegister.set( exceptNodes )
4593 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
4594 exceptNodes, SeparateCornerAndMediumNodes)
4597 # @param GroupsOfNodes a list of groups of nodes IDs for merging
4598 # (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
4599 # by nodes 1 and 25 correspondingly in all elements and groups
4600 # @param NodesToKeep nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
4601 # If @a NodesToKeep does not include a node to keep for some group to merge,
4602 # then the first node in the group is kept.
4603 # @param AvoidMakingHoles prevent merging nodes which cause removal of elements becoming
4605 # @ingroup l2_modif_trsf
4606 def MergeNodes (self, GroupsOfNodes, NodesToKeep=[], AvoidMakingHoles=False):
4607 # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
4608 self.editor.MergeNodes( GroupsOfNodes, NodesToKeep, AvoidMakingHoles )
4610 ## Find the elements built on the same nodes.
4611 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4612 # @return the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
4613 # @ingroup l2_modif_trsf
4614 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4615 if not MeshOrSubMeshOrGroup:
4616 MeshOrSubMeshOrGroup=self.mesh
4617 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4618 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4619 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4621 ## Merge elements in each given group.
4622 # @param GroupsOfElementsID a list of groups of elements IDs for merging
4623 # (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
4624 # replaced by elements 1 and 25 in all groups)
4625 # @ingroup l2_modif_trsf
4626 def MergeElements(self, GroupsOfElementsID):
4627 self.editor.MergeElements(GroupsOfElementsID)
4629 ## Leave one element and remove all other elements built on the same nodes.
4630 # @ingroup l2_modif_trsf
4631 def MergeEqualElements(self):
4632 self.editor.MergeEqualElements()
4634 ## Returns all or only closed free borders
4635 # @return list of SMESH.FreeBorder's
4636 # @ingroup l2_modif_trsf
4637 def FindFreeBorders(self, ClosedOnly=True):
4638 return self.editor.FindFreeBorders( ClosedOnly )
4640 ## Fill with 2D elements a hole defined by a SMESH.FreeBorder.
4641 # @param FreeBorder either a SMESH.FreeBorder or a list on node IDs. These nodes
4642 # must describe all sequential nodes of the hole border. The first and the last
4643 # nodes must be the same. Use FindFreeBorders() to get nodes of holes.
4644 # @ingroup l2_modif_trsf
4645 def FillHole(self, holeNodes):
4646 if holeNodes and isinstance( holeNodes, list ) and isinstance( holeNodes[0], int ):
4647 holeNodes = SMESH.FreeBorder(nodeIDs=holeNodes)
4648 if not isinstance( holeNodes, SMESH.FreeBorder ):
4649 raise TypeError, "holeNodes must be either SMESH.FreeBorder or list of integer and not %s" % holeNodes
4650 self.editor.FillHole( holeNodes )
4652 ## Return groups of FreeBorder's coincident within the given tolerance.
4653 # @param tolerance the tolerance. If the tolerance <= 0.0 then one tenth of an average
4654 # size of elements adjacent to free borders being compared is used.
4655 # @return SMESH.CoincidentFreeBorders structure
4656 # @ingroup l2_modif_trsf
4657 def FindCoincidentFreeBorders (self, tolerance=0.):
4658 return self.editor.FindCoincidentFreeBorders( tolerance )
4660 ## Sew FreeBorder's of each group
4661 # @param freeBorders either a SMESH.CoincidentFreeBorders structure or a list of lists
4662 # where each enclosed list contains node IDs of a group of coincident free
4663 # borders such that each consequent triple of IDs within a group describes
4664 # a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
4665 # last node of a border.
4666 # For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
4667 # groups of coincident free borders, each group including two borders.
4668 # @param createPolygons if @c True faces adjacent to free borders are converted to
4669 # polygons if a node of opposite border falls on a face edge, else such
4670 # faces are split into several ones.
4671 # @param createPolyhedra if @c True volumes adjacent to free borders are converted to
4672 # polyhedra if a node of opposite border falls on a volume edge, else such
4673 # volumes, if any, remain intact and the mesh becomes non-conformal.
4674 # @return a number of successfully sewed groups
4675 # @ingroup l2_modif_trsf
4676 def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
4677 if freeBorders and isinstance( freeBorders, list ):
4678 # construct SMESH.CoincidentFreeBorders
4679 if isinstance( freeBorders[0], int ):
4680 freeBorders = [freeBorders]
4682 coincidentGroups = []
4683 for nodeList in freeBorders:
4684 if not nodeList or len( nodeList ) % 3:
4685 raise ValueError, "Wrong number of nodes in this group: %s" % nodeList
4688 group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
4689 borders.append( SMESH.FreeBorder( nodeList[:3] ))
4690 nodeList = nodeList[3:]
4692 coincidentGroups.append( group )
4694 freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
4696 return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
4699 # @return SMESH::Sew_Error
4700 # @ingroup l2_modif_trsf
4701 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4702 FirstNodeID2, SecondNodeID2, LastNodeID2,
4703 CreatePolygons, CreatePolyedrs):
4704 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4705 FirstNodeID2, SecondNodeID2, LastNodeID2,
4706 CreatePolygons, CreatePolyedrs)
4708 ## Sew conform free borders
4709 # @return SMESH::Sew_Error
4710 # @ingroup l2_modif_trsf
4711 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4712 FirstNodeID2, SecondNodeID2):
4713 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4714 FirstNodeID2, SecondNodeID2)
4716 ## Sew border to side
4717 # @return SMESH::Sew_Error
4718 # @ingroup l2_modif_trsf
4719 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4720 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4721 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4722 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4724 ## Sew two sides of a mesh. The nodes belonging to Side1 are
4725 # merged with the nodes of elements of Side2.
4726 # The number of elements in theSide1 and in theSide2 must be
4727 # equal and they should have similar nodal connectivity.
4728 # The nodes to merge should belong to side borders and
4729 # the first node should be linked to the second.
4730 # @return SMESH::Sew_Error
4731 # @ingroup l2_modif_trsf
4732 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4733 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4734 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4735 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4736 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4737 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4739 ## Set new nodes for the given element.
4740 # @param ide the element id
4741 # @param newIDs nodes ids
4742 # @return If the number of nodes does not correspond to the type of element - return false
4743 # @ingroup l2_modif_edit
4744 def ChangeElemNodes(self, ide, newIDs):
4745 return self.editor.ChangeElemNodes(ide, newIDs)
4747 ## If during the last operation of MeshEditor some nodes were
4748 # created, this method return the list of their IDs, \n
4749 # if new nodes were not created - return empty list
4750 # @return the list of integer values (can be empty)
4751 # @ingroup l2_modif_add
4752 def GetLastCreatedNodes(self):
4753 return self.editor.GetLastCreatedNodes()
4755 ## If during the last operation of MeshEditor some elements were
4756 # created this method return the list of their IDs, \n
4757 # if new elements were not created - return empty list
4758 # @return the list of integer values (can be empty)
4759 # @ingroup l2_modif_add
4760 def GetLastCreatedElems(self):
4761 return self.editor.GetLastCreatedElems()
4763 ## Forget what nodes and elements were created by the last mesh edition operation
4764 # @ingroup l2_modif_add
4765 def ClearLastCreated(self):
4766 self.editor.ClearLastCreated()
4768 ## Create duplicates of given elements, i.e. create new elements based on the
4769 # same nodes as the given ones.
4770 # @param theElements - container of elements to duplicate. It can be a Mesh,
4771 # sub-mesh, group, filter or a list of element IDs. If \a theElements is
4772 # a Mesh, elements of highest dimension are duplicated
4773 # @param theGroupName - a name of group to contain the generated elements.
4774 # If a group with such a name already exists, the new elements
4775 # are added to the existng group, else a new group is created.
4776 # If \a theGroupName is empty, new elements are not added
4778 # @return a group where the new elements are added. None if theGroupName == "".
4779 # @ingroup l2_modif_duplicat
4780 def DoubleElements(self, theElements, theGroupName=""):
4781 unRegister = genObjUnRegister()
4782 if isinstance( theElements, Mesh ):
4783 theElements = theElements.mesh
4784 elif isinstance( theElements, list ):
4785 theElements = self.GetIDSource( theElements, SMESH.ALL )
4786 unRegister.set( theElements )
4787 return self.editor.DoubleElements(theElements, theGroupName)
4789 ## Create a hole in a mesh by doubling the nodes of some particular elements
4790 # @param theNodes identifiers of nodes to be doubled
4791 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4792 # nodes. If list of element identifiers is empty then nodes are doubled but
4793 # they not assigned to elements
4794 # @return TRUE if operation has been completed successfully, FALSE otherwise
4795 # @ingroup l2_modif_duplicat
4796 def DoubleNodes(self, theNodes, theModifiedElems):
4797 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4799 ## Create a hole in a mesh by doubling the nodes of some particular elements
4800 # This method provided for convenience works as DoubleNodes() described above.
4801 # @param theNodeId identifiers of node to be doubled
4802 # @param theModifiedElems identifiers of elements to be updated
4803 # @return TRUE if operation has been completed successfully, FALSE otherwise
4804 # @ingroup l2_modif_duplicat
4805 def DoubleNode(self, theNodeId, theModifiedElems):
4806 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4808 ## Create a hole in a mesh by doubling the nodes of some particular elements
4809 # This method provided for convenience works as DoubleNodes() described above.
4810 # @param theNodes group of nodes to be doubled
4811 # @param theModifiedElems group of elements to be updated.
4812 # @param theMakeGroup forces the generation of a group containing new nodes.
4813 # @return TRUE or a created group if operation has been completed successfully,
4814 # FALSE or None otherwise
4815 # @ingroup l2_modif_duplicat
4816 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4818 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4819 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4821 ## Create a hole in a mesh by doubling the nodes of some particular elements
4822 # This method provided for convenience works as DoubleNodes() described above.
4823 # @param theNodes list of groups of nodes to be doubled
4824 # @param theModifiedElems list of groups of elements to be updated.
4825 # @param theMakeGroup forces the generation of a group containing new nodes.
4826 # @return TRUE if operation has been completed successfully, FALSE otherwise
4827 # @ingroup l2_modif_duplicat
4828 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4830 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4831 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4833 ## Create a hole in a mesh by doubling the nodes of some particular elements
4834 # @param theElems - the list of elements (edges or faces) to be replicated
4835 # The nodes for duplication could be found from these elements
4836 # @param theNodesNot - list of nodes to NOT replicate
4837 # @param theAffectedElems - the list of elements (cells and edges) to which the
4838 # replicated nodes should be associated to.
4839 # @return TRUE if operation has been completed successfully, FALSE otherwise
4840 # @ingroup l2_modif_duplicat
4841 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4842 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4844 ## Create a hole in a mesh by doubling the nodes of some particular elements
4845 # @param theElems - the list of elements (edges or faces) to be replicated
4846 # The nodes for duplication could be found from these elements
4847 # @param theNodesNot - list of nodes to NOT replicate
4848 # @param theShape - shape to detect affected elements (element which geometric center
4849 # located on or inside shape).
4850 # The replicated nodes should be associated to affected elements.
4851 # @return TRUE if operation has been completed successfully, FALSE otherwise
4852 # @ingroup l2_modif_duplicat
4853 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4854 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4856 ## Create a hole in a mesh by doubling the nodes of some particular elements
4857 # This method provided for convenience works as DoubleNodes() described above.
4858 # @param theElems - group of of elements (edges or faces) to be replicated
4859 # @param theNodesNot - group of nodes not to replicated
4860 # @param theAffectedElems - group of elements to which the replicated nodes
4861 # should be associated to.
4862 # @param theMakeGroup forces the generation of a group containing new elements.
4863 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4864 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4865 # FALSE or None otherwise
4866 # @ingroup l2_modif_duplicat
4867 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4868 theMakeGroup=False, theMakeNodeGroup=False):
4869 if theMakeGroup or theMakeNodeGroup:
4870 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4872 theMakeGroup, theMakeNodeGroup)
4873 if theMakeGroup and theMakeNodeGroup:
4876 return twoGroups[ int(theMakeNodeGroup) ]
4877 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4879 ## Create a hole in a mesh by doubling the nodes of some particular elements
4880 # This method provided for convenience works as DoubleNodes() described above.
4881 # @param theElems - group of of elements (edges or faces) to be replicated
4882 # @param theNodesNot - group of nodes not to replicated
4883 # @param theShape - shape to detect affected elements (element which geometric center
4884 # located on or inside shape).
4885 # The replicated nodes should be associated to affected elements.
4886 # @ingroup l2_modif_duplicat
4887 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4888 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4890 ## Create a hole in a mesh by doubling the nodes of some particular elements
4891 # This method provided for convenience works as DoubleNodes() described above.
4892 # @param theElems - list of groups of elements (edges or faces) to be replicated
4893 # @param theNodesNot - list of groups of nodes not to replicated
4894 # @param theAffectedElems - group of elements to which the replicated nodes
4895 # should be associated to.
4896 # @param theMakeGroup forces the generation of a group containing new elements.
4897 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4898 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4899 # FALSE or None otherwise
4900 # @ingroup l2_modif_duplicat
4901 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4902 theMakeGroup=False, theMakeNodeGroup=False):
4903 if theMakeGroup or theMakeNodeGroup:
4904 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4906 theMakeGroup, theMakeNodeGroup)
4907 if theMakeGroup and theMakeNodeGroup:
4910 return twoGroups[ int(theMakeNodeGroup) ]
4911 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4913 ## Create a hole in a mesh by doubling the nodes of some particular elements
4914 # This method provided for convenience works as DoubleNodes() described above.
4915 # @param theElems - list of groups of elements (edges or faces) to be replicated
4916 # @param theNodesNot - list of groups of nodes not to replicated
4917 # @param theShape - shape to detect affected elements (element which geometric center
4918 # located on or inside shape).
4919 # The replicated nodes should be associated to affected elements.
4920 # @return TRUE if operation has been completed successfully, FALSE otherwise
4921 # @ingroup l2_modif_duplicat
4922 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4923 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4925 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4926 # This method is the first step of DoubleNodeElemGroupsInRegion.
4927 # @param theElems - list of groups of nodes or elements (edges or faces) to be replicated
4928 # @param theNodesNot - list of groups of nodes not to replicated
4929 # @param theShape - shape to detect affected elements (element which geometric center
4930 # located on or inside shape).
4931 # The replicated nodes should be associated to affected elements.
4932 # @return groups of affected elements in order: volumes, faces, edges
4933 # @ingroup l2_modif_duplicat
4934 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4935 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4937 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4938 # The list of groups must describe a partition of the mesh volumes.
4939 # The nodes of the internal faces at the boundaries of the groups are doubled.
4940 # In option, the internal faces are replaced by flat elements.
4941 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4942 # @param theDomains - list of groups of volumes
4943 # @param createJointElems - if TRUE, create the elements
4944 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4945 # the boundary between \a theDomains and the rest mesh
4946 # @return TRUE if operation has been completed successfully, FALSE otherwise
4947 # @ingroup l2_modif_duplicat
4948 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4949 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4951 ## Double nodes on some external faces and create flat elements.
4952 # Flat elements are mainly used by some types of mechanic calculations.
4954 # Each group of the list must be constituted of faces.
4955 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4956 # @param theGroupsOfFaces - list of groups of faces
4957 # @return TRUE if operation has been completed successfully, FALSE otherwise
4958 # @ingroup l2_modif_duplicat
4959 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4960 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4962 ## identify all the elements around a geom shape, get the faces delimiting the hole
4964 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4965 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4967 ## Return a cached numerical functor by its type.
4968 # @param theCriterion functor type - an item of SMESH.FunctorType enumeration.
4969 # Type SMESH.FunctorType._items in the Python Console to see all items.
4970 # Note that not all items correspond to numerical functors.
4971 # @return SMESH_NumericalFunctor. The functor is already initialized
4973 # @ingroup l1_measurements
4974 def GetFunctor(self, funcType ):
4975 fn = self.functors[ funcType._v ]
4977 fn = self.smeshpyD.GetFunctor(funcType)
4978 fn.SetMesh(self.mesh)
4979 self.functors[ funcType._v ] = fn
4982 ## Return value of a functor for a given element
4983 # @param funcType an item of SMESH.FunctorType enum
4984 # Type "SMESH.FunctorType._items" in the Python Console to see all items.
4985 # @param elemId element or node ID
4986 # @param isElem @a elemId is ID of element or node
4987 # @return the functor value or zero in case of invalid arguments
4988 # @ingroup l1_measurements
4989 def FunctorValue(self, funcType, elemId, isElem=True):
4990 fn = self.GetFunctor( funcType )
4991 if fn.GetElementType() == self.GetElementType(elemId, isElem):
4992 val = fn.GetValue(elemId)
4997 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4998 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4999 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
5000 # @ingroup l1_measurements
5001 def GetLength(self, elemId=None):
5004 length = self.smeshpyD.GetLength(self)
5006 length = self.FunctorValue(SMESH.FT_Length, elemId)
5009 ## Get area of 2D element or sum of areas of all 2D mesh elements
5010 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
5011 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
5012 # @ingroup l1_measurements
5013 def GetArea(self, elemId=None):
5016 area = self.smeshpyD.GetArea(self)
5018 area = self.FunctorValue(SMESH.FT_Area, elemId)
5021 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
5022 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
5023 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
5024 # @ingroup l1_measurements
5025 def GetVolume(self, elemId=None):
5028 volume = self.smeshpyD.GetVolume(self)
5030 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
5033 ## Get maximum element length.
5034 # @param elemId mesh element ID
5035 # @return element's maximum length value
5036 # @ingroup l1_measurements
5037 def GetMaxElementLength(self, elemId):
5038 if self.GetElementType(elemId, True) == SMESH.VOLUME:
5039 ftype = SMESH.FT_MaxElementLength3D
5041 ftype = SMESH.FT_MaxElementLength2D
5042 return self.FunctorValue(ftype, elemId)
5044 ## Get aspect ratio of 2D or 3D element.
5045 # @param elemId mesh element ID
5046 # @return element's aspect ratio value
5047 # @ingroup l1_measurements
5048 def GetAspectRatio(self, elemId):
5049 if self.GetElementType(elemId, True) == SMESH.VOLUME:
5050 ftype = SMESH.FT_AspectRatio3D
5052 ftype = SMESH.FT_AspectRatio
5053 return self.FunctorValue(ftype, elemId)
5055 ## Get warping angle of 2D element.
5056 # @param elemId mesh element ID
5057 # @return element's warping angle value
5058 # @ingroup l1_measurements
5059 def GetWarping(self, elemId):
5060 return self.FunctorValue(SMESH.FT_Warping, elemId)
5062 ## Get minimum angle of 2D element.
5063 # @param elemId mesh element ID
5064 # @return element's minimum angle value
5065 # @ingroup l1_measurements
5066 def GetMinimumAngle(self, elemId):
5067 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
5069 ## Get taper of 2D element.
5070 # @param elemId mesh element ID
5071 # @return element's taper value
5072 # @ingroup l1_measurements
5073 def GetTaper(self, elemId):
5074 return self.FunctorValue(SMESH.FT_Taper, elemId)
5076 ## Get skew of 2D element.
5077 # @param elemId mesh element ID
5078 # @return element's skew value
5079 # @ingroup l1_measurements
5080 def GetSkew(self, elemId):
5081 return self.FunctorValue(SMESH.FT_Skew, elemId)
5083 ## Return minimal and maximal value of a given functor.
5084 # @param funType a functor type, an item of SMESH.FunctorType enum
5085 # (one of SMESH.FunctorType._items)
5086 # @param meshPart a part of mesh (group, sub-mesh) to treat
5087 # @return tuple (min,max)
5088 # @ingroup l1_measurements
5089 def GetMinMax(self, funType, meshPart=None):
5090 unRegister = genObjUnRegister()
5091 if isinstance( meshPart, list ):
5092 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
5093 unRegister.set( meshPart )
5094 if isinstance( meshPart, Mesh ):
5095 meshPart = meshPart.mesh
5096 fun = self.GetFunctor( funType )
5099 if hasattr( meshPart, "SetMesh" ):
5100 meshPart.SetMesh( self.mesh ) # set mesh to filter
5101 hist = fun.GetLocalHistogram( 1, False, meshPart )
5103 hist = fun.GetHistogram( 1, False )
5105 return hist[0].min, hist[0].max
5108 pass # end of Mesh class
5111 ## Private class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
5112 # with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
5114 class meshProxy(SMESH._objref_SMESH_Mesh):
5116 SMESH._objref_SMESH_Mesh.__init__(self)
5117 def __deepcopy__(self, memo=None):
5118 new = self.__class__()
5120 def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
5121 if len( args ) == 3:
5122 args += SMESH.ALL_NODES, True
5123 return SMESH._objref_SMESH_Mesh.CreateDimGroup( self, *args )
5125 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
5128 ## Private class wrapping SMESH.SMESH_SubMesh in order to add Compute()
5130 class submeshProxy(SMESH._objref_SMESH_subMesh):
5132 SMESH._objref_SMESH_subMesh.__init__(self)
5134 def __deepcopy__(self, memo=None):
5135 new = self.__class__()
5138 ## Compute the sub-mesh and return the status of the computation
5139 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
5140 # @return True or False
5142 # This is a method of SMESH.SMESH_submesh that can be obtained via Mesh.GetSubMesh() or
5143 # @ref smesh_algorithm.Mesh_Algorithm.GetSubMesh() "Mesh_Algorithm.GetSubMesh()".
5144 # @ingroup l2_submeshes
5145 def Compute(self,refresh=False):
5147 self.mesh = Mesh( smeshBuilder(), None, self.GetMesh())
5149 ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
5151 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
5152 smeshgui = salome.ImportComponentGUI("SMESH")
5153 smeshgui.Init(self.mesh.GetStudyId())
5154 smeshgui.SetMeshIcon( salome.ObjectToID( self ), ok, (self.GetNumberOfElements()==0) )
5155 if refresh: salome.sg.updateObjBrowser(True)
5160 omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy)
5163 ## Private class used to compensate change of CORBA API of SMESH_MeshEditor for backward
5164 # compatibility with old dump scripts which call SMESH_MeshEditor directly and not via
5167 class meshEditor(SMESH._objref_SMESH_MeshEditor):
5169 SMESH._objref_SMESH_MeshEditor.__init__(self)
5171 def __getattr__(self, name ): # method called if an attribute not found
5172 if not self.mesh: # look for name() method in Mesh class
5173 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
5174 if hasattr( self.mesh, name ):
5175 return getattr( self.mesh, name )
5176 if name == "ExtrusionAlongPathObjX":
5177 return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
5178 print "meshEditor: attribute '%s' NOT FOUND" % name
5180 def __deepcopy__(self, memo=None):
5181 new = self.__class__()
5183 def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
5184 if len( args ) == 1: args += False,
5185 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
5186 def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
5187 if len( args ) == 2: args += False,
5188 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
5189 def MergeNodes(self,*args): # 2 args added (NodesToKeep,AvoidMakingHoles)
5190 if len( args ) == 1:
5191 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [], False )
5192 NodesToKeep = args[1]
5193 AvoidMakingHoles = args[2] if len( args ) == 3 else False
5194 unRegister = genObjUnRegister()
5196 if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
5197 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
5198 if not isinstance( NodesToKeep, list ):
5199 NodesToKeep = [ NodesToKeep ]
5200 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep, AvoidMakingHoles )
5202 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
5204 ## Private class wrapping SMESH.SMESH_Pattern CORBA class in order to treat Notebook
5205 # variables in some methods
5207 class Pattern(SMESH._objref_SMESH_Pattern):
5209 def LoadFromFile(self, patternTextOrFile ):
5210 text = patternTextOrFile
5211 if os.path.exists( text ):
5212 text = open( patternTextOrFile ).read()
5214 return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
5216 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
5217 decrFun = lambda i: i-1
5218 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
5219 theMesh.SetParameters(Parameters)
5220 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
5222 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
5223 decrFun = lambda i: i-1
5224 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
5225 theMesh.SetParameters(Parameters)
5226 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
5228 def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
5229 if isinstance( mesh, Mesh ):
5230 mesh = mesh.GetMesh()
5231 return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
5233 # Registering the new proxy for Pattern
5234 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
5236 ## Private class used to bind methods creating algorithms to the class Mesh
5239 def __init__(self, method):
5241 self.defaultAlgoType = ""
5242 self.algoTypeToClass = {}
5243 self.method = method
5245 # Store a python class of algorithm
5246 def add(self, algoClass):
5247 if type( algoClass ).__name__ == 'classobj' and \
5248 hasattr( algoClass, "algoType"):
5249 self.algoTypeToClass[ algoClass.algoType ] = algoClass
5250 if not self.defaultAlgoType and \
5251 hasattr( algoClass, "isDefault") and algoClass.isDefault:
5252 self.defaultAlgoType = algoClass.algoType
5253 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
5255 # Create a copy of self and assign mesh to the copy
5256 def copy(self, mesh):
5257 other = algoCreator( self.method )
5258 other.defaultAlgoType = self.defaultAlgoType
5259 other.algoTypeToClass = self.algoTypeToClass
5263 # Create an instance of algorithm
5264 def __call__(self,algo="",geom=0,*args):
5267 if isinstance( algo, str ):
5269 elif ( isinstance( algo, geomBuilder.GEOM._objref_GEOM_Object ) and \
5270 not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object )):
5275 if isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
5277 elif not algoType and isinstance( geom, str ):
5282 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ) and not shape:
5284 elif isinstance( arg, str ) and not algoType:
5287 import traceback, sys
5288 msg = "Warning. Unexpected argument in mesh.%s() ---> %s" % ( self.method, arg )
5289 sys.stderr.write( msg + '\n' )
5290 tb = traceback.extract_stack(None,2)
5291 traceback.print_list( [tb[0]] )
5293 algoType = self.defaultAlgoType
5294 if not algoType and self.algoTypeToClass:
5295 algoType = sorted( self.algoTypeToClass.keys() )[0]
5296 if self.algoTypeToClass.has_key( algoType ):
5297 #print "Create algo",algoType
5298 return self.algoTypeToClass[ algoType ]( self.mesh, shape )
5299 raise RuntimeError, "No class found for algo type %s" % algoType
5302 ## Private class used to substitute and store variable parameters of hypotheses.
5304 class hypMethodWrapper:
5305 def __init__(self, hyp, method):
5307 self.method = method
5308 #print "REBIND:", method.__name__
5311 # call a method of hypothesis with calling SetVarParameter() before
5312 def __call__(self,*args):
5314 return self.method( self.hyp, *args ) # hypothesis method with no args
5316 #print "MethWrapper.__call__",self.method.__name__, args
5318 parsed = ParseParameters(*args) # replace variables with their values
5319 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
5320 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
5321 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
5322 # maybe there is a replaced string arg which is not variable
5323 result = self.method( self.hyp, *args )
5324 except ValueError, detail: # raised by ParseParameters()
5326 result = self.method( self.hyp, *args )
5327 except omniORB.CORBA.BAD_PARAM:
5328 raise ValueError, detail # wrong variable name
5333 ## A helper class that calls UnRegister() of SALOME.GenericObj'es stored in it
5335 class genObjUnRegister:
5337 def __init__(self, genObj=None):
5338 self.genObjList = []
5342 def set(self, genObj):
5343 "Store one or a list of of SALOME.GenericObj'es"
5344 if isinstance( genObj, list ):
5345 self.genObjList.extend( genObj )
5347 self.genObjList.append( genObj )
5351 for genObj in self.genObjList:
5352 if genObj and hasattr( genObj, "UnRegister" ):
5356 ## Bind methods creating mesher plug-ins to the Mesh class
5358 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
5360 #print "pluginName: ", pluginName
5361 pluginBuilderName = pluginName + "Builder"
5363 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
5364 except Exception, e:
5365 from salome_utils import verbose
5366 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
5368 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5369 plugin = eval( pluginBuilderName )
5370 #print " plugin:" , str(plugin)
5372 # add methods creating algorithms to Mesh
5373 for k in dir( plugin ):
5374 if k[0] == '_': continue
5375 algo = getattr( plugin, k )
5376 #print " algo:", str(algo)
5377 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
5378 #print " meshMethod:" , str(algo.meshMethod)
5379 if not hasattr( Mesh, algo.meshMethod ):
5380 setattr( Mesh, algo.meshMethod, algoCreator( algo.meshMethod ))
5382 getattr( Mesh, algo.meshMethod ).add( algo )