Salome HOME
22877: EDF 10054 SMESH: Add a new filter "BelongToSmeshGroup" for Create Group
[modules/smesh.git] / src / SMESH_SWIG / smeshBuilder.py
1 # Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
2 #
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.
7 #
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.
12 #
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
16 #
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 #
19 #  File   : smeshBuilder.py
20 #  Author : Francis KLOSS, OCC
21 #  Module : SMESH
22
23 ## @package smeshBuilder
24 #  Python API for SALOME %Mesh module
25
26 ## @defgroup l1_auxiliary Auxiliary methods and structures
27 ## @defgroup l1_creating  Creating meshes
28 ## @{
29 ##   @defgroup l2_impexp     Importing and exporting meshes
30 ##   @defgroup l2_construct  Constructing meshes
31 ##   @defgroup l2_algorithms Defining Algorithms
32 ##   @{
33 ##     @defgroup l3_algos_basic   Basic meshing algorithms
34 ##     @defgroup l3_algos_proj    Projection Algorithms
35 ##     @defgroup l3_algos_radialp Radial Prism
36 ##     @defgroup l3_algos_segmarv Segments around Vertex
37 ##     @defgroup l3_algos_3dextr  3D extrusion meshing algorithm
38
39 ##   @}
40 ##   @defgroup l2_hypotheses Defining hypotheses
41 ##   @{
42 ##     @defgroup l3_hypos_1dhyps 1D Meshing Hypotheses
43 ##     @defgroup l3_hypos_2dhyps 2D Meshing Hypotheses
44 ##     @defgroup l3_hypos_maxvol Max Element Volume hypothesis
45 ##     @defgroup l3_hypos_quad Quadrangle Parameters hypothesis
46 ##     @defgroup l3_hypos_additi Additional Hypotheses
47
48 ##   @}
49 ##   @defgroup l2_submeshes Constructing submeshes
50 ##   @defgroup l2_compounds Building Compounds
51 ##   @defgroup l2_editing   Editing Meshes
52
53 ## @}
54 ## @defgroup l1_meshinfo  Mesh Information
55 ## @defgroup l1_controls  Quality controls and Filtering
56 ## @defgroup l1_grouping  Grouping elements
57 ## @{
58 ##   @defgroup l2_grps_create Creating groups
59 ##   @defgroup l2_grps_edit   Editing groups
60 ##   @defgroup l2_grps_operon Using operations on groups
61 ##   @defgroup l2_grps_delete Deleting Groups
62
63 ## @}
64 ## @defgroup l1_modifying Modifying meshes
65 ## @{
66 ##   @defgroup l2_modif_add      Adding nodes and elements
67 ##   @defgroup l2_modif_del      Removing nodes and elements
68 ##   @defgroup l2_modif_edit     Modifying nodes and elements
69 ##   @defgroup l2_modif_renumber Renumbering nodes and elements
70 ##   @defgroup l2_modif_trsf     Transforming meshes (Translation, Rotation, Symmetry, Sewing, Merging)
71 ##   @defgroup l2_modif_movenode Moving nodes
72 ##   @defgroup l2_modif_throughp Mesh through point
73 ##   @defgroup l2_modif_invdiag  Diagonal inversion of elements
74 ##   @defgroup l2_modif_unitetri Uniting triangles
75 ##   @defgroup l2_modif_changori Changing orientation of elements
76 ##   @defgroup l2_modif_cutquadr Cutting elements
77 ##   @defgroup l2_modif_smooth   Smoothing
78 ##   @defgroup l2_modif_extrurev Extrusion and Revolution
79 ##   @defgroup l2_modif_patterns Pattern mapping
80 ##   @defgroup l2_modif_tofromqu Convert to/from Quadratic Mesh
81
82 ## @}
83 ## @defgroup l1_measurements Measurements
84
85 import salome
86 from salome.geom import geomBuilder
87
88 import SMESH # This is necessary for back compatibility
89 from   SMESH import *
90 from   salome.smesh.smesh_algorithm import Mesh_Algorithm
91
92 import SALOME
93 import SALOMEDS
94 import os
95
96 class MeshMeta(type):
97     def __instancecheck__(cls, inst):
98         """Implement isinstance(inst, cls)."""
99         return any(cls.__subclasscheck__(c)
100                    for c in {type(inst), inst.__class__})
101
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__)
105
106 ## @addtogroup l1_auxiliary
107 ## @{
108
109 ## Converts an angle from degrees to radians
110 def DegreesToRadians(AngleInDegrees):
111     from math import pi
112     return AngleInDegrees * pi / 180.0
113
114 import salome_notebook
115 notebook = salome_notebook.notebook
116 # Salome notebook variable separator
117 var_separator = ":"
118
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):
122     Result = []
123     Parameters = ""
124     hasVariables = False
125     varModifFun=None
126     if args and callable( args[-1] ):
127         args, varModifFun = args[:-1], args[-1]
128     for parameter in args:
129
130         Parameters += str(parameter) + var_separator
131
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)
137             hasVariables = True
138             if varModifFun:
139                 parameter = varModifFun(parameter)
140                 pass
141             pass
142         Result.append(parameter)
143
144         pass
145     Parameters = Parameters[:-1]
146     Result.append( Parameters )
147     Result.append( hasVariables )
148     return Result
149
150 # Parse parameters converting variables to radians
151 def ParseAngles(*args):
152     return ParseParameters( *( args + (DegreesToRadians, )))
153
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)
158     pass
159 SMESH.PointStruct.__init__ = __initPointStruct
160
161 # Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
162 # Parameters are stored in AxisStruct.parameters attribute
163 def __initAxisStruct(ax,*args):
164     if len( args ) != 6:
165         raise RuntimeError,\
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)
168     pass
169 SMESH.AxisStruct.__init__ = __initAxisStruct
170
171 smeshPrecisionConfusion = 1.e-07
172 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
173     if abs(val1 - val2) < tol:
174         return True
175     return False
176
177 NO_NAME = "NoName"
178
179 ## Gets object name
180 def GetName(obj):
181     if obj:
182         # object not null
183         if isinstance(obj, SALOMEDS._objref_SObject):
184             # study object
185             return obj.GetName()
186         try:
187             ior  = salome.orb.object_to_string(obj)
188         except:
189             ior = None
190         if ior:
191             # CORBA object
192             studies = salome.myStudyManager.GetOpenStudies()
193             for sname in studies:
194                 s = salome.myStudyManager.GetStudyByName(sname)
195                 if not s: continue
196                 sobj = s.FindObjectIOR(ior)
197                 if not sobj: continue
198                 return sobj.GetName()
199             if hasattr(obj, "GetName"):
200                 # unknown CORBA object, having GetName() method
201                 return obj.GetName()
202             else:
203                 # unknown CORBA object, no GetName() method
204                 return NO_NAME
205             pass
206         if hasattr(obj, "GetName"):
207             # unknown non-CORBA object, having GetName() method
208             return obj.GetName()
209         pass
210     raise RuntimeError, "Null or invalid object"
211
212 ## Prints error message if a hypothesis was not assigned.
213 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
214     if isAlgo:
215         hypType = "algorithm"
216     else:
217         hypType = "hypothesis"
218         pass
219     reason = ""
220     if hasattr( status, "__getitem__" ):
221         status,reason = status[0],status[1]
222     if status == HYP_UNKNOWN_FATAL :
223         reason = "for unknown reason"
224     elif status == HYP_INCOMPATIBLE :
225         reason = "this hypothesis mismatches the algorithm"
226     elif status == HYP_NOTCONFORM :
227         reason = "a non-conform mesh would be built"
228     elif status == HYP_ALREADY_EXIST :
229         if isAlgo: return # it does not influence anything
230         reason = hypType + " of the same dimension is already assigned to this shape"
231     elif status == HYP_BAD_DIM :
232         reason = hypType + " mismatches the shape"
233     elif status == HYP_CONCURENT :
234         reason = "there are concurrent hypotheses on sub-shapes"
235     elif status == HYP_BAD_SUBSHAPE :
236         reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
237     elif status == HYP_BAD_GEOMETRY:
238         reason = "geometry mismatches the expectation of the algorithm"
239     elif status == HYP_HIDDEN_ALGO:
240         reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
241     elif status == HYP_HIDING_ALGO:
242         reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
243     elif status == HYP_NEED_SHAPE:
244         reason = "algorithm can't work without shape"
245     elif status == HYP_INCOMPAT_HYPS:
246         pass
247     else:
248         return
249     where = geomName
250     if where:
251         where = '"%s"' % geomName
252         if mesh:
253             meshName = GetName( mesh )
254             if meshName and meshName != NO_NAME:
255                 where = '"%s" in "%s"' % ( geomName, meshName )
256     if status < HYP_UNKNOWN_FATAL and where:
257         print '"%s" was assigned to %s but %s' %( hypName, where, reason )
258     elif where:
259         print '"%s" was not assigned to %s : %s' %( hypName, where, reason )
260     else:
261         print '"%s" was not assigned : %s' %( hypName, reason )
262         pass
263
264 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
265 def AssureGeomPublished(mesh, geom, name=''):
266     if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
267         return
268     if not geom.GetStudyEntry() and \
269            mesh.smeshpyD.GetCurrentStudy():
270         ## set the study
271         studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
272         if studyID != mesh.geompyD.myStudyId:
273             mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
274         ## get a name
275         if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
276             # for all groups SubShapeName() returns "Compound_-1"
277             name = mesh.geompyD.SubShapeName(geom, mesh.geom)
278         if not name:
279             name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
280         ## publish
281         mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
282     return
283
284 ## Return the first vertex of a geometrical edge by ignoring orientation
285 def FirstVertexOnCurve(mesh, edge):
286     vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
287     if not vv:
288         raise TypeError, "Given object has no vertices"
289     if len( vv ) == 1: return vv[0]
290     v0   = mesh.geompyD.MakeVertexOnCurve(edge,0.)
291     xyz  = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
292     xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
293     xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
294     dist1, dist2 = 0,0
295     for i in range(3):
296         dist1 += abs( xyz[i] - xyz1[i] )
297         dist2 += abs( xyz[i] - xyz2[i] )
298     if dist1 < dist2:
299         return vv[0]
300     else:
301         return vv[1]
302
303 # end of l1_auxiliary
304 ## @}
305
306
307 # Warning: smeshInst is a singleton
308 smeshInst = None
309 engine = None
310 doLcc = False
311 created = False
312
313 ## This class allows to create, load or manipulate meshes
314 #  It has a set of methods to create load or copy meshes, to combine several meshes.
315 #  It also has methods to get infos on meshes.
316 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
317
318     # MirrorType enumeration
319     POINT = SMESH_MeshEditor.POINT
320     AXIS =  SMESH_MeshEditor.AXIS
321     PLANE = SMESH_MeshEditor.PLANE
322
323     # Smooth_Method enumeration
324     LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
325     CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
326
327     PrecisionConfusion = smeshPrecisionConfusion
328
329     # TopAbs_State enumeration
330     [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
331
332     # Methods of splitting a hexahedron into tetrahedra
333     Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
334
335     def __new__(cls):
336         global engine
337         global smeshInst
338         global doLcc
339         #print "==== __new__", engine, smeshInst, doLcc
340
341         if smeshInst is None:
342             # smesh engine is either retrieved from engine, or created
343             smeshInst = engine
344             # Following test avoids a recursive loop
345             if doLcc:
346                 if smeshInst is not None:
347                     # smesh engine not created: existing engine found
348                     doLcc = False
349                 if doLcc:
350                     doLcc = False
351                     # FindOrLoadComponent called:
352                     # 1. CORBA resolution of server
353                     # 2. the __new__ method is called again
354                     #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
355                     smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
356             else:
357                 # FindOrLoadComponent not called
358                 if smeshInst is None:
359                     # smeshBuilder instance is created from lcc.FindOrLoadComponent
360                     #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
361                     smeshInst = super(smeshBuilder,cls).__new__(cls)
362                 else:
363                     # smesh engine not created: existing engine found
364                     #print "==== existing ", engine, smeshInst, doLcc
365                     pass
366             #print "====1 ", smeshInst
367             return smeshInst
368
369         #print "====2 ", smeshInst
370         return smeshInst
371
372     def __init__(self):
373         global created
374         #print "--------------- smeshbuilder __init__ ---", created
375         if not created:
376           created = True
377           SMESH._objref_SMESH_Gen.__init__(self)
378
379     ## Dump component to the Python script
380     #  This method overrides IDL function to allow default values for the parameters.
381     def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
382         return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
383
384     ## Set mode of DumpPython(), \a historical or \a snapshot.
385     # In the \a historical mode, the Python Dump script includes all commands
386     # performed by SMESH engine. In the \a snapshot mode, commands
387     # relating to objects removed from the Study are excluded from the script
388     # as well as commands not influencing the current state of meshes
389     def SetDumpPythonHistorical(self, isHistorical):
390         if isHistorical: val = "true"
391         else:            val = "false"
392         SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
393
394     ## Sets the current study and Geometry component
395     #  @ingroup l1_auxiliary
396     def init_smesh(self,theStudy,geompyD = None):
397         #print "init_smesh"
398         self.SetCurrentStudy(theStudy,geompyD)
399         if theStudy:
400             global notebook
401             notebook.myStudy = theStudy
402
403     ## Creates a mesh. This can be either an empty mesh, possibly having an underlying geometry,
404     #  or a mesh wrapping a CORBA mesh given as a parameter.
405     #  @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
406     #         salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
407     #         (2) a Geometrical object for meshing or
408     #         (3) none.
409     #  @param name the name for the new mesh.
410     #  @return an instance of Mesh class.
411     #  @ingroup l2_construct
412     def Mesh(self, obj=0, name=0):
413         if isinstance(obj,str):
414             obj,name = name,obj
415         return Mesh(self,self.geompyD,obj,name)
416
417     ## Returns a long value from enumeration
418     #  @ingroup l1_controls
419     def EnumToLong(self,theItem):
420         return theItem._v
421
422     ## Returns a string representation of the color.
423     #  To be used with filters.
424     #  @param c color value (SALOMEDS.Color)
425     #  @ingroup l1_controls
426     def ColorToString(self,c):
427         val = ""
428         if isinstance(c, SALOMEDS.Color):
429             val = "%s;%s;%s" % (c.R, c.G, c.B)
430         elif isinstance(c, str):
431             val = c
432         else:
433             raise ValueError, "Color value should be of string or SALOMEDS.Color type"
434         return val
435
436     ## Gets PointStruct from vertex
437     #  @param theVertex a GEOM object(vertex)
438     #  @return SMESH.PointStruct
439     #  @ingroup l1_auxiliary
440     def GetPointStruct(self,theVertex):
441         [x, y, z] = self.geompyD.PointCoordinates(theVertex)
442         return PointStruct(x,y,z)
443
444     ## Gets DirStruct from vector
445     #  @param theVector a GEOM object(vector)
446     #  @return SMESH.DirStruct
447     #  @ingroup l1_auxiliary
448     def GetDirStruct(self,theVector):
449         vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
450         if(len(vertices) != 2):
451             print "Error: vector object is incorrect."
452             return None
453         p1 = self.geompyD.PointCoordinates(vertices[0])
454         p2 = self.geompyD.PointCoordinates(vertices[1])
455         pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
456         dirst = DirStruct(pnt)
457         return dirst
458
459     ## Makes DirStruct from a triplet
460     #  @param x,y,z vector components
461     #  @return SMESH.DirStruct
462     #  @ingroup l1_auxiliary
463     def MakeDirStruct(self,x,y,z):
464         pnt = PointStruct(x,y,z)
465         return DirStruct(pnt)
466
467     ## Get AxisStruct from object
468     #  @param theObj a GEOM object (line or plane)
469     #  @return SMESH.AxisStruct
470     #  @ingroup l1_auxiliary
471     def GetAxisStruct(self,theObj):
472         import GEOM
473         edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
474         axis = None
475         if len(edges) > 1:
476             vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
477             vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
478             vertex1 = self.geompyD.PointCoordinates(vertex1)
479             vertex2 = self.geompyD.PointCoordinates(vertex2)
480             vertex3 = self.geompyD.PointCoordinates(vertex3)
481             vertex4 = self.geompyD.PointCoordinates(vertex4)
482             v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
483             v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
484             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] ]
485             axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
486             axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
487         elif len(edges) == 1:
488             vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
489             p1 = self.geompyD.PointCoordinates( vertex1 )
490             p2 = self.geompyD.PointCoordinates( vertex2 )
491             axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
492             axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
493         elif theObj.GetShapeType() == GEOM.VERTEX:
494             x,y,z = self.geompyD.PointCoordinates( theObj )
495             axis = AxisStruct( x,y,z, 1,0,0,)
496             axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
497         return axis
498
499     # From SMESH_Gen interface:
500     # ------------------------
501
502     ## Sets the given name to the object
503     #  @param obj the object to rename
504     #  @param name a new object name
505     #  @ingroup l1_auxiliary
506     def SetName(self, obj, name):
507         if isinstance( obj, Mesh ):
508             obj = obj.GetMesh()
509         elif isinstance( obj, Mesh_Algorithm ):
510             obj = obj.GetAlgorithm()
511         ior  = salome.orb.object_to_string(obj)
512         SMESH._objref_SMESH_Gen.SetName(self, ior, name)
513
514     ## Sets the current mode
515     #  @ingroup l1_auxiliary
516     def SetEmbeddedMode( self,theMode ):
517         #self.SetEmbeddedMode(theMode)
518         SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
519
520     ## Gets the current mode
521     #  @ingroup l1_auxiliary
522     def IsEmbeddedMode(self):
523         #return self.IsEmbeddedMode()
524         return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
525
526     ## Sets the current study. Calling SetCurrentStudy( None ) allows to
527     #  switch OFF automatic pubilishing in the Study of mesh objects.
528     #  @ingroup l1_auxiliary
529     def SetCurrentStudy( self, theStudy, geompyD = None ):
530         #self.SetCurrentStudy(theStudy)
531         if not geompyD:
532             from salome.geom import geomBuilder
533             geompyD = geomBuilder.geom
534             pass
535         self.geompyD=geompyD
536         self.SetGeomEngine(geompyD)
537         SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
538         global notebook
539         if theStudy:
540             notebook = salome_notebook.NoteBook( theStudy )
541         else:
542             notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
543         if theStudy:
544             sb = theStudy.NewBuilder()
545             sc = theStudy.FindComponent("SMESH")
546             if sc: sb.LoadWith(sc, self)
547             pass
548         pass
549
550     ## Gets the current study
551     #  @ingroup l1_auxiliary
552     def GetCurrentStudy(self):
553         #return self.GetCurrentStudy()
554         return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
555
556     ## Creates a Mesh object importing data from the given UNV file
557     #  @return an instance of Mesh class
558     #  @ingroup l2_impexp
559     def CreateMeshesFromUNV( self,theFileName ):
560         aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
561         aMesh = Mesh(self, self.geompyD, aSmeshMesh)
562         return aMesh
563
564     ## Creates a Mesh object(s) importing data from the given MED file
565     #  @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
566     #  @ingroup l2_impexp
567     def CreateMeshesFromMED( self,theFileName ):
568         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
569         aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
570         return aMeshes, aStatus
571
572     ## Creates a Mesh object(s) importing data from the given SAUV file
573     #  @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
574     #  @ingroup l2_impexp
575     def CreateMeshesFromSAUV( self,theFileName ):
576         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
577         aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
578         return aMeshes, aStatus
579
580     ## Creates a Mesh object importing data from the given STL file
581     #  @return an instance of Mesh class
582     #  @ingroup l2_impexp
583     def CreateMeshesFromSTL( self, theFileName ):
584         aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
585         aMesh = Mesh(self, self.geompyD, aSmeshMesh)
586         return aMesh
587
588     ## Creates Mesh objects importing data from the given CGNS file
589     #  @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
590     #  @ingroup l2_impexp
591     def CreateMeshesFromCGNS( self, theFileName ):
592         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
593         aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
594         return aMeshes, aStatus
595
596     ## Creates a Mesh object importing data from the given GMF file.
597     #  GMF files must have .mesh extension for the ASCII format and .meshb for
598     #  the binary format.
599     #  @return [ an instance of Mesh class, SMESH.ComputeError ]
600     #  @ingroup l2_impexp
601     def CreateMeshesFromGMF( self, theFileName ):
602         aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
603                                                                         theFileName,
604                                                                         True)
605         if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
606         return Mesh(self, self.geompyD, aSmeshMesh), error
607
608     ## Concatenate the given meshes into one mesh. All groups of input meshes will be
609     #  present in the new mesh.
610     #  @param meshes the meshes, sub-meshes and groups to combine into one mesh
611     #  @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
612     #  @param mergeNodesAndElements if true, equal nodes and elements are merged
613     #  @param mergeTolerance tolerance for merging nodes
614     #  @param allGroups forces creation of groups corresponding to every input mesh
615     #  @param name name of a new mesh
616     #  @return an instance of Mesh class
617     def Concatenate( self, meshes, uniteIdenticalGroups,
618                      mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
619                      name = ""):
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)
626         if allGroups:
627             aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
628                 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
629         else:
630             aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
631                 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
632         aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
633         return aMesh
634
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     def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
644         if (isinstance( meshPart, Mesh )):
645             meshPart = meshPart.GetMesh()
646         mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
647         return Mesh(self, self.geompyD, mesh)
648
649     ## From SMESH_Gen interface
650     #  @return the list of integer values
651     #  @ingroup l1_auxiliary
652     def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
653         return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
654
655     ## From SMESH_Gen interface. Creates a pattern
656     #  @return an instance of SMESH_Pattern
657     #
658     #  <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
659     #  @ingroup l2_modif_patterns
660     def GetPattern(self):
661         return SMESH._objref_SMESH_Gen.GetPattern(self)
662
663     ## Sets number of segments per diagonal of boundary box of geometry by which
664     #  default segment length of appropriate 1D hypotheses is defined.
665     #  Default value is 10
666     #  @ingroup l1_auxiliary
667     def SetBoundaryBoxSegmentation(self, nbSegments):
668         SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
669
670     # Filtering. Auxiliary functions:
671     # ------------------------------
672
673     ## Creates an empty criterion
674     #  @return SMESH.Filter.Criterion
675     #  @ingroup l1_controls
676     def GetEmptyCriterion(self):
677         Type = self.EnumToLong(FT_Undefined)
678         Compare = self.EnumToLong(FT_Undefined)
679         Threshold = 0
680         ThresholdStr = ""
681         ThresholdID = ""
682         UnaryOp = self.EnumToLong(FT_Undefined)
683         BinaryOp = self.EnumToLong(FT_Undefined)
684         Tolerance = 1e-07
685         TypeOfElement = ALL
686         Precision = -1 ##@1e-07
687         return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
688                                 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
689
690     ## Creates a criterion by the given parameters
691     #  \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
692     #  @param elementType the type of elements(NODE, EDGE, FACE, VOLUME)
693     #  @param CritType the type of criterion (FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc.)
694     #  @param Compare  belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
695     #  @param Threshold the threshold value (range of ids as string, shape, numeric)
696     #  @param UnaryOp  FT_LogicalNOT or FT_Undefined
697     #  @param BinaryOp a binary logical operation FT_LogicalAND, FT_LogicalOR or
698     #                  FT_Undefined (must be for the last criterion of all criteria)
699     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
700     #         FT_LyingOnGeom, FT_CoplanarFaces criteria
701     #  @return SMESH.Filter.Criterion
702     #
703     #  <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
704     #  @ingroup l1_controls
705     def GetCriterion(self,elementType,
706                      CritType,
707                      Compare = FT_EqualTo,
708                      Threshold="",
709                      UnaryOp=FT_Undefined,
710                      BinaryOp=FT_Undefined,
711                      Tolerance=1e-07):
712         if not CritType in SMESH.FunctorType._items:
713             raise TypeError, "CritType should be of SMESH.FunctorType"
714         aCriterion               = self.GetEmptyCriterion()
715         aCriterion.TypeOfElement = elementType
716         aCriterion.Type          = self.EnumToLong(CritType)
717         aCriterion.Tolerance     = Tolerance
718
719         aThreshold = Threshold
720
721         if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
722             aCriterion.Compare = self.EnumToLong(Compare)
723         elif Compare == "=" or Compare == "==":
724             aCriterion.Compare = self.EnumToLong(FT_EqualTo)
725         elif Compare == "<":
726             aCriterion.Compare = self.EnumToLong(FT_LessThan)
727         elif Compare == ">":
728             aCriterion.Compare = self.EnumToLong(FT_MoreThan)
729         elif Compare != FT_Undefined:
730             aCriterion.Compare = self.EnumToLong(FT_EqualTo)
731             aThreshold = Compare
732
733         if CritType in [FT_BelongToGeom,     FT_BelongToPlane, FT_BelongToGenSurface,
734                         FT_BelongToCylinder, FT_LyingOnGeom]:
735             # Check that Threshold is GEOM object
736             if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
737                 aCriterion.ThresholdStr = GetName(aThreshold)
738                 aCriterion.ThresholdID  = aThreshold.GetStudyEntry()
739                 if not aCriterion.ThresholdID:
740                     name = aCriterion.ThresholdStr
741                     if not name:
742                         name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
743                     aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
744             # or a name of GEOM object
745             elif isinstance( aThreshold, str ):
746                 aCriterion.ThresholdStr = aThreshold
747             else:
748                 raise TypeError, "The Threshold should be a shape."
749             if isinstance(UnaryOp,float):
750                 aCriterion.Tolerance = UnaryOp
751                 UnaryOp = FT_Undefined
752                 pass
753         elif CritType == FT_BelongToMeshGroup:
754             # Check that Threshold is a group
755             if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
756                 if aThreshold.GetType() != elementType:
757                     raise ValueError, "Group type mismatches Element type"
758                 aCriterion.ThresholdStr = aThreshold.GetName()
759                 aCriterion.ThresholdID  = salome.orb.object_to_string( aThreshold )
760             else:
761                 raise TypeError, "The Threshold should be a Mesh Group"
762         elif CritType == FT_RangeOfIds:
763             # Check that Threshold is string
764             if isinstance(aThreshold, str):
765                 aCriterion.ThresholdStr = aThreshold
766             else:
767                 raise TypeError, "The Threshold should be a string."
768         elif CritType == FT_CoplanarFaces:
769             # Check the Threshold
770             if isinstance(aThreshold, int):
771                 aCriterion.ThresholdID = str(aThreshold)
772             elif isinstance(aThreshold, str):
773                 ID = int(aThreshold)
774                 if ID < 1:
775                     raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
776                 aCriterion.ThresholdID = aThreshold
777             else:
778                 raise TypeError,\
779                       "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
780         elif CritType == FT_ConnectedElements:
781             # Check the Threshold
782             if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
783                 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
784                 if not aCriterion.ThresholdID:
785                     name = aThreshold.GetName()
786                     if not name:
787                         name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
788                     aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
789             elif isinstance(aThreshold, int): # node id
790                 aCriterion.Threshold = aThreshold
791             elif isinstance(aThreshold, list): # 3 point coordinates
792                 if len( aThreshold ) < 3:
793                     raise ValueError, "too few point coordinates, must be 3"
794                 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
795             elif isinstance(aThreshold, str):
796                 if aThreshold.isdigit():
797                     aCriterion.Threshold = aThreshold # node id
798                 else:
799                     aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
800             else:
801                 raise TypeError,\
802                       "The Threshold should either a VERTEX, or a node ID, "\
803                       "or a list of point coordinates and not '%s'"%aThreshold
804         elif CritType == FT_ElemGeomType:
805             # Check the Threshold
806             try:
807                 aCriterion.Threshold = self.EnumToLong(aThreshold)
808                 assert( aThreshold in SMESH.GeometryType._items )
809             except:
810                 if isinstance(aThreshold, int):
811                     aCriterion.Threshold = aThreshold
812                 else:
813                     raise TypeError, "The Threshold should be an integer or SMESH.GeometryType."
814                 pass
815             pass
816         elif CritType == FT_EntityType:
817             # Check the Threshold
818             try:
819                 aCriterion.Threshold = self.EnumToLong(aThreshold)
820                 assert( aThreshold in SMESH.EntityType._items )
821             except:
822                 if isinstance(aThreshold, int):
823                     aCriterion.Threshold = aThreshold
824                 else:
825                     raise TypeError, "The Threshold should be an integer or SMESH.EntityType."
826                 pass
827             pass
828         
829         elif CritType == FT_GroupColor:
830             # Check the Threshold
831             try:
832                 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
833             except:
834                 raise TypeError, "The threshold value should be of SALOMEDS.Color type"
835             pass
836         elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
837                           FT_LinearOrQuadratic, FT_BadOrientedVolume,
838                           FT_BareBorderFace, FT_BareBorderVolume,
839                           FT_OverConstrainedFace, FT_OverConstrainedVolume,
840                           FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
841             # At this point the Threshold is unnecessary
842             if aThreshold ==  FT_LogicalNOT:
843                 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
844             elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
845                 aCriterion.BinaryOp = aThreshold
846         else:
847             # Check Threshold
848             try:
849                 aThreshold = float(aThreshold)
850                 aCriterion.Threshold = aThreshold
851             except:
852                 raise TypeError, "The Threshold should be a number."
853                 return None
854
855         if Threshold ==  FT_LogicalNOT or UnaryOp ==  FT_LogicalNOT:
856             aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
857
858         if Threshold in [FT_LogicalAND, FT_LogicalOR]:
859             aCriterion.BinaryOp = self.EnumToLong(Threshold)
860
861         if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
862             aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
863
864         if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
865             aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
866
867         return aCriterion
868
869     ## Creates a filter with the given parameters
870     #  @param elementType the type of elements in the group
871     #  @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
872     #  @param Compare  belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
873     #  @param Threshold the threshold value (range of id ids as string, shape, numeric)
874     #  @param UnaryOp  FT_LogicalNOT or FT_Undefined
875     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
876     #         FT_LyingOnGeom, FT_CoplanarFaces and FT_EqualNodes criteria
877     #  @param mesh the mesh to initialize the filter with
878     #  @return SMESH_Filter
879     #
880     #  <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
881     #  @ingroup l1_controls
882     def GetFilter(self,elementType,
883                   CritType=FT_Undefined,
884                   Compare=FT_EqualTo,
885                   Threshold="",
886                   UnaryOp=FT_Undefined,
887                   Tolerance=1e-07,
888                   mesh=None):
889         aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
890         aFilterMgr = self.CreateFilterManager()
891         aFilter = aFilterMgr.CreateFilter()
892         aCriteria = []
893         aCriteria.append(aCriterion)
894         aFilter.SetCriteria(aCriteria)
895         if mesh:
896             if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
897             else                       : aFilter.SetMesh( mesh )
898         aFilterMgr.UnRegister()
899         return aFilter
900
901     ## Creates a filter from criteria
902     #  @param criteria a list of criteria
903     #  @param binOp binary operator used when binary operator of criteria is undefined
904     #  @return SMESH_Filter
905     #
906     #  <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
907     #  @ingroup l1_controls
908     def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
909         for i in range( len( criteria ) - 1 ):
910             if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
911                 criteria[i].BinaryOp = self.EnumToLong( binOp )
912         aFilterMgr = self.CreateFilterManager()
913         aFilter = aFilterMgr.CreateFilter()
914         aFilter.SetCriteria(criteria)
915         aFilterMgr.UnRegister()
916         return aFilter
917
918     ## Creates a numerical functor by its type
919     #  @param theCriterion FT_...; functor type
920     #  @return SMESH_NumericalFunctor
921     #  @ingroup l1_controls
922     def GetFunctor(self,theCriterion):
923         if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
924             return theCriterion
925         aFilterMgr = self.CreateFilterManager()
926         functor = None
927         if theCriterion == FT_AspectRatio:
928             functor = aFilterMgr.CreateAspectRatio()
929         elif theCriterion == FT_AspectRatio3D:
930             functor = aFilterMgr.CreateAspectRatio3D()
931         elif theCriterion == FT_Warping:
932             functor = aFilterMgr.CreateWarping()
933         elif theCriterion == FT_MinimumAngle:
934             functor = aFilterMgr.CreateMinimumAngle()
935         elif theCriterion == FT_Taper:
936             functor = aFilterMgr.CreateTaper()
937         elif theCriterion == FT_Skew:
938             functor = aFilterMgr.CreateSkew()
939         elif theCriterion == FT_Area:
940             functor = aFilterMgr.CreateArea()
941         elif theCriterion == FT_Volume3D:
942             functor = aFilterMgr.CreateVolume3D()
943         elif theCriterion == FT_MaxElementLength2D:
944             functor = aFilterMgr.CreateMaxElementLength2D()
945         elif theCriterion == FT_MaxElementLength3D:
946             functor = aFilterMgr.CreateMaxElementLength3D()
947         elif theCriterion == FT_MultiConnection:
948             functor = aFilterMgr.CreateMultiConnection()
949         elif theCriterion == FT_MultiConnection2D:
950             functor = aFilterMgr.CreateMultiConnection2D()
951         elif theCriterion == FT_Length:
952             functor = aFilterMgr.CreateLength()
953         elif theCriterion == FT_Length2D:
954             functor = aFilterMgr.CreateLength2D()
955         else:
956             print "Error: given parameter is not numerical functor type."
957         aFilterMgr.UnRegister()
958         return functor
959
960     ## Creates hypothesis
961     #  @param theHType mesh hypothesis type (string)
962     #  @param theLibName mesh plug-in library name
963     #  @return created hypothesis instance
964     def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
965         hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
966
967         if isinstance( hyp, SMESH._objref_SMESH_Algo ):
968             return hyp
969
970         # wrap hypothesis methods
971         #print "HYPOTHESIS", theHType
972         for meth_name in dir( hyp.__class__ ):
973             if not meth_name.startswith("Get") and \
974                not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
975                 method = getattr ( hyp.__class__, meth_name )
976                 if callable(method):
977                     setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
978
979         return hyp
980
981     ## Gets the mesh statistic
982     #  @return dictionary "element type" - "count of elements"
983     #  @ingroup l1_meshinfo
984     def GetMeshInfo(self, obj):
985         if isinstance( obj, Mesh ):
986             obj = obj.GetMesh()
987         d = {}
988         if hasattr(obj, "GetMeshInfo"):
989             values = obj.GetMeshInfo()
990             for i in range(SMESH.Entity_Last._v):
991                 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
992             pass
993         return d
994
995     ## Get minimum distance between two objects
996     #
997     #  If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
998     #  If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
999     #
1000     #  @param src1 first source object
1001     #  @param src2 second source object
1002     #  @param id1 node/element id from the first source
1003     #  @param id2 node/element id from the second (or first) source
1004     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1005     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1006     #  @return minimum distance value
1007     #  @sa GetMinDistance()
1008     #  @ingroup l1_measurements
1009     def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1010         result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1011         if result is None:
1012             result = 0.0
1013         else:
1014             result = result.value
1015         return result
1016
1017     ## Get measure structure specifying minimum distance data between two objects
1018     #
1019     #  If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1020     #  If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1021     #
1022     #  @param src1 first source object
1023     #  @param src2 second source object
1024     #  @param id1 node/element id from the first source
1025     #  @param id2 node/element id from the second (or first) source
1026     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1027     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1028     #  @return Measure structure or None if input data is invalid
1029     #  @sa MinDistance()
1030     #  @ingroup l1_measurements
1031     def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1032         if isinstance(src1, Mesh): src1 = src1.mesh
1033         if isinstance(src2, Mesh): src2 = src2.mesh
1034         if src2 is None and id2 != 0: src2 = src1
1035         if not hasattr(src1, "_narrow"): return None
1036         src1 = src1._narrow(SMESH.SMESH_IDSource)
1037         if not src1: return None
1038         unRegister = genObjUnRegister()
1039         if id1 != 0:
1040             m = src1.GetMesh()
1041             e = m.GetMeshEditor()
1042             if isElem1:
1043                 src1 = e.MakeIDSource([id1], SMESH.FACE)
1044             else:
1045                 src1 = e.MakeIDSource([id1], SMESH.NODE)
1046             unRegister.set( src1 )
1047             pass
1048         if hasattr(src2, "_narrow"):
1049             src2 = src2._narrow(SMESH.SMESH_IDSource)
1050             if src2 and id2 != 0:
1051                 m = src2.GetMesh()
1052                 e = m.GetMeshEditor()
1053                 if isElem2:
1054                     src2 = e.MakeIDSource([id2], SMESH.FACE)
1055                 else:
1056                     src2 = e.MakeIDSource([id2], SMESH.NODE)
1057                 unRegister.set( src2 )
1058                 pass
1059             pass
1060         aMeasurements = self.CreateMeasurements()
1061         unRegister.set( aMeasurements )
1062         result = aMeasurements.MinDistance(src1, src2)
1063         return result
1064
1065     ## Get bounding box of the specified object(s)
1066     #  @param objects single source object or list of source objects
1067     #  @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1068     #  @sa GetBoundingBox()
1069     #  @ingroup l1_measurements
1070     def BoundingBox(self, objects):
1071         result = self.GetBoundingBox(objects)
1072         if result is None:
1073             result = (0.0,)*6
1074         else:
1075             result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1076         return result
1077
1078     ## Get measure structure specifying bounding box data of the specified object(s)
1079     #  @param objects single source object or list of source objects
1080     #  @return Measure structure
1081     #  @sa BoundingBox()
1082     #  @ingroup l1_measurements
1083     def GetBoundingBox(self, objects):
1084         if isinstance(objects, tuple):
1085             objects = list(objects)
1086         if not isinstance(objects, list):
1087             objects = [objects]
1088         srclist = []
1089         for o in objects:
1090             if isinstance(o, Mesh):
1091                 srclist.append(o.mesh)
1092             elif hasattr(o, "_narrow"):
1093                 src = o._narrow(SMESH.SMESH_IDSource)
1094                 if src: srclist.append(src)
1095                 pass
1096             pass
1097         aMeasurements = self.CreateMeasurements()
1098         result = aMeasurements.BoundingBox(srclist)
1099         aMeasurements.UnRegister()
1100         return result
1101
1102     ## Get sum of lengths of all 1D elements in the mesh object.
1103     #  @param obj mesh, submesh or group
1104     #  @return sum of lengths of all 1D elements
1105     #  @ingroup l1_measurements
1106     def GetLength(self, obj):
1107         if isinstance(obj, Mesh): obj = obj.mesh
1108         if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1109         aMeasurements = self.CreateMeasurements()
1110         value = aMeasurements.Length(obj)
1111         aMeasurements.UnRegister()
1112         return value
1113
1114     ## Get sum of areas of all 2D elements in the mesh object.
1115     #  @param obj mesh, submesh or group
1116     #  @return sum of areas of all 2D elements
1117     #  @ingroup l1_measurements
1118     def GetArea(self, obj):
1119         if isinstance(obj, Mesh): obj = obj.mesh
1120         if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1121         aMeasurements = self.CreateMeasurements()
1122         value = aMeasurements.Area(obj)
1123         aMeasurements.UnRegister()
1124         return value
1125
1126     ## Get sum of volumes of all 3D elements in the mesh object.
1127     #  @param obj mesh, submesh or group
1128     #  @return sum of volumes of all 3D elements
1129     #  @ingroup l1_measurements
1130     def GetVolume(self, obj):
1131         if isinstance(obj, Mesh): obj = obj.mesh
1132         if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1133         aMeasurements = self.CreateMeasurements()
1134         value = aMeasurements.Volume(obj)
1135         aMeasurements.UnRegister()
1136         return value
1137
1138     pass # end of class smeshBuilder
1139
1140 import omniORB
1141 #Registering the new proxy for SMESH_Gen
1142 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1143
1144 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1145 #  interface to create or load meshes.
1146 #
1147 #  Typical use is:
1148 #  \code
1149 #    import salome
1150 #    salome.salome_init()
1151 #    from salome.smesh import smeshBuilder
1152 #    smesh = smeshBuilder.New(theStudy)
1153 #  \endcode
1154 #  @param  study     SALOME study, generally obtained by salome.myStudy.
1155 #  @param  instance  CORBA proxy of SMESH Engine. If None, the default Engine is used.
1156 #  @return smeshBuilder instance
1157
1158 def New( study, instance=None):
1159     """
1160     Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1161     interface to create or load meshes.
1162
1163     Typical use is:
1164         import salome
1165         salome.salome_init()
1166         from salome.smesh import smeshBuilder
1167         smesh = smeshBuilder.New(theStudy)
1168
1169     Parameters:
1170         study     SALOME study, generally obtained by salome.myStudy.
1171         instance  CORBA proxy of SMESH Engine. If None, the default Engine is used.
1172     Returns:
1173         smeshBuilder instance
1174     """
1175     global engine
1176     global smeshInst
1177     global doLcc
1178     engine = instance
1179     if engine is None:
1180       doLcc = True
1181     smeshInst = smeshBuilder()
1182     assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1183     smeshInst.init_smesh(study)
1184     return smeshInst
1185
1186
1187 # Public class: Mesh
1188 # ==================
1189
1190 ## This class allows defining and managing a mesh.
1191 #  It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1192 #  It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1193 #  new nodes and elements and by changing the existing entities), to get information
1194 #  about a mesh and to export a mesh into different formats.
1195 class Mesh:
1196     __metaclass__ = MeshMeta
1197
1198     geom = 0
1199     mesh = 0
1200     editor = 0
1201
1202     ## Constructor
1203     #
1204     #  Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1205     #  sets the GUI name of this mesh to \a name.
1206     #  @param smeshpyD an instance of smeshBuilder class
1207     #  @param geompyD an instance of geomBuilder class
1208     #  @param obj Shape to be meshed or SMESH_Mesh object
1209     #  @param name Study name of the mesh
1210     #  @ingroup l2_construct
1211     def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1212         self.smeshpyD=smeshpyD
1213         self.geompyD=geompyD
1214         if obj is None:
1215             obj = 0
1216         objHasName = False
1217         if obj != 0:
1218             if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1219                 self.geom = obj
1220                 objHasName = True
1221                 # publish geom of mesh (issue 0021122)
1222                 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1223                     objHasName = False
1224                     studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1225                     if studyID != geompyD.myStudyId:
1226                         geompyD.init_geom( smeshpyD.GetCurrentStudy())
1227                         pass
1228                     if name:
1229                         geo_name = name + " shape"
1230                     else:
1231                         geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1232                     geompyD.addToStudy( self.geom, geo_name )
1233                 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1234
1235             elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1236                 self.SetMesh(obj)
1237         else:
1238             self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1239         if name:
1240             self.smeshpyD.SetName(self.mesh, name)
1241         elif objHasName:
1242             self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1243
1244         if not self.geom:
1245             self.geom = self.mesh.GetShapeToMesh()
1246
1247         self.editor   = self.mesh.GetMeshEditor()
1248         self.functors = [None] * SMESH.FT_Undefined._v
1249
1250         # set self to algoCreator's
1251         for attrName in dir(self):
1252             attr = getattr( self, attrName )
1253             if isinstance( attr, algoCreator ):
1254                 setattr( self, attrName, attr.copy( self ))
1255                 pass
1256             pass
1257         pass
1258
1259     ## Destructor. Clean-up resources
1260     def __del__(self):
1261         if self.mesh:
1262             #self.mesh.UnRegister()
1263             pass
1264         pass
1265         
1266     ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1267     #  @param theMesh a SMESH_Mesh object
1268     #  @ingroup l2_construct
1269     def SetMesh(self, theMesh):
1270         # do not call Register() as this prevents mesh servant deletion at closing study
1271         #if self.mesh: self.mesh.UnRegister()
1272         self.mesh = theMesh
1273         if self.mesh:
1274             #self.mesh.Register()
1275             self.geom = self.mesh.GetShapeToMesh()
1276         pass
1277
1278     ## Returns the mesh, that is an instance of SMESH_Mesh interface
1279     #  @return a SMESH_Mesh object
1280     #  @ingroup l2_construct
1281     def GetMesh(self):
1282         return self.mesh
1283
1284     ## Gets the name of the mesh
1285     #  @return the name of the mesh as a string
1286     #  @ingroup l2_construct
1287     def GetName(self):
1288         name = GetName(self.GetMesh())
1289         return name
1290
1291     ## Sets a name to the mesh
1292     #  @param name a new name of the mesh
1293     #  @ingroup l2_construct
1294     def SetName(self, name):
1295         self.smeshpyD.SetName(self.GetMesh(), name)
1296
1297     ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1298     #  The subMesh object gives access to the IDs of nodes and elements.
1299     #  @param geom a geometrical object (shape)
1300     #  @param name a name for the submesh
1301     #  @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1302     #  @ingroup l2_submeshes
1303     def GetSubMesh(self, geom, name):
1304         AssureGeomPublished( self, geom, name )
1305         submesh = self.mesh.GetSubMesh( geom, name )
1306         return submesh
1307
1308     ## Returns the shape associated to the mesh
1309     #  @return a GEOM_Object
1310     #  @ingroup l2_construct
1311     def GetShape(self):
1312         return self.geom
1313
1314     ## Associates the given shape to the mesh (entails the recreation of the mesh)
1315     #  @param geom the shape to be meshed (GEOM_Object)
1316     #  @ingroup l2_construct
1317     def SetShape(self, geom):
1318         self.mesh = self.smeshpyD.CreateMesh(geom)
1319
1320     ## Loads mesh from the study after opening the study
1321     def Load(self):
1322         self.mesh.Load()
1323
1324     ## Returns true if the hypotheses are defined well
1325     #  @param theSubObject a sub-shape of a mesh shape
1326     #  @return True or False
1327     #  @ingroup l2_construct
1328     def IsReadyToCompute(self, theSubObject):
1329         return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1330
1331     ## Returns errors of hypotheses definition.
1332     #  The list of errors is empty if everything is OK.
1333     #  @param theSubObject a sub-shape of a mesh shape
1334     #  @return a list of errors
1335     #  @ingroup l2_construct
1336     def GetAlgoState(self, theSubObject):
1337         return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1338
1339     ## Returns a geometrical object on which the given element was built.
1340     #  The returned geometrical object, if not nil, is either found in the
1341     #  study or published by this method with the given name
1342     #  @param theElementID the id of the mesh element
1343     #  @param theGeomName the user-defined name of the geometrical object
1344     #  @return GEOM::GEOM_Object instance
1345     #  @ingroup l2_construct
1346     def GetGeometryByMeshElement(self, theElementID, theGeomName):
1347         return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1348
1349     ## Returns the mesh dimension depending on the dimension of the underlying shape
1350     #  or, if the mesh is not based on any shape, basing on deimension of elements
1351     #  @return mesh dimension as an integer value [0,3]
1352     #  @ingroup l1_auxiliary
1353     def MeshDimension(self):
1354         if self.mesh.HasShapeToMesh():
1355             shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1356             if len( shells ) > 0 :
1357                 return 3
1358             elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1359                 return 2
1360             elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1361                 return 1
1362             else:
1363                 return 0;
1364         else:
1365             if self.NbVolumes() > 0: return 3
1366             if self.NbFaces()   > 0: return 2
1367             if self.NbEdges()   > 0: return 1
1368         return 0
1369
1370     ## Evaluates size of prospective mesh on a shape
1371     #  @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1372     #  To know predicted number of e.g. edges, inquire it this way
1373     #  Evaluate()[ EnumToLong( Entity_Edge )]
1374     def Evaluate(self, geom=0):
1375         if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1376             if self.geom == 0:
1377                 geom = self.mesh.GetShapeToMesh()
1378             else:
1379                 geom = self.geom
1380         return self.smeshpyD.Evaluate(self.mesh, geom)
1381
1382
1383     ## Computes the mesh and returns the status of the computation
1384     #  @param geom geomtrical shape on which mesh data should be computed
1385     #  @param discardModifs if True and the mesh has been edited since
1386     #         a last total re-compute and that may prevent successful partial re-compute,
1387     #         then the mesh is cleaned before Compute()
1388     #  @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1389     #  @return True or False
1390     #  @ingroup l2_construct
1391     def Compute(self, geom=0, discardModifs=False, refresh=False):
1392         if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1393             if self.geom == 0:
1394                 geom = self.mesh.GetShapeToMesh()
1395             else:
1396                 geom = self.geom
1397         ok = False
1398         try:
1399             if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1400                 self.mesh.Clear()
1401             ok = self.smeshpyD.Compute(self.mesh, geom)
1402         except SALOME.SALOME_Exception, ex:
1403             print "Mesh computation failed, exception caught:"
1404             print "    ", ex.details.text
1405         except:
1406             import traceback
1407             print "Mesh computation failed, exception caught:"
1408             traceback.print_exc()
1409         if True:#not ok:
1410             allReasons = ""
1411
1412             # Treat compute errors
1413             computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1414             for err in computeErrors:
1415                 shapeText = ""
1416                 if self.mesh.HasShapeToMesh():
1417                     try:
1418                         mainIOR  = salome.orb.object_to_string(geom)
1419                         for sname in salome.myStudyManager.GetOpenStudies():
1420                             s = salome.myStudyManager.GetStudyByName(sname)
1421                             if not s: continue
1422                             mainSO = s.FindObjectIOR(mainIOR)
1423                             if not mainSO: continue
1424                             if err.subShapeID == 1:
1425                                 shapeText = ' on "%s"' % mainSO.GetName()
1426                             subIt = s.NewChildIterator(mainSO)
1427                             while subIt.More():
1428                                 subSO = subIt.Value()
1429                                 subIt.Next()
1430                                 obj = subSO.GetObject()
1431                                 if not obj: continue
1432                                 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1433                                 if not go: continue
1434                                 ids = go.GetSubShapeIndices()
1435                                 if len(ids) == 1 and ids[0] == err.subShapeID:
1436                                     shapeText = ' on "%s"' % subSO.GetName()
1437                                     break
1438                         if not shapeText:
1439                             shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1440                             if shape:
1441                                 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1442                             else:
1443                                 shapeText = " on subshape #%s" % (err.subShapeID)
1444                     except:
1445                         shapeText = " on subshape #%s" % (err.subShapeID)
1446                 errText = ""
1447                 stdErrors = ["OK",                   #COMPERR_OK
1448                              "Invalid input mesh",   #COMPERR_BAD_INPUT_MESH
1449                              "std::exception",       #COMPERR_STD_EXCEPTION
1450                              "OCC exception",        #COMPERR_OCC_EXCEPTION
1451                              "..",                   #COMPERR_SLM_EXCEPTION
1452                              "Unknown exception",    #COMPERR_EXCEPTION
1453                              "Memory allocation problem", #COMPERR_MEMORY_PB
1454                              "Algorithm failed",     #COMPERR_ALGO_FAILED
1455                              "Unexpected geometry",  #COMPERR_BAD_SHAPE
1456                              "Warning",              #COMPERR_WARNING
1457                              "Computation cancelled",#COMPERR_CANCELED
1458                              "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1459                 if err.code > 0:
1460                     if err.code < len(stdErrors): errText = stdErrors[err.code]
1461                 else:
1462                     errText = "code %s" % -err.code
1463                 if errText: errText += ". "
1464                 errText += err.comment
1465                 if allReasons != "":allReasons += "\n"
1466                 if ok:
1467                     allReasons += '-  "%s"%s - %s' %(err.algoName, shapeText, errText)
1468                 else:
1469                     allReasons += '-  "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1470                 pass
1471
1472             # Treat hyp errors
1473             errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1474             for err in errors:
1475                 if err.isGlobalAlgo:
1476                     glob = "global"
1477                 else:
1478                     glob = "local"
1479                     pass
1480                 dim = err.algoDim
1481                 name = err.algoName
1482                 if len(name) == 0:
1483                     reason = '%s %sD algorithm is missing' % (glob, dim)
1484                 elif err.state == HYP_MISSING:
1485                     reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1486                               % (glob, dim, name, dim))
1487                 elif err.state == HYP_NOTCONFORM:
1488                     reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1489                 elif err.state == HYP_BAD_PARAMETER:
1490                     reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1491                               % ( glob, dim, name ))
1492                 elif err.state == HYP_BAD_GEOMETRY:
1493                     reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1494                               'geometry' % ( glob, dim, name ))
1495                 elif err.state == HYP_HIDDEN_ALGO:
1496                     reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1497                               'algorithm of upper dimension generating %sD mesh'
1498                               % ( glob, dim, name, glob, dim ))
1499                 else:
1500                     reason = ("For unknown reason. "
1501                               "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1502                     pass
1503                 if allReasons != "":allReasons += "\n"
1504                 allReasons += "-  " + reason
1505                 pass
1506             if not ok or allReasons != "":
1507                 msg = '"' + GetName(self.mesh) + '"'
1508                 if ok: msg += " has been computed with warnings"
1509                 else:  msg += " has not been computed"
1510                 if allReasons != "": msg += ":"
1511                 else:                msg += "."
1512                 print msg
1513                 print allReasons
1514             pass
1515         if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1516             smeshgui = salome.ImportComponentGUI("SMESH")
1517             smeshgui.Init(self.mesh.GetStudyId())
1518             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1519             if refresh: salome.sg.updateObjBrowser(1)
1520             pass
1521         return ok
1522
1523     ## Return submesh objects list in meshing order
1524     #  @return list of list of submesh objects
1525     #  @ingroup l2_construct
1526     def GetMeshOrder(self):
1527         return self.mesh.GetMeshOrder()
1528
1529     ## Return submesh objects list in meshing order
1530     #  @return list of list of submesh objects
1531     #  @ingroup l2_construct
1532     def SetMeshOrder(self, submeshes):
1533         return self.mesh.SetMeshOrder(submeshes)
1534
1535     ## Removes all nodes and elements
1536     #  @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1537     #  @ingroup l2_construct
1538     def Clear(self, refresh=False):
1539         self.mesh.Clear()
1540         if ( salome.sg.hasDesktop() and 
1541              salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1542             smeshgui = salome.ImportComponentGUI("SMESH")
1543             smeshgui.Init(self.mesh.GetStudyId())
1544             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1545             if refresh: salome.sg.updateObjBrowser(1)
1546
1547     ## Removes all nodes and elements of indicated shape
1548     #  @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1549     #  @param geomId the ID of a sub-shape to remove elements on
1550     #  @ingroup l2_construct
1551     def ClearSubMesh(self, geomId, refresh=False):
1552         self.mesh.ClearSubMesh(geomId)
1553         if salome.sg.hasDesktop():
1554             smeshgui = salome.ImportComponentGUI("SMESH")
1555             smeshgui.Init(self.mesh.GetStudyId())
1556             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1557             if refresh: salome.sg.updateObjBrowser(1)
1558
1559     ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1560     #  @param fineness [0.0,1.0] defines mesh fineness
1561     #  @return True or False
1562     #  @ingroup l3_algos_basic
1563     def AutomaticTetrahedralization(self, fineness=0):
1564         dim = self.MeshDimension()
1565         # assign hypotheses
1566         self.RemoveGlobalHypotheses()
1567         self.Segment().AutomaticLength(fineness)
1568         if dim > 1 :
1569             self.Triangle().LengthFromEdges()
1570             pass
1571         if dim > 2 :
1572             self.Tetrahedron()
1573             pass
1574         return self.Compute()
1575
1576     ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1577     #  @param fineness [0.0, 1.0] defines mesh fineness
1578     #  @return True or False
1579     #  @ingroup l3_algos_basic
1580     def AutomaticHexahedralization(self, fineness=0):
1581         dim = self.MeshDimension()
1582         # assign the hypotheses
1583         self.RemoveGlobalHypotheses()
1584         self.Segment().AutomaticLength(fineness)
1585         if dim > 1 :
1586             self.Quadrangle()
1587             pass
1588         if dim > 2 :
1589             self.Hexahedron()
1590             pass
1591         return self.Compute()
1592
1593     ## Assigns a hypothesis
1594     #  @param hyp a hypothesis to assign
1595     #  @param geom a subhape of mesh geometry
1596     #  @return SMESH.Hypothesis_Status
1597     #  @ingroup l2_hypotheses
1598     def AddHypothesis(self, hyp, geom=0):
1599         if isinstance( hyp, Mesh_Algorithm ):
1600             hyp = hyp.GetAlgorithm()
1601             pass
1602         if not geom:
1603             geom = self.geom
1604             if not geom:
1605                 geom = self.mesh.GetShapeToMesh()
1606             pass
1607         isApplicable = True
1608         if self.mesh.HasShapeToMesh():
1609             hyp_type     = hyp.GetName()
1610             lib_name     = hyp.GetLibName()
1611             checkAll    = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1612             if checkAll and geom:
1613                 checkAll = geom.GetType() == 37
1614             isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1615         if isApplicable:
1616             AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1617             status = self.mesh.AddHypothesis(geom, hyp)
1618         else:
1619             status = HYP_BAD_GEOMETRY,""
1620         hyp_name = GetName( hyp )
1621         geom_name = ""
1622         if geom:
1623             geom_name = geom.GetName()
1624         isAlgo = hyp._narrow( SMESH_Algo )
1625         TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1626         return status
1627
1628     ## Return True if an algorithm of hypothesis is assigned to a given shape
1629     #  @param hyp a hypothesis to check
1630     #  @param geom a subhape of mesh geometry
1631     #  @return True of False
1632     #  @ingroup l2_hypotheses
1633     def IsUsedHypothesis(self, hyp, geom):
1634         if not hyp: # or not geom
1635             return False
1636         if isinstance( hyp, Mesh_Algorithm ):
1637             hyp = hyp.GetAlgorithm()
1638             pass
1639         hyps = self.GetHypothesisList(geom)
1640         for h in hyps:
1641             if h.GetId() == hyp.GetId():
1642                 return True
1643         return False
1644
1645     ## Unassigns a hypothesis
1646     #  @param hyp a hypothesis to unassign
1647     #  @param geom a sub-shape of mesh geometry
1648     #  @return SMESH.Hypothesis_Status
1649     #  @ingroup l2_hypotheses
1650     def RemoveHypothesis(self, hyp, geom=0):
1651         if not hyp:
1652             return None
1653         if isinstance( hyp, Mesh_Algorithm ):
1654             hyp = hyp.GetAlgorithm()
1655             pass
1656         shape = geom
1657         if not shape:
1658             shape = self.geom
1659             pass
1660         if self.IsUsedHypothesis( hyp, shape ):
1661             return self.mesh.RemoveHypothesis( shape, hyp )
1662         hypName = GetName( hyp )
1663         geoName = GetName( shape )
1664         print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1665         return None
1666
1667     ## Gets the list of hypotheses added on a geometry
1668     #  @param geom a sub-shape of mesh geometry
1669     #  @return the sequence of SMESH_Hypothesis
1670     #  @ingroup l2_hypotheses
1671     def GetHypothesisList(self, geom):
1672         return self.mesh.GetHypothesisList( geom )
1673
1674     ## Removes all global hypotheses
1675     #  @ingroup l2_hypotheses
1676     def RemoveGlobalHypotheses(self):
1677         current_hyps = self.mesh.GetHypothesisList( self.geom )
1678         for hyp in current_hyps:
1679             self.mesh.RemoveHypothesis( self.geom, hyp )
1680             pass
1681         pass
1682
1683    ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1684     ## allowing to overwrite the file if it exists or add the exported data to its contents
1685     #  @param f is the file name
1686     #  @param auto_groups boolean parameter for creating/not creating
1687     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1688     #  the typical use is auto_groups=false.
1689     #  @param version MED format version(MED_V2_1 or MED_V2_2)
1690     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1691     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1692     #  @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1693     #         - 1D if all mesh nodes lie on OX coordinate axis, or
1694     #         - 2D if all mesh nodes lie on XOY coordinate plane, or
1695     #         - 3D in the rest cases.
1696     #         If @a autoDimension is @c False, the space dimension is always 3.
1697     #  @param fields : list of GEOM fields defined on the shape to mesh.
1698     #  @param geomAssocFields : each character of this string means a need to export a 
1699     #         corresponding field; correspondence between fields and characters is following:
1700     #         - 'v' stands for _vertices_ field;
1701     #         - 'e' stands for _edges_ field;
1702     #         - 'f' stands for _faces_ field;
1703     #         - 's' stands for _solids_ field.
1704     #  @ingroup l2_impexp
1705     def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1706                   overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1707         if meshPart or fields or geomAssocFields:
1708             unRegister = genObjUnRegister()
1709             if isinstance( meshPart, list ):
1710                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1711                 unRegister.set( meshPart )
1712             self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1713                                        fields, geomAssocFields)
1714         else:
1715             self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1716
1717     ## Exports the mesh in a file in SAUV format
1718     #  @param f is the file name
1719     #  @param auto_groups boolean parameter for creating/not creating
1720     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1721     #  the typical use is auto_groups=false.
1722     #  @ingroup l2_impexp
1723     def ExportSAUV(self, f, auto_groups=0):
1724         self.mesh.ExportSAUV(f, auto_groups)
1725
1726     ## Exports the mesh in a file in DAT format
1727     #  @param f the file name
1728     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1729     #  @ingroup l2_impexp
1730     def ExportDAT(self, f, meshPart=None):
1731         if meshPart:
1732             unRegister = genObjUnRegister()
1733             if isinstance( meshPart, list ):
1734                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1735                 unRegister.set( meshPart )
1736             self.mesh.ExportPartToDAT( meshPart, f )
1737         else:
1738             self.mesh.ExportDAT(f)
1739
1740     ## Exports the mesh in a file in UNV format
1741     #  @param f the file name
1742     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1743     #  @ingroup l2_impexp
1744     def ExportUNV(self, f, meshPart=None):
1745         if meshPart:
1746             unRegister = genObjUnRegister()
1747             if isinstance( meshPart, list ):
1748                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1749                 unRegister.set( meshPart )
1750             self.mesh.ExportPartToUNV( meshPart, f )
1751         else:
1752             self.mesh.ExportUNV(f)
1753
1754     ## Export the mesh in a file in STL format
1755     #  @param f the file name
1756     #  @param ascii defines the file encoding
1757     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1758     #  @ingroup l2_impexp
1759     def ExportSTL(self, f, ascii=1, meshPart=None):
1760         if meshPart:
1761             unRegister = genObjUnRegister()
1762             if isinstance( meshPart, list ):
1763                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1764                 unRegister.set( meshPart )
1765             self.mesh.ExportPartToSTL( meshPart, f, ascii )
1766         else:
1767             self.mesh.ExportSTL(f, ascii)
1768
1769     ## Exports the mesh in a file in CGNS format
1770     #  @param f is the file name
1771     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1772     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1773     #  @ingroup l2_impexp
1774     def ExportCGNS(self, f, overwrite=1, meshPart=None):
1775         unRegister = genObjUnRegister()
1776         if isinstance( meshPart, list ):
1777             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1778             unRegister.set( meshPart )
1779         if isinstance( meshPart, Mesh ):
1780             meshPart = meshPart.mesh
1781         elif not meshPart:
1782             meshPart = self.mesh
1783         self.mesh.ExportCGNS(meshPart, f, overwrite)
1784
1785     ## Exports the mesh in a file in GMF format.
1786     #  GMF files must have .mesh extension for the ASCII format and .meshb for
1787     #  the bynary format. Other extensions are not allowed.
1788     #  @param f is the file name
1789     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1790     #  @ingroup l2_impexp
1791     def ExportGMF(self, f, meshPart=None):
1792         unRegister = genObjUnRegister()
1793         if isinstance( meshPart, list ):
1794             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1795             unRegister.set( meshPart )
1796         if isinstance( meshPart, Mesh ):
1797             meshPart = meshPart.mesh
1798         elif not meshPart:
1799             meshPart = self.mesh
1800         self.mesh.ExportGMF(meshPart, f, True)
1801
1802     ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1803     #  Exports the mesh in a file in MED format and chooses the \a version of MED format
1804     ## allowing to overwrite the file if it exists or add the exported data to its contents
1805     #  @param f the file name
1806     #  @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1807     #  @param opt boolean parameter for creating/not creating
1808     #         the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1809     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1810     #  @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1811     #         - 1D if all mesh nodes lie on OX coordinate axis, or
1812     #         - 2D if all mesh nodes lie on XOY coordinate plane, or
1813     #         - 3D in the rest cases.
1814     #
1815     #         If @a autoDimension is @c False, the space dimension is always 3.
1816     #  @ingroup l2_impexp
1817     def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1818         self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1819
1820     # Operations with groups:
1821     # ----------------------
1822
1823     ## Creates an empty mesh group
1824     #  @param elementType the type of elements in the group
1825     #  @param name the name of the mesh group
1826     #  @return SMESH_Group
1827     #  @ingroup l2_grps_create
1828     def CreateEmptyGroup(self, elementType, name):
1829         return self.mesh.CreateGroup(elementType, name)
1830
1831     ## Creates a mesh group based on the geometric object \a grp
1832     #  and gives a \a name, \n if this parameter is not defined
1833     #  the name is the same as the geometric group name \n
1834     #  Note: Works like GroupOnGeom().
1835     #  @param grp  a geometric group, a vertex, an edge, a face or a solid
1836     #  @param name the name of the mesh group
1837     #  @return SMESH_GroupOnGeom
1838     #  @ingroup l2_grps_create
1839     def Group(self, grp, name=""):
1840         return self.GroupOnGeom(grp, name)
1841
1842     ## Creates a mesh group based on the geometrical object \a grp
1843     #  and gives a \a name, \n if this parameter is not defined
1844     #  the name is the same as the geometrical group name
1845     #  @param grp  a geometrical group, a vertex, an edge, a face or a solid
1846     #  @param name the name of the mesh group
1847     #  @param typ  the type of elements in the group. If not set, it is
1848     #              automatically detected by the type of the geometry
1849     #  @return SMESH_GroupOnGeom
1850     #  @ingroup l2_grps_create
1851     def GroupOnGeom(self, grp, name="", typ=None):
1852         AssureGeomPublished( self, grp, name )
1853         if name == "":
1854             name = grp.GetName()
1855         if not typ:
1856             typ = self._groupTypeFromShape( grp )
1857         return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1858
1859     ## Pivate method to get a type of group on geometry
1860     def _groupTypeFromShape( self, shape ):
1861         tgeo = str(shape.GetShapeType())
1862         if tgeo == "VERTEX":
1863             typ = NODE
1864         elif tgeo == "EDGE":
1865             typ = EDGE
1866         elif tgeo == "FACE" or tgeo == "SHELL":
1867             typ = FACE
1868         elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1869             typ = VOLUME
1870         elif tgeo == "COMPOUND":
1871             sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1872             if not sub:
1873                 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1874             return self._groupTypeFromShape( sub[0] )
1875         else:
1876             raise ValueError, \
1877                   "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1878         return typ
1879
1880     ## Creates a mesh group with given \a name based on the \a filter which
1881     ## is a special type of group dynamically updating it's contents during
1882     ## mesh modification
1883     #  @param typ  the type of elements in the group
1884     #  @param name the name of the mesh group
1885     #  @param filter the filter defining group contents
1886     #  @return SMESH_GroupOnFilter
1887     #  @ingroup l2_grps_create
1888     def GroupOnFilter(self, typ, name, filter):
1889         return self.mesh.CreateGroupFromFilter(typ, name, filter)
1890
1891     ## Creates a mesh group by the given ids of elements
1892     #  @param groupName the name of the mesh group
1893     #  @param elementType the type of elements in the group
1894     #  @param elemIDs the list of ids
1895     #  @return SMESH_Group
1896     #  @ingroup l2_grps_create
1897     def MakeGroupByIds(self, groupName, elementType, elemIDs):
1898         group = self.mesh.CreateGroup(elementType, groupName)
1899         if hasattr( elemIDs, "GetIDs" ):
1900             if hasattr( elemIDs, "SetMesh" ):
1901                 elemIDs.SetMesh( self.GetMesh() )
1902             group.AddFrom( elemIDs )
1903         else:
1904             group.Add(elemIDs)
1905         return group
1906
1907     ## Creates a mesh group by the given conditions
1908     #  @param groupName the name of the mesh group
1909     #  @param elementType the type of elements in the group
1910     #  @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1911     #  @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1912     #  @param Threshold the threshold value (range of id ids as string, shape, numeric)
1913     #  @param UnaryOp FT_LogicalNOT or FT_Undefined
1914     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1915     #         FT_LyingOnGeom, FT_CoplanarFaces criteria
1916     #  @return SMESH_GroupOnFilter
1917     #  @ingroup l2_grps_create
1918     def MakeGroup(self,
1919                   groupName,
1920                   elementType,
1921                   CritType=FT_Undefined,
1922                   Compare=FT_EqualTo,
1923                   Threshold="",
1924                   UnaryOp=FT_Undefined,
1925                   Tolerance=1e-07):
1926         aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1927         group = self.MakeGroupByCriterion(groupName, aCriterion)
1928         return group
1929
1930     ## Creates a mesh group by the given criterion
1931     #  @param groupName the name of the mesh group
1932     #  @param Criterion the instance of Criterion class
1933     #  @return SMESH_GroupOnFilter
1934     #  @ingroup l2_grps_create
1935     def MakeGroupByCriterion(self, groupName, Criterion):
1936         return self.MakeGroupByCriteria( groupName, [Criterion] )
1937
1938     ## Creates a mesh group by the given criteria (list of criteria)
1939     #  @param groupName the name of the mesh group
1940     #  @param theCriteria the list of criteria
1941     #  @param binOp binary operator used when binary operator of criteria is undefined
1942     #  @return SMESH_GroupOnFilter
1943     #  @ingroup l2_grps_create
1944     def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
1945         aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
1946         group = self.MakeGroupByFilter(groupName, aFilter)
1947         return group
1948
1949     ## Creates a mesh group by the given filter
1950     #  @param groupName the name of the mesh group
1951     #  @param theFilter the instance of Filter class
1952     #  @return SMESH_GroupOnFilter
1953     #  @ingroup l2_grps_create
1954     def MakeGroupByFilter(self, groupName, theFilter):
1955         #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1956         #theFilter.SetMesh( self.mesh )
1957         #group.AddFrom( theFilter )
1958         group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
1959         return group
1960
1961     ## Removes a group
1962     #  @ingroup l2_grps_delete
1963     def RemoveGroup(self, group):
1964         self.mesh.RemoveGroup(group)
1965
1966     ## Removes a group with its contents
1967     #  @ingroup l2_grps_delete
1968     def RemoveGroupWithContents(self, group):
1969         self.mesh.RemoveGroupWithContents(group)
1970
1971     ## Gets the list of groups existing in the mesh in the order
1972     #  of creation (starting from the oldest one)
1973     #  @return a sequence of SMESH_GroupBase
1974     #  @ingroup l2_grps_create
1975     def GetGroups(self):
1976         return self.mesh.GetGroups()
1977
1978     ## Gets the number of groups existing in the mesh
1979     #  @return the quantity of groups as an integer value
1980     #  @ingroup l2_grps_create
1981     def NbGroups(self):
1982         return self.mesh.NbGroups()
1983
1984     ## Gets the list of names of groups existing in the mesh
1985     #  @return list of strings
1986     #  @ingroup l2_grps_create
1987     def GetGroupNames(self):
1988         groups = self.GetGroups()
1989         names = []
1990         for group in groups:
1991             names.append(group.GetName())
1992         return names
1993
1994     ## Produces a union of two groups.
1995     #  A new group is created. All mesh elements that are
1996     #  present in the initial groups are added to the new one
1997     #  @return an instance of SMESH_Group
1998     #  @ingroup l2_grps_operon
1999     def UnionGroups(self, group1, group2, name):
2000         return self.mesh.UnionGroups(group1, group2, name)
2001
2002     ## Produces a union list of groups.
2003     #  New group is created. All mesh elements that are present in
2004     #  initial groups are added to the new one
2005     #  @return an instance of SMESH_Group
2006     #  @ingroup l2_grps_operon
2007     def UnionListOfGroups(self, groups, name):
2008       return self.mesh.UnionListOfGroups(groups, name)
2009
2010     ## Prodices an intersection of two groups.
2011     #  A new group is created. All mesh elements that are common
2012     #  for the two initial groups are added to the new one.
2013     #  @return an instance of SMESH_Group
2014     #  @ingroup l2_grps_operon
2015     def IntersectGroups(self, group1, group2, name):
2016         return self.mesh.IntersectGroups(group1, group2, name)
2017
2018     ## Produces an intersection of groups.
2019     #  New group is created. All mesh elements that are present in all
2020     #  initial groups simultaneously are added to the new one
2021     #  @return an instance of SMESH_Group
2022     #  @ingroup l2_grps_operon
2023     def IntersectListOfGroups(self, groups, name):
2024       return self.mesh.IntersectListOfGroups(groups, name)
2025
2026     ## Produces a cut of two groups.
2027     #  A new group is created. All mesh elements that are present in
2028     #  the main group but are not present in the tool group are added to the new one
2029     #  @return an instance of SMESH_Group
2030     #  @ingroup l2_grps_operon
2031     def CutGroups(self, main_group, tool_group, name):
2032         return self.mesh.CutGroups(main_group, tool_group, name)
2033
2034     ## Produces a cut of groups.
2035     #  A new group is created. All mesh elements that are present in main groups
2036     #  but do not present in tool groups are added to the new one
2037     #  @return an instance of SMESH_Group
2038     #  @ingroup l2_grps_operon
2039     def CutListOfGroups(self, main_groups, tool_groups, name):
2040         return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2041
2042     ##
2043     #  Create a standalone group of entities basing on nodes of other groups.
2044     #  \param groups - list of groups, sub-meshes or filters, of any type.
2045     #  \param elemType - a type of elements to include to the new group.
2046     #  \param name - a name of the new group.
2047     #  \param nbCommonNodes - a criterion of inclusion of an element to the new group
2048     #         basing on number of element nodes common with reference \a groups.
2049     #         Meaning of possible values are:
2050     #         - SMESH.ALL_NODES - include if all nodes are common,
2051     #         - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2052     #         - SMESH.AT_LEAST_ONE - include if one or more node is common,
2053     #         - SMEHS.MAJORITY - include if half of nodes or more are common.
2054     #  \param underlyingOnly - if \c True (default), an element is included to the
2055     #         new group provided that it is based on nodes of one element of \a groups.
2056     #  @return an instance of SMESH_Group
2057     #  @ingroup l2_grps_operon
2058     def CreateDimGroup(self, groups, elemType, name,
2059                        nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2060         if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2061             groups = [groups]
2062         return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2063
2064
2065     ## Convert group on geom into standalone group
2066     #  @ingroup l2_grps_delete
2067     def ConvertToStandalone(self, group):
2068         return self.mesh.ConvertToStandalone(group)
2069
2070     # Get some info about mesh:
2071     # ------------------------
2072
2073     ## Returns the log of nodes and elements added or removed
2074     #  since the previous clear of the log.
2075     #  @param clearAfterGet log is emptied after Get (safe if concurrents access)
2076     #  @return list of log_block structures:
2077     #                                        commandType
2078     #                                        number
2079     #                                        coords
2080     #                                        indexes
2081     #  @ingroup l1_auxiliary
2082     def GetLog(self, clearAfterGet):
2083         return self.mesh.GetLog(clearAfterGet)
2084
2085     ## Clears the log of nodes and elements added or removed since the previous
2086     #  clear. Must be used immediately after GetLog if clearAfterGet is false.
2087     #  @ingroup l1_auxiliary
2088     def ClearLog(self):
2089         self.mesh.ClearLog()
2090
2091     ## Toggles auto color mode on the object.
2092     #  @param theAutoColor the flag which toggles auto color mode.
2093     #  @ingroup l1_auxiliary
2094     def SetAutoColor(self, theAutoColor):
2095         self.mesh.SetAutoColor(theAutoColor)
2096
2097     ## Gets flag of object auto color mode.
2098     #  @return True or False
2099     #  @ingroup l1_auxiliary
2100     def GetAutoColor(self):
2101         return self.mesh.GetAutoColor()
2102
2103     ## Gets the internal ID
2104     #  @return integer value, which is the internal Id of the mesh
2105     #  @ingroup l1_auxiliary
2106     def GetId(self):
2107         return self.mesh.GetId()
2108
2109     ## Get the study Id
2110     #  @return integer value, which is the study Id of the mesh
2111     #  @ingroup l1_auxiliary
2112     def GetStudyId(self):
2113         return self.mesh.GetStudyId()
2114
2115     ## Checks the group names for duplications.
2116     #  Consider the maximum group name length stored in MED file.
2117     #  @return True or False
2118     #  @ingroup l1_auxiliary
2119     def HasDuplicatedGroupNamesMED(self):
2120         return self.mesh.HasDuplicatedGroupNamesMED()
2121
2122     ## Obtains the mesh editor tool
2123     #  @return an instance of SMESH_MeshEditor
2124     #  @ingroup l1_modifying
2125     def GetMeshEditor(self):
2126         return self.editor
2127
2128     ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2129     #  can be passed as argument to a method accepting mesh, group or sub-mesh
2130     #  @return an instance of SMESH_IDSource
2131     #  @ingroup l1_auxiliary
2132     def GetIDSource(self, ids, elemType):
2133         return self.editor.MakeIDSource(ids, elemType)
2134
2135
2136     # Get informations about mesh contents:
2137     # ------------------------------------
2138
2139     ## Gets the mesh stattistic
2140     #  @return dictionary type element - count of elements
2141     #  @ingroup l1_meshinfo
2142     def GetMeshInfo(self, obj = None):
2143         if not obj: obj = self.mesh
2144         return self.smeshpyD.GetMeshInfo(obj)
2145
2146     ## Returns the number of nodes in the mesh
2147     #  @return an integer value
2148     #  @ingroup l1_meshinfo
2149     def NbNodes(self):
2150         return self.mesh.NbNodes()
2151
2152     ## Returns the number of elements in the mesh
2153     #  @return an integer value
2154     #  @ingroup l1_meshinfo
2155     def NbElements(self):
2156         return self.mesh.NbElements()
2157
2158     ## Returns the number of 0d elements in the mesh
2159     #  @return an integer value
2160     #  @ingroup l1_meshinfo
2161     def Nb0DElements(self):
2162         return self.mesh.Nb0DElements()
2163
2164     ## Returns the number of ball discrete elements in the mesh
2165     #  @return an integer value
2166     #  @ingroup l1_meshinfo
2167     def NbBalls(self):
2168         return self.mesh.NbBalls()
2169
2170     ## Returns the number of edges in the mesh
2171     #  @return an integer value
2172     #  @ingroup l1_meshinfo
2173     def NbEdges(self):
2174         return self.mesh.NbEdges()
2175
2176     ## Returns the number of edges with the given order in the mesh
2177     #  @param elementOrder the order of elements:
2178     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2179     #  @return an integer value
2180     #  @ingroup l1_meshinfo
2181     def NbEdgesOfOrder(self, elementOrder):
2182         return self.mesh.NbEdgesOfOrder(elementOrder)
2183
2184     ## Returns the number of faces in the mesh
2185     #  @return an integer value
2186     #  @ingroup l1_meshinfo
2187     def NbFaces(self):
2188         return self.mesh.NbFaces()
2189
2190     ## Returns the number of faces with the given order in the mesh
2191     #  @param elementOrder the order of elements:
2192     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2193     #  @return an integer value
2194     #  @ingroup l1_meshinfo
2195     def NbFacesOfOrder(self, elementOrder):
2196         return self.mesh.NbFacesOfOrder(elementOrder)
2197
2198     ## Returns the number of triangles in the mesh
2199     #  @return an integer value
2200     #  @ingroup l1_meshinfo
2201     def NbTriangles(self):
2202         return self.mesh.NbTriangles()
2203
2204     ## Returns the number of triangles with the given order in the mesh
2205     #  @param elementOrder is the order of elements:
2206     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2207     #  @return an integer value
2208     #  @ingroup l1_meshinfo
2209     def NbTrianglesOfOrder(self, elementOrder):
2210         return self.mesh.NbTrianglesOfOrder(elementOrder)
2211
2212     ## Returns the number of biquadratic triangles in the mesh
2213     #  @return an integer value
2214     #  @ingroup l1_meshinfo
2215     def NbBiQuadTriangles(self):
2216         return self.mesh.NbBiQuadTriangles()
2217
2218     ## Returns the number of quadrangles in the mesh
2219     #  @return an integer value
2220     #  @ingroup l1_meshinfo
2221     def NbQuadrangles(self):
2222         return self.mesh.NbQuadrangles()
2223
2224     ## Returns the number of quadrangles with the given order in the mesh
2225     #  @param elementOrder the order of elements:
2226     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2227     #  @return an integer value
2228     #  @ingroup l1_meshinfo
2229     def NbQuadranglesOfOrder(self, elementOrder):
2230         return self.mesh.NbQuadranglesOfOrder(elementOrder)
2231
2232     ## Returns the number of biquadratic quadrangles in the mesh
2233     #  @return an integer value
2234     #  @ingroup l1_meshinfo
2235     def NbBiQuadQuadrangles(self):
2236         return self.mesh.NbBiQuadQuadrangles()
2237
2238     ## Returns the number of polygons in the mesh
2239     #  @return an integer value
2240     #  @ingroup l1_meshinfo
2241     def NbPolygons(self):
2242         return self.mesh.NbPolygons()
2243
2244     ## Returns the number of volumes in the mesh
2245     #  @return an integer value
2246     #  @ingroup l1_meshinfo
2247     def NbVolumes(self):
2248         return self.mesh.NbVolumes()
2249
2250     ## Returns the number of volumes with the given order in the mesh
2251     #  @param elementOrder  the order of elements:
2252     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2253     #  @return an integer value
2254     #  @ingroup l1_meshinfo
2255     def NbVolumesOfOrder(self, elementOrder):
2256         return self.mesh.NbVolumesOfOrder(elementOrder)
2257
2258     ## Returns the number of tetrahedrons in the mesh
2259     #  @return an integer value
2260     #  @ingroup l1_meshinfo
2261     def NbTetras(self):
2262         return self.mesh.NbTetras()
2263
2264     ## Returns the number of tetrahedrons with the given order in the mesh
2265     #  @param elementOrder  the order of elements:
2266     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2267     #  @return an integer value
2268     #  @ingroup l1_meshinfo
2269     def NbTetrasOfOrder(self, elementOrder):
2270         return self.mesh.NbTetrasOfOrder(elementOrder)
2271
2272     ## Returns the number of hexahedrons in the mesh
2273     #  @return an integer value
2274     #  @ingroup l1_meshinfo
2275     def NbHexas(self):
2276         return self.mesh.NbHexas()
2277
2278     ## Returns the number of hexahedrons with the given order in the mesh
2279     #  @param elementOrder  the order of elements:
2280     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2281     #  @return an integer value
2282     #  @ingroup l1_meshinfo
2283     def NbHexasOfOrder(self, elementOrder):
2284         return self.mesh.NbHexasOfOrder(elementOrder)
2285
2286     ## Returns the number of triquadratic hexahedrons in the mesh
2287     #  @return an integer value
2288     #  @ingroup l1_meshinfo
2289     def NbTriQuadraticHexas(self):
2290         return self.mesh.NbTriQuadraticHexas()
2291
2292     ## Returns the number of pyramids in the mesh
2293     #  @return an integer value
2294     #  @ingroup l1_meshinfo
2295     def NbPyramids(self):
2296         return self.mesh.NbPyramids()
2297
2298     ## Returns the number of pyramids with the given order in the mesh
2299     #  @param elementOrder  the order of elements:
2300     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2301     #  @return an integer value
2302     #  @ingroup l1_meshinfo
2303     def NbPyramidsOfOrder(self, elementOrder):
2304         return self.mesh.NbPyramidsOfOrder(elementOrder)
2305
2306     ## Returns the number of prisms in the mesh
2307     #  @return an integer value
2308     #  @ingroup l1_meshinfo
2309     def NbPrisms(self):
2310         return self.mesh.NbPrisms()
2311
2312     ## Returns the number of prisms with the given order in the mesh
2313     #  @param elementOrder  the order of elements:
2314     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2315     #  @return an integer value
2316     #  @ingroup l1_meshinfo
2317     def NbPrismsOfOrder(self, elementOrder):
2318         return self.mesh.NbPrismsOfOrder(elementOrder)
2319
2320     ## Returns the number of hexagonal prisms in the mesh
2321     #  @return an integer value
2322     #  @ingroup l1_meshinfo
2323     def NbHexagonalPrisms(self):
2324         return self.mesh.NbHexagonalPrisms()
2325
2326     ## Returns the number of polyhedrons in the mesh
2327     #  @return an integer value
2328     #  @ingroup l1_meshinfo
2329     def NbPolyhedrons(self):
2330         return self.mesh.NbPolyhedrons()
2331
2332     ## Returns the number of submeshes in the mesh
2333     #  @return an integer value
2334     #  @ingroup l1_meshinfo
2335     def NbSubMesh(self):
2336         return self.mesh.NbSubMesh()
2337
2338     ## Returns the list of mesh elements IDs
2339     #  @return the list of integer values
2340     #  @ingroup l1_meshinfo
2341     def GetElementsId(self):
2342         return self.mesh.GetElementsId()
2343
2344     ## Returns the list of IDs of mesh elements with the given type
2345     #  @param elementType  the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2346     #  @return list of integer values
2347     #  @ingroup l1_meshinfo
2348     def GetElementsByType(self, elementType):
2349         return self.mesh.GetElementsByType(elementType)
2350
2351     ## Returns the list of mesh nodes IDs
2352     #  @return the list of integer values
2353     #  @ingroup l1_meshinfo
2354     def GetNodesId(self):
2355         return self.mesh.GetNodesId()
2356
2357     # Get the information about mesh elements:
2358     # ------------------------------------
2359
2360     ## Returns the type of mesh element
2361     #  @return the value from SMESH::ElementType enumeration
2362     #  @ingroup l1_meshinfo
2363     def GetElementType(self, id, iselem):
2364         return self.mesh.GetElementType(id, iselem)
2365
2366     ## Returns the geometric type of mesh element
2367     #  @return the value from SMESH::EntityType enumeration
2368     #  @ingroup l1_meshinfo
2369     def GetElementGeomType(self, id):
2370         return self.mesh.GetElementGeomType(id)
2371
2372     ## Returns the shape type of mesh element
2373     #  @return the value from SMESH::GeometryType enumeration
2374     #  @ingroup l1_meshinfo
2375     def GetElementShape(self, id):
2376         return self.mesh.GetElementShape(id)
2377
2378     ## Returns the list of submesh elements IDs
2379     #  @param Shape a geom object(sub-shape) IOR
2380     #         Shape must be the sub-shape of a ShapeToMesh()
2381     #  @return the list of integer values
2382     #  @ingroup l1_meshinfo
2383     def GetSubMeshElementsId(self, Shape):
2384         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2385             ShapeID = Shape.GetSubShapeIndices()[0]
2386         else:
2387             ShapeID = Shape
2388         return self.mesh.GetSubMeshElementsId(ShapeID)
2389
2390     ## Returns the list of submesh nodes IDs
2391     #  @param Shape a geom object(sub-shape) IOR
2392     #         Shape must be the sub-shape of a ShapeToMesh()
2393     #  @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2394     #  @return the list of integer values
2395     #  @ingroup l1_meshinfo
2396     def GetSubMeshNodesId(self, Shape, all):
2397         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2398             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2399         else:
2400             ShapeID = Shape
2401         return self.mesh.GetSubMeshNodesId(ShapeID, all)
2402
2403     ## Returns type of elements on given shape
2404     #  @param Shape a geom object(sub-shape) IOR
2405     #         Shape must be a sub-shape of a ShapeToMesh()
2406     #  @return element type
2407     #  @ingroup l1_meshinfo
2408     def GetSubMeshElementType(self, Shape):
2409         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2410             ShapeID = Shape.GetSubShapeIndices()[0]
2411         else:
2412             ShapeID = Shape
2413         return self.mesh.GetSubMeshElementType(ShapeID)
2414
2415     ## Gets the mesh description
2416     #  @return string value
2417     #  @ingroup l1_meshinfo
2418     def Dump(self):
2419         return self.mesh.Dump()
2420
2421
2422     # Get the information about nodes and elements of a mesh by its IDs:
2423     # -----------------------------------------------------------
2424
2425     ## Gets XYZ coordinates of a node
2426     #  \n If there is no nodes for the given ID - returns an empty list
2427     #  @return a list of double precision values
2428     #  @ingroup l1_meshinfo
2429     def GetNodeXYZ(self, id):
2430         return self.mesh.GetNodeXYZ(id)
2431
2432     ## Returns list of IDs of inverse elements for the given node
2433     #  \n If there is no node for the given ID - returns an empty list
2434     #  @return a list of integer values
2435     #  @ingroup l1_meshinfo
2436     def GetNodeInverseElements(self, id):
2437         return self.mesh.GetNodeInverseElements(id)
2438
2439     ## @brief Returns the position of a node on the shape
2440     #  @return SMESH::NodePosition
2441     #  @ingroup l1_meshinfo
2442     def GetNodePosition(self,NodeID):
2443         return self.mesh.GetNodePosition(NodeID)
2444
2445     ## @brief Returns the position of an element on the shape
2446     #  @return SMESH::ElementPosition
2447     #  @ingroup l1_meshinfo
2448     def GetElementPosition(self,ElemID):
2449         return self.mesh.GetElementPosition(ElemID)
2450
2451     ## If the given element is a node, returns the ID of shape
2452     #  \n If there is no node for the given ID - returns -1
2453     #  @return an integer value
2454     #  @ingroup l1_meshinfo
2455     def GetShapeID(self, id):
2456         return self.mesh.GetShapeID(id)
2457
2458     ## Returns the ID of the result shape after
2459     #  FindShape() from SMESH_MeshEditor for the given element
2460     #  \n If there is no element for the given ID - returns -1
2461     #  @return an integer value
2462     #  @ingroup l1_meshinfo
2463     def GetShapeIDForElem(self,id):
2464         return self.mesh.GetShapeIDForElem(id)
2465
2466     ## Returns the number of nodes for the given element
2467     #  \n If there is no element for the given ID - returns -1
2468     #  @return an integer value
2469     #  @ingroup l1_meshinfo
2470     def GetElemNbNodes(self, id):
2471         return self.mesh.GetElemNbNodes(id)
2472
2473     ## Returns the node ID the given (zero based) index for the given element
2474     #  \n If there is no element for the given ID - returns -1
2475     #  \n If there is no node for the given index - returns -2
2476     #  @return an integer value
2477     #  @ingroup l1_meshinfo
2478     def GetElemNode(self, id, index):
2479         return self.mesh.GetElemNode(id, index)
2480
2481     ## Returns the IDs of nodes of the given element
2482     #  @return a list of integer values
2483     #  @ingroup l1_meshinfo
2484     def GetElemNodes(self, id):
2485         return self.mesh.GetElemNodes(id)
2486
2487     ## Returns true if the given node is the medium node in the given quadratic element
2488     #  @ingroup l1_meshinfo
2489     def IsMediumNode(self, elementID, nodeID):
2490         return self.mesh.IsMediumNode(elementID, nodeID)
2491
2492     ## Returns true if the given node is the medium node in one of quadratic elements
2493     #  @ingroup l1_meshinfo
2494     def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2495         return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2496
2497     ## Returns the number of edges for the given element
2498     #  @ingroup l1_meshinfo
2499     def ElemNbEdges(self, id):
2500         return self.mesh.ElemNbEdges(id)
2501
2502     ## Returns the number of faces for the given element
2503     #  @ingroup l1_meshinfo
2504     def ElemNbFaces(self, id):
2505         return self.mesh.ElemNbFaces(id)
2506
2507     ## Returns nodes of given face (counted from zero) for given volumic element.
2508     #  @ingroup l1_meshinfo
2509     def GetElemFaceNodes(self,elemId, faceIndex):
2510         return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2511
2512     ## Returns three components of normal of given mesh face
2513     #  (or an empty array in KO case)
2514     #  @ingroup l1_meshinfo
2515     def GetFaceNormal(self, faceId, normalized=False):
2516         return self.mesh.GetFaceNormal(faceId,normalized)
2517
2518     ## Returns an element based on all given nodes.
2519     #  @ingroup l1_meshinfo
2520     def FindElementByNodes(self,nodes):
2521         return self.mesh.FindElementByNodes(nodes)
2522
2523     ## Returns true if the given element is a polygon
2524     #  @ingroup l1_meshinfo
2525     def IsPoly(self, id):
2526         return self.mesh.IsPoly(id)
2527
2528     ## Returns true if the given element is quadratic
2529     #  @ingroup l1_meshinfo
2530     def IsQuadratic(self, id):
2531         return self.mesh.IsQuadratic(id)
2532
2533     ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2534     #  @ingroup l1_meshinfo
2535     def GetBallDiameter(self, id):
2536         return self.mesh.GetBallDiameter(id)
2537
2538     ## Returns XYZ coordinates of the barycenter of the given element
2539     #  \n If there is no element for the given ID - returns an empty list
2540     #  @return a list of three double values
2541     #  @ingroup l1_meshinfo
2542     def BaryCenter(self, id):
2543         return self.mesh.BaryCenter(id)
2544
2545     ## Passes mesh elements through the given filter and return IDs of fitting elements
2546     #  @param theFilter SMESH_Filter
2547     #  @return a list of ids
2548     #  @ingroup l1_controls
2549     def GetIdsFromFilter(self, theFilter):
2550         theFilter.SetMesh( self.mesh )
2551         return theFilter.GetIDs()
2552
2553     ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2554     #  Returns a list of special structures (borders).
2555     #  @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2556     #  @ingroup l1_controls
2557     def GetFreeBorders(self):
2558         aFilterMgr = self.smeshpyD.CreateFilterManager()
2559         aPredicate = aFilterMgr.CreateFreeEdges()
2560         aPredicate.SetMesh(self.mesh)
2561         aBorders = aPredicate.GetBorders()
2562         aFilterMgr.UnRegister()
2563         return aBorders
2564
2565
2566     # Get mesh measurements information:
2567     # ------------------------------------
2568
2569     ## Get minimum distance between two nodes, elements or distance to the origin
2570     #  @param id1 first node/element id
2571     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2572     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2573     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2574     #  @return minimum distance value
2575     #  @sa GetMinDistance()
2576     def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2577         aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2578         return aMeasure.value
2579
2580     ## Get measure structure specifying minimum distance data between two objects
2581     #  @param id1 first node/element id
2582     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2583     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2584     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2585     #  @return Measure structure
2586     #  @sa MinDistance()
2587     def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2588         if isElem1:
2589             id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2590         else:
2591             id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2592         if id2 != 0:
2593             if isElem2:
2594                 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2595             else:
2596                 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2597             pass
2598         else:
2599             id2 = None
2600
2601         aMeasurements = self.smeshpyD.CreateMeasurements()
2602         aMeasure = aMeasurements.MinDistance(id1, id2)
2603         genObjUnRegister([aMeasurements,id1, id2])
2604         return aMeasure
2605
2606     ## Get bounding box of the specified object(s)
2607     #  @param objects single source object or list of source objects or list of nodes/elements IDs
2608     #  @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2609     #  @c False specifies that @a objects are nodes
2610     #  @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2611     #  @sa GetBoundingBox()
2612     def BoundingBox(self, objects=None, isElem=False):
2613         result = self.GetBoundingBox(objects, isElem)
2614         if result is None:
2615             result = (0.0,)*6
2616         else:
2617             result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2618         return result
2619
2620     ## Get measure structure specifying bounding box data of the specified object(s)
2621     #  @param IDs single source object or list of source objects or list of nodes/elements IDs
2622     #  @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2623     #  @c False specifies that @a objects are nodes
2624     #  @return Measure structure
2625     #  @sa BoundingBox()
2626     def GetBoundingBox(self, IDs=None, isElem=False):
2627         if IDs is None:
2628             IDs = [self.mesh]
2629         elif isinstance(IDs, tuple):
2630             IDs = list(IDs)
2631         if not isinstance(IDs, list):
2632             IDs = [IDs]
2633         if len(IDs) > 0 and isinstance(IDs[0], int):
2634             IDs = [IDs]
2635         srclist = []
2636         unRegister = genObjUnRegister()
2637         for o in IDs:
2638             if isinstance(o, Mesh):
2639                 srclist.append(o.mesh)
2640             elif hasattr(o, "_narrow"):
2641                 src = o._narrow(SMESH.SMESH_IDSource)
2642                 if src: srclist.append(src)
2643                 pass
2644             elif isinstance(o, list):
2645                 if isElem:
2646                     srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2647                 else:
2648                     srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2649                 unRegister.set( srclist[-1] )
2650                 pass
2651             pass
2652         aMeasurements = self.smeshpyD.CreateMeasurements()
2653         unRegister.set( aMeasurements )
2654         aMeasure = aMeasurements.BoundingBox(srclist)
2655         return aMeasure
2656
2657     # Mesh edition (SMESH_MeshEditor functionality):
2658     # ---------------------------------------------
2659
2660     ## Removes the elements from the mesh by ids
2661     #  @param IDsOfElements is a list of ids of elements to remove
2662     #  @return True or False
2663     #  @ingroup l2_modif_del
2664     def RemoveElements(self, IDsOfElements):
2665         return self.editor.RemoveElements(IDsOfElements)
2666
2667     ## Removes nodes from mesh by ids
2668     #  @param IDsOfNodes is a list of ids of nodes to remove
2669     #  @return True or False
2670     #  @ingroup l2_modif_del
2671     def RemoveNodes(self, IDsOfNodes):
2672         return self.editor.RemoveNodes(IDsOfNodes)
2673
2674     ## Removes all orphan (free) nodes from mesh
2675     #  @return number of the removed nodes
2676     #  @ingroup l2_modif_del
2677     def RemoveOrphanNodes(self):
2678         return self.editor.RemoveOrphanNodes()
2679
2680     ## Add a node to the mesh by coordinates
2681     #  @return Id of the new node
2682     #  @ingroup l2_modif_add
2683     def AddNode(self, x, y, z):
2684         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2685         if hasVars: self.mesh.SetParameters(Parameters)
2686         return self.editor.AddNode( x, y, z)
2687
2688     ## Creates a 0D element on a node with given number.
2689     #  @param IDOfNode the ID of node for creation of the element.
2690     #  @return the Id of the new 0D element
2691     #  @ingroup l2_modif_add
2692     def Add0DElement(self, IDOfNode):
2693         return self.editor.Add0DElement(IDOfNode)
2694
2695     ## Create 0D elements on all nodes of the given elements except those 
2696     #  nodes on which a 0D element already exists.
2697     #  @param theObject an object on whose nodes 0D elements will be created.
2698     #         It can be mesh, sub-mesh, group, list of element IDs or a holder
2699     #         of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2700     #  @param theGroupName optional name of a group to add 0D elements created
2701     #         and/or found on nodes of \a theObject.
2702     #  @return an object (a new group or a temporary SMESH_IDSource) holding
2703     #          IDs of new and/or found 0D elements. IDs of 0D elements 
2704     #          can be retrieved from the returned object by calling GetIDs()
2705     #  @ingroup l2_modif_add
2706     def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2707         unRegister = genObjUnRegister()
2708         if isinstance( theObject, Mesh ):
2709             theObject = theObject.GetMesh()
2710         if isinstance( theObject, list ):
2711             theObject = self.GetIDSource( theObject, SMESH.ALL )
2712             unRegister.set( theObject )
2713         return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2714
2715     ## Creates a ball element on a node with given ID.
2716     #  @param IDOfNode the ID of node for creation of the element.
2717     #  @param diameter the bal diameter.
2718     #  @return the Id of the new ball element
2719     #  @ingroup l2_modif_add
2720     def AddBall(self, IDOfNode, diameter):
2721         return self.editor.AddBall( IDOfNode, diameter )
2722
2723     ## Creates a linear or quadratic edge (this is determined
2724     #  by the number of given nodes).
2725     #  @param IDsOfNodes the list of node IDs for creation of the element.
2726     #  The order of nodes in this list should correspond to the description
2727     #  of MED. \n This description is located by the following link:
2728     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2729     #  @return the Id of the new edge
2730     #  @ingroup l2_modif_add
2731     def AddEdge(self, IDsOfNodes):
2732         return self.editor.AddEdge(IDsOfNodes)
2733
2734     ## Creates a linear or quadratic face (this is determined
2735     #  by the number of given nodes).
2736     #  @param IDsOfNodes the list of node IDs for creation of the element.
2737     #  The order of nodes in this list should correspond to the description
2738     #  of MED. \n This description is located by the following link:
2739     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2740     #  @return the Id of the new face
2741     #  @ingroup l2_modif_add
2742     def AddFace(self, IDsOfNodes):
2743         return self.editor.AddFace(IDsOfNodes)
2744
2745     ## Adds a polygonal face to the mesh by the list of node IDs
2746     #  @param IdsOfNodes the list of node IDs for creation of the element.
2747     #  @return the Id of the new face
2748     #  @ingroup l2_modif_add
2749     def AddPolygonalFace(self, IdsOfNodes):
2750         return self.editor.AddPolygonalFace(IdsOfNodes)
2751
2752     ## Creates both simple and quadratic volume (this is determined
2753     #  by the number of given nodes).
2754     #  @param IDsOfNodes the list of node IDs for creation of the element.
2755     #  The order of nodes in this list should correspond to the description
2756     #  of MED. \n This description is located by the following link:
2757     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2758     #  @return the Id of the new volumic element
2759     #  @ingroup l2_modif_add
2760     def AddVolume(self, IDsOfNodes):
2761         return self.editor.AddVolume(IDsOfNodes)
2762
2763     ## Creates a volume of many faces, giving nodes for each face.
2764     #  @param IdsOfNodes the list of node IDs for volume creation face by face.
2765     #  @param Quantities the list of integer values, Quantities[i]
2766     #         gives the quantity of nodes in face number i.
2767     #  @return the Id of the new volumic element
2768     #  @ingroup l2_modif_add
2769     def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2770         return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2771
2772     ## Creates a volume of many faces, giving the IDs of the existing faces.
2773     #  @param IdsOfFaces the list of face IDs for volume creation.
2774     #
2775     #  Note:  The created volume will refer only to the nodes
2776     #         of the given faces, not to the faces themselves.
2777     #  @return the Id of the new volumic element
2778     #  @ingroup l2_modif_add
2779     def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2780         return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2781
2782
2783     ## @brief Binds a node to a vertex
2784     #  @param NodeID a node ID
2785     #  @param Vertex a vertex or vertex ID
2786     #  @return True if succeed else raises an exception
2787     #  @ingroup l2_modif_add
2788     def SetNodeOnVertex(self, NodeID, Vertex):
2789         if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2790             VertexID = Vertex.GetSubShapeIndices()[0]
2791         else:
2792             VertexID = Vertex
2793         try:
2794             self.editor.SetNodeOnVertex(NodeID, VertexID)
2795         except SALOME.SALOME_Exception, inst:
2796             raise ValueError, inst.details.text
2797         return True
2798
2799
2800     ## @brief Stores the node position on an edge
2801     #  @param NodeID a node ID
2802     #  @param Edge an edge or edge ID
2803     #  @param paramOnEdge a parameter on the edge where the node is located
2804     #  @return True if succeed else raises an exception
2805     #  @ingroup l2_modif_add
2806     def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2807         if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2808             EdgeID = Edge.GetSubShapeIndices()[0]
2809         else:
2810             EdgeID = Edge
2811         try:
2812             self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2813         except SALOME.SALOME_Exception, inst:
2814             raise ValueError, inst.details.text
2815         return True
2816
2817     ## @brief Stores node position on a face
2818     #  @param NodeID a node ID
2819     #  @param Face a face or face ID
2820     #  @param u U parameter on the face where the node is located
2821     #  @param v V parameter on the face where the node is located
2822     #  @return True if succeed else raises an exception
2823     #  @ingroup l2_modif_add
2824     def SetNodeOnFace(self, NodeID, Face, u, v):
2825         if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2826             FaceID = Face.GetSubShapeIndices()[0]
2827         else:
2828             FaceID = Face
2829         try:
2830             self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2831         except SALOME.SALOME_Exception, inst:
2832             raise ValueError, inst.details.text
2833         return True
2834
2835     ## @brief Binds a node to a solid
2836     #  @param NodeID a node ID
2837     #  @param Solid  a solid or solid ID
2838     #  @return True if succeed else raises an exception
2839     #  @ingroup l2_modif_add
2840     def SetNodeInVolume(self, NodeID, Solid):
2841         if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2842             SolidID = Solid.GetSubShapeIndices()[0]
2843         else:
2844             SolidID = Solid
2845         try:
2846             self.editor.SetNodeInVolume(NodeID, SolidID)
2847         except SALOME.SALOME_Exception, inst:
2848             raise ValueError, inst.details.text
2849         return True
2850
2851     ## @brief Bind an element to a shape
2852     #  @param ElementID an element ID
2853     #  @param Shape a shape or shape ID
2854     #  @return True if succeed else raises an exception
2855     #  @ingroup l2_modif_add
2856     def SetMeshElementOnShape(self, ElementID, Shape):
2857         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2858             ShapeID = Shape.GetSubShapeIndices()[0]
2859         else:
2860             ShapeID = Shape
2861         try:
2862             self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2863         except SALOME.SALOME_Exception, inst:
2864             raise ValueError, inst.details.text
2865         return True
2866
2867
2868     ## Moves the node with the given id
2869     #  @param NodeID the id of the node
2870     #  @param x  a new X coordinate
2871     #  @param y  a new Y coordinate
2872     #  @param z  a new Z coordinate
2873     #  @return True if succeed else False
2874     #  @ingroup l2_modif_movenode
2875     def MoveNode(self, NodeID, x, y, z):
2876         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2877         if hasVars: self.mesh.SetParameters(Parameters)
2878         return self.editor.MoveNode(NodeID, x, y, z)
2879
2880     ## Finds the node closest to a point and moves it to a point location
2881     #  @param x  the X coordinate of a point
2882     #  @param y  the Y coordinate of a point
2883     #  @param z  the Z coordinate of a point
2884     #  @param NodeID if specified (>0), the node with this ID is moved,
2885     #  otherwise, the node closest to point (@a x,@a y,@a z) is moved
2886     #  @return the ID of a node
2887     #  @ingroup l2_modif_throughp
2888     def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2889         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2890         if hasVars: self.mesh.SetParameters(Parameters)
2891         return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2892
2893     ## Finds the node closest to a point
2894     #  @param x  the X coordinate of a point
2895     #  @param y  the Y coordinate of a point
2896     #  @param z  the Z coordinate of a point
2897     #  @return the ID of a node
2898     #  @ingroup l2_modif_throughp
2899     def FindNodeClosestTo(self, x, y, z):
2900         #preview = self.mesh.GetMeshEditPreviewer()
2901         #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2902         return self.editor.FindNodeClosestTo(x, y, z)
2903
2904     ## Finds the elements where a point lays IN or ON
2905     #  @param x  the X coordinate of a point
2906     #  @param y  the Y coordinate of a point
2907     #  @param z  the Z coordinate of a point
2908     #  @param elementType type of elements to find (SMESH.ALL type
2909     #         means elements of any type excluding nodes, discrete and 0D elements)
2910     #  @param meshPart a part of mesh (group, sub-mesh) to search within
2911     #  @return list of IDs of found elements
2912     #  @ingroup l2_modif_throughp
2913     def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2914         if meshPart:
2915             return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2916         else:
2917             return self.editor.FindElementsByPoint(x, y, z, elementType)
2918
2919     # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2920     # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2921     # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2922
2923     def GetPointState(self, x, y, z):
2924         return self.editor.GetPointState(x, y, z)
2925
2926     ## Finds the node closest to a point and moves it to a point location
2927     #  @param x  the X coordinate of a point
2928     #  @param y  the Y coordinate of a point
2929     #  @param z  the Z coordinate of a point
2930     #  @return the ID of a moved node
2931     #  @ingroup l2_modif_throughp
2932     def MeshToPassThroughAPoint(self, x, y, z):
2933         return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2934
2935     ## Replaces two neighbour triangles sharing Node1-Node2 link
2936     #  with the triangles built on the same 4 nodes but having other common link.
2937     #  @param NodeID1  the ID of the first node
2938     #  @param NodeID2  the ID of the second node
2939     #  @return false if proper faces were not found
2940     #  @ingroup l2_modif_invdiag
2941     def InverseDiag(self, NodeID1, NodeID2):
2942         return self.editor.InverseDiag(NodeID1, NodeID2)
2943
2944     ## Replaces two neighbour triangles sharing Node1-Node2 link
2945     #  with a quadrangle built on the same 4 nodes.
2946     #  @param NodeID1  the ID of the first node
2947     #  @param NodeID2  the ID of the second node
2948     #  @return false if proper faces were not found
2949     #  @ingroup l2_modif_unitetri
2950     def DeleteDiag(self, NodeID1, NodeID2):
2951         return self.editor.DeleteDiag(NodeID1, NodeID2)
2952
2953     ## Reorients elements by ids
2954     #  @param IDsOfElements if undefined reorients all mesh elements
2955     #  @return True if succeed else False
2956     #  @ingroup l2_modif_changori
2957     def Reorient(self, IDsOfElements=None):
2958         if IDsOfElements == None:
2959             IDsOfElements = self.GetElementsId()
2960         return self.editor.Reorient(IDsOfElements)
2961
2962     ## Reorients all elements of the object
2963     #  @param theObject mesh, submesh or group
2964     #  @return True if succeed else False
2965     #  @ingroup l2_modif_changori
2966     def ReorientObject(self, theObject):
2967         if ( isinstance( theObject, Mesh )):
2968             theObject = theObject.GetMesh()
2969         return self.editor.ReorientObject(theObject)
2970
2971     ## Reorient faces contained in \a the2DObject.
2972     #  @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2973     #  @param theDirection is a desired direction of normal of \a theFace.
2974     #         It can be either a GEOM vector or a list of coordinates [x,y,z].
2975     #  @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2976     #         compared with theDirection. It can be either ID of face or a point
2977     #         by which the face will be found. The point can be given as either
2978     #         a GEOM vertex or a list of point coordinates.
2979     #  @return number of reoriented faces
2980     #  @ingroup l2_modif_changori
2981     def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2982         unRegister = genObjUnRegister()
2983         # check the2DObject
2984         if isinstance( the2DObject, Mesh ):
2985             the2DObject = the2DObject.GetMesh()
2986         if isinstance( the2DObject, list ):
2987             the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2988             unRegister.set( the2DObject )
2989         # check theDirection
2990         if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2991             theDirection = self.smeshpyD.GetDirStruct( theDirection )
2992         if isinstance( theDirection, list ):
2993             theDirection = self.smeshpyD.MakeDirStruct( *theDirection  )
2994         # prepare theFace and thePoint
2995         theFace = theFaceOrPoint
2996         thePoint = PointStruct(0,0,0)
2997         if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
2998             thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
2999             theFace = -1
3000         if isinstance( theFaceOrPoint, list ):
3001             thePoint = PointStruct( *theFaceOrPoint )
3002             theFace = -1
3003         if isinstance( theFaceOrPoint, PointStruct ):
3004             thePoint = theFaceOrPoint
3005             theFace = -1
3006         return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3007
3008     ## Reorient faces according to adjacent volumes.
3009     #  @param the2DObject is a mesh, sub-mesh, group or list of
3010     #         either IDs of faces or face groups.
3011     #  @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3012     #  @param theOutsideNormal to orient faces to have their normals
3013     #         pointing either \a outside or \a inside the adjacent volumes.
3014     #  @return number of reoriented faces.
3015     #  @ingroup l2_modif_changori
3016     def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3017         unRegister = genObjUnRegister()
3018         # check the2DObject
3019         if not isinstance( the2DObject, list ):
3020             the2DObject = [ the2DObject ]
3021         elif the2DObject and isinstance( the2DObject[0], int ):
3022             the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3023             unRegister.set( the2DObject )
3024             the2DObject = [ the2DObject ]
3025         for i,obj2D in enumerate( the2DObject ):
3026             if isinstance( obj2D, Mesh ):
3027                 the2DObject[i] = obj2D.GetMesh()
3028             if isinstance( obj2D, list ):
3029                 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3030                 unRegister.set( the2DObject[i] )
3031         # check the3DObject
3032         if isinstance( the3DObject, Mesh ):
3033             the3DObject = the3DObject.GetMesh()
3034         if isinstance( the3DObject, list ):
3035             the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3036             unRegister.set( the3DObject )
3037         return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3038
3039     ## Fuses the neighbouring triangles into quadrangles.
3040     #  @param IDsOfElements The triangles to be fused,
3041     #  @param theCriterion  is a numerical functor, in terms of enum SMESH.FunctorType, used to
3042     #                       choose a neighbour to fuse with.
3043     #  @param MaxAngle      is the maximum angle between element normals at which the fusion
3044     #                       is still performed; theMaxAngle is mesured in radians.
3045     #                       Also it could be a name of variable which defines angle in degrees.
3046     #  @return TRUE in case of success, FALSE otherwise.
3047     #  @ingroup l2_modif_unitetri
3048     def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3049         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3050         self.mesh.SetParameters(Parameters)
3051         if not IDsOfElements:
3052             IDsOfElements = self.GetElementsId()
3053         Functor = self.smeshpyD.GetFunctor(theCriterion)
3054         return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3055
3056     ## Fuses the neighbouring triangles of the object into quadrangles
3057     #  @param theObject is mesh, submesh or group
3058     #  @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3059     #         choose a neighbour to fuse with.
3060     #  @param MaxAngle   a max angle between element normals at which the fusion
3061     #                   is still performed; theMaxAngle is mesured in radians.
3062     #  @return TRUE in case of success, FALSE otherwise.
3063     #  @ingroup l2_modif_unitetri
3064     def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3065         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3066         self.mesh.SetParameters(Parameters)
3067         if isinstance( theObject, Mesh ):
3068             theObject = theObject.GetMesh()
3069         Functor = self.smeshpyD.GetFunctor(theCriterion)
3070         return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3071
3072     ## Splits quadrangles into triangles.
3073     #  @param IDsOfElements the faces to be splitted.
3074     #  @param theCriterion   is a numerical functor, in terms of enum SMESH.FunctorType, used to
3075     #         choose a diagonal for splitting. If @a theCriterion is None, which is a default
3076     #         value, then quadrangles will be split by the smallest diagonal.
3077     #  @return TRUE in case of success, FALSE otherwise.
3078     #  @ingroup l2_modif_cutquadr
3079     def QuadToTri (self, IDsOfElements, theCriterion = None):
3080         if IDsOfElements == []:
3081             IDsOfElements = self.GetElementsId()
3082         if theCriterion is None:
3083             theCriterion = FT_MaxElementLength2D
3084         Functor = self.smeshpyD.GetFunctor(theCriterion)
3085         return self.editor.QuadToTri(IDsOfElements, Functor)
3086
3087     ## Splits quadrangles into triangles.
3088     #  @param theObject the object from which the list of elements is taken,
3089     #         this is mesh, submesh or group
3090     #  @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3091     #         choose a diagonal for splitting. If @a theCriterion is None, which is a default
3092     #         value, then quadrangles will be split by the smallest diagonal.
3093     #  @return TRUE in case of success, FALSE otherwise.
3094     #  @ingroup l2_modif_cutquadr
3095     def QuadToTriObject (self, theObject, theCriterion = None):
3096         if ( isinstance( theObject, Mesh )):
3097             theObject = theObject.GetMesh()
3098         if theCriterion is None:
3099             theCriterion = FT_MaxElementLength2D
3100         Functor = self.smeshpyD.GetFunctor(theCriterion)
3101         return self.editor.QuadToTriObject(theObject, Functor)
3102
3103     ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3104     #  a quadrangle.
3105     #  @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3106     #         group or a list of face IDs. By default all quadrangles are split
3107     #  @ingroup l2_modif_cutquadr
3108     def QuadTo4Tri (self, theElements=[]):
3109         unRegister = genObjUnRegister()
3110         if isinstance( theElements, Mesh ):
3111             theElements = theElements.mesh
3112         elif not theElements:
3113             theElements = self.mesh
3114         elif isinstance( theElements, list ):
3115             theElements = self.GetIDSource( theElements, SMESH.FACE )
3116             unRegister.set( theElements )
3117         return self.editor.QuadTo4Tri( theElements )
3118
3119     ## Splits quadrangles into triangles.
3120     #  @param IDsOfElements the faces to be splitted
3121     #  @param Diag13        is used to choose a diagonal for splitting.
3122     #  @return TRUE in case of success, FALSE otherwise.
3123     #  @ingroup l2_modif_cutquadr
3124     def SplitQuad (self, IDsOfElements, Diag13):
3125         if IDsOfElements == []:
3126             IDsOfElements = self.GetElementsId()
3127         return self.editor.SplitQuad(IDsOfElements, Diag13)
3128
3129     ## Splits quadrangles into triangles.
3130     #  @param theObject the object from which the list of elements is taken,
3131     #         this is mesh, submesh or group
3132     #  @param Diag13    is used to choose a diagonal for splitting.
3133     #  @return TRUE in case of success, FALSE otherwise.
3134     #  @ingroup l2_modif_cutquadr
3135     def SplitQuadObject (self, theObject, Diag13):
3136         if ( isinstance( theObject, Mesh )):
3137             theObject = theObject.GetMesh()
3138         return self.editor.SplitQuadObject(theObject, Diag13)
3139
3140     ## Finds a better splitting of the given quadrangle.
3141     #  @param IDOfQuad   the ID of the quadrangle to be splitted.
3142     #  @param theCriterion  is a numerical functor, in terms of enum SMESH.FunctorType, used to
3143     #         choose a diagonal for splitting.
3144     #  @return 1 if 1-3 diagonal is better, 2 if 2-4
3145     #          diagonal is better, 0 if error occurs.
3146     #  @ingroup l2_modif_cutquadr
3147     def BestSplit (self, IDOfQuad, theCriterion):
3148         return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3149
3150     ## Splits volumic elements into tetrahedrons
3151     #  @param elems either a list of elements or a mesh or a group or a submesh or a filter
3152     #  @param method  flags passing splitting method:
3153     #         smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3154     #         smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3155     #  @ingroup l2_modif_cutquadr
3156     def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3157         unRegister = genObjUnRegister()
3158         if isinstance( elems, Mesh ):
3159             elems = elems.GetMesh()
3160         if ( isinstance( elems, list )):
3161             elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3162             unRegister.set( elems )
3163         self.editor.SplitVolumesIntoTetra(elems, method)
3164
3165     ## Splits hexahedra into prisms
3166     #  @param elems either a list of elements or a mesh or a group or a submesh or a filter
3167     #  @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3168     #         gives a normal vector defining facets to split into triangles.
3169     #         @a startHexPoint can be either a triple of coordinates or a vertex.
3170     #  @param facetNormal a normal to a facet to split into triangles of a
3171     #         hexahedron found by @a startHexPoint.
3172     #         @a facetNormal can be either a triple of coordinates or an edge.
3173     #  @param method  flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3174     #         smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3175     #  @param allDomains if @c False, only hexahedra adjacent to one closest
3176     #         to @a startHexPoint are split, else @a startHexPoint
3177     #         is used to find the facet to split in all domains present in @a elems.
3178     #  @ingroup l2_modif_cutquadr
3179     def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3180                                  method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3181         # IDSource
3182         unRegister = genObjUnRegister()
3183         if isinstance( elems, Mesh ):
3184             elems = elems.GetMesh()
3185         if ( isinstance( elems, list )):
3186             elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3187             unRegister.set( elems )
3188             pass
3189         # axis
3190         if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3191             startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3192         elif isinstance( startHexPoint, list ):
3193             startHexPoint = SMESH.PointStruct( startHexPoint[0],
3194                                                startHexPoint[1],
3195                                                startHexPoint[2])
3196         if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3197             facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3198         elif isinstance( facetNormal, list ):
3199             facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3200                                                        facetNormal[1],
3201                                                        facetNormal[2])
3202         self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3203
3204         self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3205
3206     ## Splits quadrangle faces near triangular facets of volumes
3207     #
3208     #  @ingroup l1_auxiliary
3209     def SplitQuadsNearTriangularFacets(self):
3210         faces_array = self.GetElementsByType(SMESH.FACE)
3211         for face_id in faces_array:
3212             if self.GetElemNbNodes(face_id) == 4: # quadrangle
3213                 quad_nodes = self.mesh.GetElemNodes(face_id)
3214                 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3215                 isVolumeFound = False
3216                 for node1_elem in node1_elems:
3217                     if not isVolumeFound:
3218                         if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3219                             nb_nodes = self.GetElemNbNodes(node1_elem)
3220                             if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3221                                 volume_elem = node1_elem
3222                                 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3223                                 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3224                                     if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3225                                         isVolumeFound = True
3226                                         if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3227                                             self.SplitQuad([face_id], False) # diagonal 2-4
3228                                     elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3229                                         isVolumeFound = True
3230                                         self.SplitQuad([face_id], True) # diagonal 1-3
3231                                 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3232                                     if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3233                                         isVolumeFound = True
3234                                         self.SplitQuad([face_id], True) # diagonal 1-3
3235
3236     ## @brief Splits hexahedrons into tetrahedrons.
3237     #
3238     #  This operation uses pattern mapping functionality for splitting.
3239     #  @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3240     #  @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3241     #         pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3242     #         will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3243     #         key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3244     #         The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3245     #  @return TRUE in case of success, FALSE otherwise.
3246     #  @ingroup l1_auxiliary
3247     def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3248         # Pattern:     5.---------.6
3249         #              /|#*      /|
3250         #             / | #*    / |
3251         #            /  |  # * /  |
3252         #           /   |   # /*  |
3253         # (0,0,1) 4.---------.7 * |
3254         #          |#*  |1   | # *|
3255         #          | # *.----|---#.2
3256         #          |  #/ *   |   /
3257         #          |  /#  *  |  /
3258         #          | /   # * | /
3259         #          |/      #*|/
3260         # (0,0,0) 0.---------.3
3261         pattern_tetra = "!!! Nb of points: \n 8 \n\
3262         !!! Points: \n\
3263         0 0 0  !- 0 \n\
3264         0 1 0  !- 1 \n\
3265         1 1 0  !- 2 \n\
3266         1 0 0  !- 3 \n\
3267         0 0 1  !- 4 \n\
3268         0 1 1  !- 5 \n\
3269         1 1 1  !- 6 \n\
3270         1 0 1  !- 7 \n\
3271         !!! Indices of points of 6 tetras: \n\
3272         0 3 4 1 \n\
3273         7 4 3 1 \n\
3274         4 7 5 1 \n\
3275         6 2 5 7 \n\
3276         1 5 2 7 \n\
3277         2 3 1 7 \n"
3278
3279         pattern = self.smeshpyD.GetPattern()
3280         isDone  = pattern.LoadFromFile(pattern_tetra)
3281         if not isDone:
3282             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3283             return isDone
3284
3285         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3286         isDone = pattern.MakeMesh(self.mesh, False, False)
3287         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3288
3289         # split quafrangle faces near triangular facets of volumes
3290         self.SplitQuadsNearTriangularFacets()
3291
3292         return isDone
3293
3294     ## @brief Split hexahedrons into prisms.
3295     #
3296     #  Uses the pattern mapping functionality for splitting.
3297     #  @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3298     #  @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3299     #         pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3300     #         will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3301     #         will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3302     #         Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3303     #  @return TRUE in case of success, FALSE otherwise.
3304     #  @ingroup l1_auxiliary
3305     def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3306         # Pattern:     5.---------.6
3307         #              /|#       /|
3308         #             / | #     / |
3309         #            /  |  #   /  |
3310         #           /   |   # /   |
3311         # (0,0,1) 4.---------.7   |
3312         #          |    |    |    |
3313         #          |   1.----|----.2
3314         #          |   / *   |   /
3315         #          |  /   *  |  /
3316         #          | /     * | /
3317         #          |/       *|/
3318         # (0,0,0) 0.---------.3
3319         pattern_prism = "!!! Nb of points: \n 8 \n\
3320         !!! Points: \n\
3321         0 0 0  !- 0 \n\
3322         0 1 0  !- 1 \n\
3323         1 1 0  !- 2 \n\
3324         1 0 0  !- 3 \n\
3325         0 0 1  !- 4 \n\
3326         0 1 1  !- 5 \n\
3327         1 1 1  !- 6 \n\
3328         1 0 1  !- 7 \n\
3329         !!! Indices of points of 2 prisms: \n\
3330         0 1 3 4 5 7 \n\
3331         2 3 1 6 7 5 \n"
3332
3333         pattern = self.smeshpyD.GetPattern()
3334         isDone  = pattern.LoadFromFile(pattern_prism)
3335         if not isDone:
3336             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3337             return isDone
3338
3339         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3340         isDone = pattern.MakeMesh(self.mesh, False, False)
3341         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3342
3343         # Splits quafrangle faces near triangular facets of volumes
3344         self.SplitQuadsNearTriangularFacets()
3345
3346         return isDone
3347
3348     ## Smoothes elements
3349     #  @param IDsOfElements the list if ids of elements to smooth
3350     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3351     #  Note that nodes built on edges and boundary nodes are always fixed.
3352     #  @param MaxNbOfIterations the maximum number of iterations
3353     #  @param MaxAspectRatio varies in range [1.0, inf]
3354     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3355     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3356     #  @return TRUE in case of success, FALSE otherwise.
3357     #  @ingroup l2_modif_smooth
3358     def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3359                MaxNbOfIterations, MaxAspectRatio, Method):
3360         if IDsOfElements == []:
3361             IDsOfElements = self.GetElementsId()
3362         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3363         self.mesh.SetParameters(Parameters)
3364         return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3365                                   MaxNbOfIterations, MaxAspectRatio, Method)
3366
3367     ## Smoothes elements which belong to the given object
3368     #  @param theObject the object to smooth
3369     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3370     #  Note that nodes built on edges and boundary nodes are always fixed.
3371     #  @param MaxNbOfIterations the maximum number of iterations
3372     #  @param MaxAspectRatio varies in range [1.0, inf]
3373     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3374     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3375     #  @return TRUE in case of success, FALSE otherwise.
3376     #  @ingroup l2_modif_smooth
3377     def SmoothObject(self, theObject, IDsOfFixedNodes,
3378                      MaxNbOfIterations, MaxAspectRatio, Method):
3379         if ( isinstance( theObject, Mesh )):
3380             theObject = theObject.GetMesh()
3381         return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3382                                         MaxNbOfIterations, MaxAspectRatio, Method)
3383
3384     ## Parametrically smoothes the given elements
3385     #  @param IDsOfElements the list if ids of elements to smooth
3386     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3387     #  Note that nodes built on edges and boundary nodes are always fixed.
3388     #  @param MaxNbOfIterations the maximum number of iterations
3389     #  @param MaxAspectRatio varies in range [1.0, inf]
3390     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3391     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3392     #  @return TRUE in case of success, FALSE otherwise.
3393     #  @ingroup l2_modif_smooth
3394     def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3395                          MaxNbOfIterations, MaxAspectRatio, Method):
3396         if IDsOfElements == []:
3397             IDsOfElements = self.GetElementsId()
3398         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3399         self.mesh.SetParameters(Parameters)
3400         return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3401                                             MaxNbOfIterations, MaxAspectRatio, Method)
3402
3403     ## Parametrically smoothes the elements which belong to the given object
3404     #  @param theObject the object to smooth
3405     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3406     #  Note that nodes built on edges and boundary nodes are always fixed.
3407     #  @param MaxNbOfIterations the maximum number of iterations
3408     #  @param MaxAspectRatio varies in range [1.0, inf]
3409     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3410     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3411     #  @return TRUE in case of success, FALSE otherwise.
3412     #  @ingroup l2_modif_smooth
3413     def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3414                                MaxNbOfIterations, MaxAspectRatio, Method):
3415         if ( isinstance( theObject, Mesh )):
3416             theObject = theObject.GetMesh()
3417         return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3418                                                   MaxNbOfIterations, MaxAspectRatio, Method)
3419
3420     ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3421     #  them with quadratic with the same id.
3422     #  @param theForce3d new node creation method:
3423     #         0 - the medium node lies at the geometrical entity from which the mesh element is built
3424     #         1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3425     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3426     #  @param theToBiQuad If True, converts the mesh to bi-quadratic
3427     #  @ingroup l2_modif_tofromqu
3428     def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3429         if isinstance( theSubMesh, Mesh ):
3430             theSubMesh = theSubMesh.mesh
3431         if theToBiQuad:
3432             self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3433         else:
3434             if theSubMesh:
3435                 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3436             else:
3437                 self.editor.ConvertToQuadratic(theForce3d)
3438         error = self.editor.GetLastError()
3439         if error and error.comment:
3440             print error.comment
3441             
3442     ## Converts the mesh from quadratic to ordinary,
3443     #  deletes old quadratic elements, \n replacing
3444     #  them with ordinary mesh elements with the same id.
3445     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3446     #  @ingroup l2_modif_tofromqu
3447     def ConvertFromQuadratic(self, theSubMesh=None):
3448         if theSubMesh:
3449             self.editor.ConvertFromQuadraticObject(theSubMesh)
3450         else:
3451             return self.editor.ConvertFromQuadratic()
3452
3453     ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3454     #  @return TRUE if operation has been completed successfully, FALSE otherwise
3455     #  @ingroup l2_modif_edit
3456     def  Make2DMeshFrom3D(self):
3457         return self.editor. Make2DMeshFrom3D()
3458
3459     ## Creates missing boundary elements
3460     #  @param elements - elements whose boundary is to be checked:
3461     #                    mesh, group, sub-mesh or list of elements
3462     #   if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3463     #  @param dimension - defines type of boundary elements to create:
3464     #                     SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D
3465     #    SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3466     #  @param groupName - a name of group to store created boundary elements in,
3467     #                     "" means not to create the group
3468     #  @param meshName - a name of new mesh to store created boundary elements in,
3469     #                     "" means not to create the new mesh
3470     #  @param toCopyElements - if true, the checked elements will be copied into
3471     #     the new mesh else only boundary elements will be copied into the new mesh
3472     #  @param toCopyExistingBondary - if true, not only new but also pre-existing
3473     #     boundary elements will be copied into the new mesh
3474     #  @return tuple (mesh, group) where boundary elements were added to
3475     #  @ingroup l2_modif_edit
3476     def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3477                          toCopyElements=False, toCopyExistingBondary=False):
3478         unRegister = genObjUnRegister()
3479         if isinstance( elements, Mesh ):
3480             elements = elements.GetMesh()
3481         if ( isinstance( elements, list )):
3482             elemType = SMESH.ALL
3483             if elements: elemType = self.GetElementType( elements[0], iselem=True)
3484             elements = self.editor.MakeIDSource(elements, elemType)
3485             unRegister.set( elements )
3486         mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3487                                                    toCopyElements,toCopyExistingBondary)
3488         if mesh: mesh = self.smeshpyD.Mesh(mesh)
3489         return mesh, group
3490
3491     ##
3492     # @brief Creates missing boundary elements around either the whole mesh or 
3493     #    groups of elements
3494     #  @param dimension - defines type of boundary elements to create
3495     #  @param groupName - a name of group to store all boundary elements in,
3496     #    "" means not to create the group
3497     #  @param meshName - a name of a new mesh, which is a copy of the initial 
3498     #    mesh + created boundary elements; "" means not to create the new mesh
3499     #  @param toCopyAll - if true, the whole initial mesh will be copied into
3500     #    the new mesh else only boundary elements will be copied into the new mesh
3501     #  @param groups - groups of elements to make boundary around
3502     #  @retval tuple( long, mesh, groups )
3503     #                 long - number of added boundary elements
3504     #                 mesh - the mesh where elements were added to
3505     #                 group - the group of boundary elements or None
3506     #
3507     def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3508                              toCopyAll=False, groups=[]):
3509         nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3510                                                            toCopyAll,groups)
3511         if mesh: mesh = self.smeshpyD.Mesh(mesh)
3512         return nb, mesh, group
3513
3514     ## Renumber mesh nodes (Obsolete, does nothing)
3515     #  @ingroup l2_modif_renumber
3516     def RenumberNodes(self):
3517         self.editor.RenumberNodes()
3518
3519     ## Renumber mesh elements (Obsole, does nothing)
3520     #  @ingroup l2_modif_renumber
3521     def RenumberElements(self):
3522         self.editor.RenumberElements()
3523
3524     ## Private method converting \a arg into a list of SMESH_IdSource's
3525     def _getIdSourceList(self, arg, idType, unRegister):
3526         if arg and isinstance( arg, list ):
3527             if isinstance( arg[0], int ):
3528                 arg = self.GetIDSource( arg, idType )
3529                 unRegister.set( arg )
3530             elif isinstance( arg[0], Mesh ):
3531                 arg[0] = arg[0].GetMesh()
3532         elif isinstance( arg, Mesh ):
3533             arg = arg.GetMesh()
3534         if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3535             arg = [arg]
3536         return arg
3537
3538     ## Generates new elements by rotation of the given elements and nodes around the axis
3539     #  @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3540     #  @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3541     #  @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3542     #  @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3543     #  @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3544     #         which defines angle in degrees
3545     #  @param NbOfSteps the number of steps
3546     #  @param Tolerance tolerance
3547     #  @param MakeGroups forces the generation of new groups from existing ones
3548     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3549     #                    of all steps, else - size of each step
3550     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3551     #  @ingroup l2_modif_extrurev
3552     def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3553                              MakeGroups=False, TotalAngle=False):
3554         unRegister = genObjUnRegister()
3555         nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3556         edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3557         faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3558
3559         if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3560             Axis = self.smeshpyD.GetAxisStruct( Axis )
3561         if isinstance( Axis, list ):
3562             Axis = SMESH.AxisStruct( *Axis )
3563
3564         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3565         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3566         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3567         self.mesh.SetParameters(Parameters)
3568         if TotalAngle and NbOfSteps:
3569             AngleInRadians /= NbOfSteps
3570         return self.editor.RotationSweepObjects( nodes, edges, faces,
3571                                                  Axis, AngleInRadians,
3572                                                  NbOfSteps, Tolerance, MakeGroups)
3573
3574     ## Generates new elements by rotation of the elements around the axis
3575     #  @param IDsOfElements the list of ids of elements to sweep
3576     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3577     #  @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3578     #  @param NbOfSteps the number of steps
3579     #  @param Tolerance tolerance
3580     #  @param MakeGroups forces the generation of new groups from existing ones
3581     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3582     #                    of all steps, else - size of each step
3583     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3584     #  @ingroup l2_modif_extrurev
3585     def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3586                       MakeGroups=False, TotalAngle=False):
3587         return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3588                                          AngleInRadians, NbOfSteps, Tolerance,
3589                                          MakeGroups, TotalAngle)
3590
3591     ## Generates new elements by rotation of the elements of object around the axis
3592     #  @param theObject object which elements should be sweeped.
3593     #                   It can be a mesh, a sub mesh or a group.
3594     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3595     #  @param AngleInRadians the angle of Rotation
3596     #  @param NbOfSteps number of steps
3597     #  @param Tolerance tolerance
3598     #  @param MakeGroups forces the generation of new groups from existing ones
3599     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3600     #                    of all steps, else - size of each step
3601     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3602     #  @ingroup l2_modif_extrurev
3603     def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3604                             MakeGroups=False, TotalAngle=False):
3605         return self.RotationSweepObjects( [], theObject, theObject, Axis,
3606                                           AngleInRadians, NbOfSteps, Tolerance,
3607                                           MakeGroups, TotalAngle )
3608
3609     ## Generates new elements by rotation of the elements of object around the axis
3610     #  @param theObject object which elements should be sweeped.
3611     #                   It can be a mesh, a sub mesh or a group.
3612     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3613     #  @param AngleInRadians the angle of Rotation
3614     #  @param NbOfSteps number of steps
3615     #  @param Tolerance tolerance
3616     #  @param MakeGroups forces the generation of new groups from existing ones
3617     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3618     #                    of all steps, else - size of each step
3619     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3620     #  @ingroup l2_modif_extrurev
3621     def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3622                               MakeGroups=False, TotalAngle=False):
3623         return self.RotationSweepObjects([],theObject,[], Axis,
3624                                          AngleInRadians, NbOfSteps, Tolerance,
3625                                          MakeGroups, TotalAngle)
3626
3627     ## Generates new elements by rotation of the elements of object around the axis
3628     #  @param theObject object which elements should be sweeped.
3629     #                   It can be a mesh, a sub mesh or a group.
3630     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3631     #  @param AngleInRadians the angle of Rotation
3632     #  @param NbOfSteps number of steps
3633     #  @param Tolerance tolerance
3634     #  @param MakeGroups forces the generation of new groups from existing ones
3635     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3636     #                    of all steps, else - size of each step
3637     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3638     #  @ingroup l2_modif_extrurev
3639     def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3640                               MakeGroups=False, TotalAngle=False):
3641         return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3642                                          NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3643
3644     ## Generates new elements by extrusion of the given elements and nodes
3645     #  @param nodes - nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3646     #  @param edges - edges to extrude: a list including ids, groups, sub-meshes or a mesh
3647     #  @param faces - faces to extrude: a list including ids, groups, sub-meshes or a mesh
3648     #  @param StepVector vector or DirStruct or 3 vector components, defining
3649     #         the direction and value of extrusion for one step (the total extrusion
3650     #         length will be NbOfSteps * ||StepVector||)
3651     #  @param NbOfSteps the number of steps
3652     #  @param MakeGroups forces the generation of new groups from existing ones
3653     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3654     #  @ingroup l2_modif_extrurev
3655     def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False):
3656         unRegister = genObjUnRegister()
3657         nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3658         edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3659         faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3660
3661         if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3662             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3663         if isinstance( StepVector, list ):
3664             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3665
3666         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3667         Parameters = StepVector.PS.parameters + var_separator + Parameters
3668         self.mesh.SetParameters(Parameters)
3669
3670         return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
3671                                                   StepVector, NbOfSteps, MakeGroups)
3672
3673
3674     ## Generates new elements by extrusion of the elements with given ids
3675     #  @param IDsOfElements the list of elements ids for extrusion
3676     #  @param StepVector vector or DirStruct or 3 vector components, defining
3677     #         the direction and value of extrusion for one step (the total extrusion
3678     #         length will be NbOfSteps * ||StepVector||)
3679     #  @param NbOfSteps the number of steps
3680     #  @param MakeGroups forces the generation of new groups from existing ones
3681     #  @param IsNodes is True if elements with given ids are nodes
3682     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3683     #  @ingroup l2_modif_extrurev
3684     def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3685         n,e,f = [],[],[]
3686         if IsNodes: n = IDsOfElements
3687         else      : e,f, = IDsOfElements,IDsOfElements
3688         return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3689
3690     ## Generates new elements by extrusion along the normal to a discretized surface or wire
3691     #  @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh
3692     #         Only faces can be extruded so far. Sub-mesh should be a sub-mesh on geom faces.
3693     #  @param StepSize length of one extrusion step (the total extrusion
3694     #         length will be \a NbOfSteps * \a StepSize ).
3695     #  @param NbOfSteps number of extrusion steps.
3696     #  @param ByAverageNormal if True each node is translated by \a StepSize
3697     #         along the average of the normal vectors to the faces sharing the node;
3698     #         else each node is translated along the same average normal till
3699     #         intersection with the plane got by translation of the face sharing
3700     #         the node along its own normal by \a StepSize.
3701     #  @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3702     #         for every node of \a Elements.
3703     #  @param MakeGroups forces generation of new groups from existing ones.
3704     #  @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
3705     #         is not yet implemented. This parameter is used if \a Elements contains
3706     #         both faces and edges, i.e. \a Elements is a Mesh.
3707     #  @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
3708     #          empty list otherwise.
3709     #  @ingroup l2_modif_extrurev
3710     def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
3711                           ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
3712         unRegister = genObjUnRegister()
3713         if isinstance( Elements, Mesh ):
3714             Elements = [ Elements.GetMesh() ]
3715         if isinstance( Elements, list ):
3716             if not Elements:
3717                 raise RuntimeError, "Elements empty!"
3718             if isinstance( Elements[0], int ):
3719                 Elements = self.GetIDSource( Elements, SMESH.ALL )
3720                 unRegister.set( Elements )
3721         if not isinstance( Elements, list ):
3722             Elements = [ Elements ]
3723         StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
3724         self.mesh.SetParameters(Parameters)
3725         return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
3726                                              ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
3727
3728     ## Generates new elements by extrusion of the elements which belong to the object
3729     #  @param theObject the object which elements should be processed.
3730     #                   It can be a mesh, a sub mesh or a group.
3731     #  @param StepVector vector or DirStruct or 3 vector components, defining
3732     #         the direction and value of extrusion for one step (the total extrusion
3733     #         length will be NbOfSteps * ||StepVector||)
3734     #  @param NbOfSteps the number of steps
3735     #  @param MakeGroups forces the generation of new groups from existing ones
3736     #  @param  IsNodes is True if elements to extrude are nodes
3737     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3738     #  @ingroup l2_modif_extrurev
3739     def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3740         n,e,f = [],[],[]
3741         if IsNodes: n    = theObject
3742         else      : e,f, = theObject,theObject
3743         return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3744
3745     ## Generates new elements by extrusion of the elements which belong to the object
3746     #  @param theObject object which elements should be processed.
3747     #                   It can be a mesh, a sub mesh or a group.
3748     #  @param StepVector vector or DirStruct or 3 vector components, defining
3749     #         the direction and value of extrusion for one step (the total extrusion
3750     #         length will be NbOfSteps * ||StepVector||)
3751     #  @param NbOfSteps the number of steps
3752     #  @param MakeGroups to generate new groups from existing ones
3753     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3754     #  @ingroup l2_modif_extrurev
3755     def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3756         return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
3757
3758     ## Generates new elements by extrusion of the elements which belong to the object
3759     #  @param theObject object which elements should be processed.
3760     #                   It can be a mesh, a sub mesh or a group.
3761     #  @param StepVector vector or DirStruct or 3 vector components, defining
3762     #         the direction and value of extrusion for one step (the total extrusion
3763     #         length will be NbOfSteps * ||StepVector||)
3764     #  @param NbOfSteps the number of steps
3765     #  @param MakeGroups forces the generation of new groups from existing ones
3766     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3767     #  @ingroup l2_modif_extrurev
3768     def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3769         return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
3770
3771     ## Generates new elements by extrusion of the elements with given ids
3772     #  @param IDsOfElements is ids of elements
3773     #  @param StepVector vector or DirStruct or 3 vector components, defining
3774     #         the direction and value of extrusion for one step (the total extrusion
3775     #         length will be NbOfSteps * ||StepVector||)
3776     #  @param NbOfSteps the number of steps
3777     #  @param ExtrFlags sets flags for extrusion
3778     #  @param SewTolerance uses for comparing locations of nodes if flag
3779     #         EXTRUSION_FLAG_SEW is set
3780     #  @param MakeGroups forces the generation of new groups from existing ones
3781     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3782     #  @ingroup l2_modif_extrurev
3783     def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3784                           ExtrFlags, SewTolerance, MakeGroups=False):
3785         if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3786             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3787         if isinstance( StepVector, list ):
3788             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3789         return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3790                                              ExtrFlags, SewTolerance, MakeGroups)
3791
3792     ## Generates new elements by extrusion of the given elements and nodes along the path.
3793     #  The path of extrusion must be a meshed edge.
3794     #  @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3795     #  @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3796     #  @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3797     #  @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3798     #  @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
3799     #         contains not only path segments, else it can be None
3800     #  @param NodeStart the first or the last node on the path. Defines the direction of extrusion
3801     #  @param HasAngles allows the shape to be rotated around the path
3802     #                   to get the resulting mesh in a helical fashion
3803     #  @param Angles list of angles
3804     #  @param LinearVariation forces the computation of rotation angles as linear
3805     #                         variation of the given Angles along path steps
3806     #  @param HasRefPoint allows using the reference point
3807     #  @param RefPoint the point around which the shape is rotated (the mass center of the
3808     #         shape by default). The User can specify any point as the Reference Point.
3809     #  @param MakeGroups forces the generation of new groups from existing ones
3810     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
3811     #  @ingroup l2_modif_extrurev
3812     def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
3813                                   NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
3814                                   HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
3815         unRegister = genObjUnRegister()
3816         Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
3817         Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
3818         Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
3819
3820         if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3821             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3822         if isinstance( RefPoint, list ):
3823             RefPoint = SMESH.PointStruct( *RefPoint )
3824         if isinstance( PathMesh, Mesh ):
3825             PathMesh = PathMesh.GetMesh()
3826         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3827         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3828         self.mesh.SetParameters(Parameters)
3829         return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
3830                                                      PathMesh, PathShape, NodeStart,
3831                                                      HasAngles, Angles, LinearVariation,
3832                                                      HasRefPoint, RefPoint, MakeGroups)
3833
3834     ## Generates new elements by extrusion of the given elements
3835     #  The path of extrusion must be a meshed edge.
3836     #  @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3837     #  @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3838     #  @param NodeStart the start node from Path. Defines the direction of extrusion
3839     #  @param HasAngles allows the shape to be rotated around the path
3840     #                   to get the resulting mesh in a helical fashion
3841     #  @param Angles list of angles in radians
3842     #  @param LinearVariation forces the computation of rotation angles as linear
3843     #                         variation of the given Angles along path steps
3844     #  @param HasRefPoint allows using the reference point
3845     #  @param RefPoint the point around which the elements are rotated (the mass
3846     #         center of the elements by default).
3847     #         The User can specify any point as the Reference Point.
3848     #         RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
3849     #  @param MakeGroups forces the generation of new groups from existing ones
3850     #  @param ElemType type of elements for extrusion (if param Base is a mesh)
3851     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3852     #          only SMESH::Extrusion_Error otherwise
3853     #  @ingroup l2_modif_extrurev
3854     def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3855                             HasAngles, Angles, LinearVariation,
3856                             HasRefPoint, RefPoint, MakeGroups, ElemType):
3857         n,e,f = [],[],[]
3858         if ElemType == SMESH.NODE: n = Base
3859         if ElemType == SMESH.EDGE: e = Base
3860         if ElemType == SMESH.FACE: f = Base
3861         gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
3862                                                HasAngles, Angles, LinearVariation,
3863                                                HasRefPoint, RefPoint, MakeGroups)
3864         if MakeGroups: return gr,er
3865         return er
3866
3867     ## Generates new elements by extrusion of the given elements
3868     #  The path of extrusion must be a meshed edge.
3869     #  @param IDsOfElements ids of elements
3870     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3871     #  @param PathShape shape(edge) defines the sub-mesh for the path
3872     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3873     #  @param HasAngles allows the shape to be rotated around the path
3874     #                   to get the resulting mesh in a helical fashion
3875     #  @param Angles list of angles in radians
3876     #  @param HasRefPoint allows using the reference point
3877     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3878     #         The User can specify any point as the Reference Point.
3879     #  @param MakeGroups forces the generation of new groups from existing ones
3880     #  @param LinearVariation forces the computation of rotation angles as linear
3881     #                         variation of the given Angles along path steps
3882     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3883     #          only SMESH::Extrusion_Error otherwise
3884     #  @ingroup l2_modif_extrurev
3885     def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3886                            HasAngles, Angles, HasRefPoint, RefPoint,
3887                            MakeGroups=False, LinearVariation=False):
3888         n,e,f = [],IDsOfElements,IDsOfElements
3889         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
3890                                                NodeStart, HasAngles, Angles,
3891                                                LinearVariation,
3892                                                HasRefPoint, RefPoint, MakeGroups)
3893         if MakeGroups: return gr,er
3894         return er
3895
3896     ## Generates new elements by extrusion of the elements which belong to the object
3897     #  The path of extrusion must be a meshed edge.
3898     #  @param theObject the object which elements should be processed.
3899     #                   It can be a mesh, a sub-mesh or a group.
3900     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3901     #  @param PathShape shape(edge) defines the sub-mesh for the path
3902     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3903     #  @param HasAngles allows the shape to be rotated around the path
3904     #                   to get the resulting mesh in a helical fashion
3905     #  @param Angles list of angles
3906     #  @param HasRefPoint allows using the reference point
3907     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3908     #         The User can specify any point as the Reference Point.
3909     #  @param MakeGroups forces the generation of new groups from existing ones
3910     #  @param LinearVariation forces the computation of rotation angles as linear
3911     #                         variation of the given Angles along path steps
3912     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3913     #          only SMESH::Extrusion_Error otherwise
3914     #  @ingroup l2_modif_extrurev
3915     def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
3916                                  HasAngles, Angles, HasRefPoint, RefPoint,
3917                                  MakeGroups=False, LinearVariation=False):
3918         n,e,f = [],theObject,theObject
3919         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
3920                                                HasAngles, Angles, LinearVariation,
3921                                                HasRefPoint, RefPoint, MakeGroups)
3922         if MakeGroups: return gr,er
3923         return er
3924
3925     ## Generates new elements by extrusion of the elements which belong to the object
3926     #  The path of extrusion must be a meshed edge.
3927     #  @param theObject the object which elements should be processed.
3928     #                   It can be a mesh, a sub mesh or a group.
3929     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3930     #  @param PathShape shape(edge) defines the sub-mesh for the path
3931     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3932     #  @param HasAngles allows the shape to be rotated around the path
3933     #                   to get the resulting mesh in a helical fashion
3934     #  @param Angles list of angles
3935     #  @param HasRefPoint allows using the reference point
3936     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3937     #         The User can specify any point as the Reference Point.
3938     #  @param MakeGroups forces the generation of new groups from existing ones
3939     #  @param LinearVariation forces the computation of rotation angles as linear
3940     #                         variation of the given Angles along path steps
3941     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3942     #          only SMESH::Extrusion_Error otherwise
3943     #  @ingroup l2_modif_extrurev
3944     def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
3945                                    HasAngles, Angles, HasRefPoint, RefPoint,
3946                                    MakeGroups=False, LinearVariation=False):
3947         n,e,f = [],theObject,[]
3948         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
3949                                                HasAngles, Angles, LinearVariation,
3950                                                HasRefPoint, RefPoint, MakeGroups)
3951         if MakeGroups: return gr,er
3952         return er
3953
3954     ## Generates new elements by extrusion of the elements which belong to the object
3955     #  The path of extrusion must be a meshed edge.
3956     #  @param theObject the object which elements should be processed.
3957     #                   It can be a mesh, a sub mesh or a group.
3958     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3959     #  @param PathShape shape(edge) defines the sub-mesh for the path
3960     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3961     #  @param HasAngles allows the shape to be rotated around the path
3962     #                   to get the resulting mesh in a helical fashion
3963     #  @param Angles list of angles
3964     #  @param HasRefPoint allows using the reference point
3965     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3966     #         The User can specify any point as the Reference Point.
3967     #  @param MakeGroups forces the generation of new groups from existing ones
3968     #  @param LinearVariation forces the computation of rotation angles as linear
3969     #                         variation of the given Angles along path steps
3970     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3971     #          only SMESH::Extrusion_Error otherwise
3972     #  @ingroup l2_modif_extrurev
3973     def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
3974                                    HasAngles, Angles, HasRefPoint, RefPoint,
3975                                    MakeGroups=False, LinearVariation=False):
3976         n,e,f = [],[],theObject
3977         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
3978                                                HasAngles, Angles, LinearVariation,
3979                                                HasRefPoint, RefPoint, MakeGroups)
3980         if MakeGroups: return gr,er
3981         return er
3982
3983     ## Creates a symmetrical copy of mesh elements
3984     #  @param IDsOfElements list of elements ids
3985     #  @param Mirror is AxisStruct or geom object(point, line, plane)
3986     #  @param theMirrorType is  POINT, AXIS or PLANE
3987     #  If the Mirror is a geom object this parameter is unnecessary
3988     #  @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
3989     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3990     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3991     #  @ingroup l2_modif_trsf
3992     def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
3993         if IDsOfElements == []:
3994             IDsOfElements = self.GetElementsId()
3995         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3996             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
3997             theMirrorType = Mirror._mirrorType
3998         else:
3999             self.mesh.SetParameters(Mirror.parameters)
4000         if Copy and MakeGroups:
4001             return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4002         self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4003         return []
4004
4005     ## Creates a new mesh by a symmetrical copy of mesh elements
4006     #  @param IDsOfElements the list of elements ids
4007     #  @param Mirror is AxisStruct or geom object (point, line, plane)
4008     #  @param theMirrorType is  POINT, AXIS or PLANE
4009     #  If the Mirror is a geom object this parameter is unnecessary
4010     #  @param MakeGroups to generate new groups from existing ones
4011     #  @param NewMeshName a name of the new mesh to create
4012     #  @return instance of Mesh class
4013     #  @ingroup l2_modif_trsf
4014     def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4015         if IDsOfElements == []:
4016             IDsOfElements = self.GetElementsId()
4017         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4018             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
4019             theMirrorType = Mirror._mirrorType
4020         else:
4021             self.mesh.SetParameters(Mirror.parameters)
4022         mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4023                                           MakeGroups, NewMeshName)
4024         return Mesh(self.smeshpyD,self.geompyD,mesh)
4025
4026     ## Creates a symmetrical copy of the object
4027     #  @param theObject mesh, submesh or group
4028     #  @param Mirror AxisStruct or geom object (point, line, plane)
4029     #  @param theMirrorType is  POINT, AXIS or PLANE
4030     #  If the Mirror is a geom object this parameter is unnecessary
4031     #  @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4032     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4033     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4034     #  @ingroup l2_modif_trsf
4035     def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4036         if ( isinstance( theObject, Mesh )):
4037             theObject = theObject.GetMesh()
4038         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4039             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
4040             theMirrorType = Mirror._mirrorType
4041         else:
4042             self.mesh.SetParameters(Mirror.parameters)
4043         if Copy and MakeGroups:
4044             return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4045         self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4046         return []
4047
4048     ## Creates a new mesh by a symmetrical copy of the object
4049     #  @param theObject mesh, submesh or group
4050     #  @param Mirror AxisStruct or geom object (point, line, plane)
4051     #  @param theMirrorType POINT, AXIS or PLANE
4052     #  If the Mirror is a geom object this parameter is unnecessary
4053     #  @param MakeGroups forces the generation of new groups from existing ones
4054     #  @param NewMeshName the name of the new mesh to create
4055     #  @return instance of Mesh class
4056     #  @ingroup l2_modif_trsf
4057     def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4058         if ( isinstance( theObject, Mesh )):
4059             theObject = theObject.GetMesh()
4060         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4061             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
4062             theMirrorType = Mirror._mirrorType
4063         else:
4064             self.mesh.SetParameters(Mirror.parameters)
4065         mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4066                                                 MakeGroups, NewMeshName)
4067         return Mesh( self.smeshpyD,self.geompyD,mesh )
4068
4069     ## Translates the elements
4070     #  @param IDsOfElements list of elements ids
4071     #  @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4072     #  @param Copy allows copying the translated elements
4073     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4074     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4075     #  @ingroup l2_modif_trsf
4076     def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4077         if IDsOfElements == []:
4078             IDsOfElements = self.GetElementsId()
4079         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4080             Vector = self.smeshpyD.GetDirStruct(Vector)
4081         if isinstance( Vector, list ):
4082             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4083         self.mesh.SetParameters(Vector.PS.parameters)
4084         if Copy and MakeGroups:
4085             return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4086         self.editor.Translate(IDsOfElements, Vector, Copy)
4087         return []
4088
4089     ## Creates a new mesh of translated elements
4090     #  @param IDsOfElements list of elements ids
4091     #  @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4092     #  @param MakeGroups forces the generation of new groups from existing ones
4093     #  @param NewMeshName the name of the newly created mesh
4094     #  @return instance of Mesh class
4095     #  @ingroup l2_modif_trsf
4096     def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4097         if IDsOfElements == []:
4098             IDsOfElements = self.GetElementsId()
4099         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4100             Vector = self.smeshpyD.GetDirStruct(Vector)
4101         if isinstance( Vector, list ):
4102             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4103         self.mesh.SetParameters(Vector.PS.parameters)
4104         mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4105         return Mesh ( self.smeshpyD, self.geompyD, mesh )
4106
4107     ## Translates the object
4108     #  @param theObject the object to translate (mesh, submesh, or group)
4109     #  @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4110     #  @param Copy allows copying the translated elements
4111     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4112     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4113     #  @ingroup l2_modif_trsf
4114     def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4115         if ( isinstance( theObject, Mesh )):
4116             theObject = theObject.GetMesh()
4117         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4118             Vector = self.smeshpyD.GetDirStruct(Vector)
4119         if isinstance( Vector, list ):
4120             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4121         self.mesh.SetParameters(Vector.PS.parameters)
4122         if Copy and MakeGroups:
4123             return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4124         self.editor.TranslateObject(theObject, Vector, Copy)
4125         return []
4126
4127     ## Creates a new mesh from the translated object
4128     #  @param theObject the object to translate (mesh, submesh, or group)
4129     #  @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4130     #  @param MakeGroups forces the generation of new groups from existing ones
4131     #  @param NewMeshName the name of the newly created mesh
4132     #  @return instance of Mesh class
4133     #  @ingroup l2_modif_trsf
4134     def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4135         if isinstance( theObject, Mesh ):
4136             theObject = theObject.GetMesh()
4137         if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4138             Vector = self.smeshpyD.GetDirStruct(Vector)
4139         if isinstance( Vector, list ):
4140             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4141         self.mesh.SetParameters(Vector.PS.parameters)
4142         mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4143         return Mesh( self.smeshpyD, self.geompyD, mesh )
4144
4145
4146
4147     ## Scales the object
4148     #  @param theObject - the object to translate (mesh, submesh, or group)
4149     #  @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4150     #  @param theScaleFact - list of 1-3 scale factors for axises
4151     #  @param Copy - allows copying the translated elements
4152     #  @param MakeGroups - forces the generation of new groups from existing
4153     #                      ones (if Copy)
4154     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4155     #          empty list otherwise
4156     def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4157         unRegister = genObjUnRegister()
4158         if ( isinstance( theObject, Mesh )):
4159             theObject = theObject.GetMesh()
4160         if ( isinstance( theObject, list )):
4161             theObject = self.GetIDSource(theObject, SMESH.ALL)
4162             unRegister.set( theObject )
4163         if ( isinstance( thePoint, list )):
4164             thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4165         if ( isinstance( theScaleFact, float )):
4166              theScaleFact = [theScaleFact]
4167         if ( isinstance( theScaleFact, int )):
4168              theScaleFact = [ float(theScaleFact)]
4169
4170         self.mesh.SetParameters(thePoint.parameters)
4171
4172         if Copy and MakeGroups:
4173             return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4174         self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4175         return []
4176
4177     ## Creates a new mesh from the translated object
4178     #  @param theObject - the object to translate (mesh, submesh, or group)
4179     #  @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4180     #  @param theScaleFact - list of 1-3 scale factors for axises
4181     #  @param MakeGroups - forces the generation of new groups from existing ones
4182     #  @param NewMeshName - the name of the newly created mesh
4183     #  @return instance of Mesh class
4184     def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4185         unRegister = genObjUnRegister()
4186         if (isinstance(theObject, Mesh)):
4187             theObject = theObject.GetMesh()
4188         if ( isinstance( theObject, list )):
4189             theObject = self.GetIDSource(theObject,SMESH.ALL)
4190             unRegister.set( theObject )
4191         if ( isinstance( thePoint, list )):
4192             thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4193         if ( isinstance( theScaleFact, float )):
4194              theScaleFact = [theScaleFact]
4195         if ( isinstance( theScaleFact, int )):
4196              theScaleFact = [ float(theScaleFact)]
4197
4198         self.mesh.SetParameters(thePoint.parameters)
4199         mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4200                                          MakeGroups, NewMeshName)
4201         return Mesh( self.smeshpyD, self.geompyD, mesh )
4202
4203
4204
4205     ## Rotates the elements
4206     #  @param IDsOfElements list of elements ids
4207     #  @param Axis the axis of rotation (AxisStruct or geom line)
4208     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4209     #  @param Copy allows copying the rotated elements
4210     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4211     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4212     #  @ingroup l2_modif_trsf
4213     def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4214         if IDsOfElements == []:
4215             IDsOfElements = self.GetElementsId()
4216         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4217             Axis = self.smeshpyD.GetAxisStruct(Axis)
4218         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4219         Parameters = Axis.parameters + var_separator + Parameters
4220         self.mesh.SetParameters(Parameters)
4221         if Copy and MakeGroups:
4222             return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4223         self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4224         return []
4225
4226     ## Creates a new mesh of rotated elements
4227     #  @param IDsOfElements list of element ids
4228     #  @param Axis the axis of rotation (AxisStruct or geom line)
4229     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4230     #  @param MakeGroups forces the generation of new groups from existing ones
4231     #  @param NewMeshName the name of the newly created mesh
4232     #  @return instance of Mesh class
4233     #  @ingroup l2_modif_trsf
4234     def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4235         if IDsOfElements == []:
4236             IDsOfElements = self.GetElementsId()
4237         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4238             Axis = self.smeshpyD.GetAxisStruct(Axis)
4239         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4240         Parameters = Axis.parameters + var_separator + Parameters
4241         self.mesh.SetParameters(Parameters)
4242         mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4243                                           MakeGroups, NewMeshName)
4244         return Mesh( self.smeshpyD, self.geompyD, mesh )
4245
4246     ## Rotates the object
4247     #  @param theObject the object to rotate( mesh, submesh, or group)
4248     #  @param Axis the axis of rotation (AxisStruct or geom line)
4249     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4250     #  @param Copy allows copying the rotated elements
4251     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4252     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4253     #  @ingroup l2_modif_trsf
4254     def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4255         if (isinstance(theObject, Mesh)):
4256             theObject = theObject.GetMesh()
4257         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4258             Axis = self.smeshpyD.GetAxisStruct(Axis)
4259         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4260         Parameters = Axis.parameters + ":" + Parameters
4261         self.mesh.SetParameters(Parameters)
4262         if Copy and MakeGroups:
4263             return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4264         self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4265         return []
4266
4267     ## Creates a new mesh from the rotated object
4268     #  @param theObject the object to rotate (mesh, submesh, or group)
4269     #  @param Axis the axis of rotation (AxisStruct or geom line)
4270     #  @param AngleInRadians the angle of rotation (in radians)  or a name of variable which defines angle in degrees
4271     #  @param MakeGroups forces the generation of new groups from existing ones
4272     #  @param NewMeshName the name of the newly created mesh
4273     #  @return instance of Mesh class
4274     #  @ingroup l2_modif_trsf
4275     def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4276         if (isinstance( theObject, Mesh )):
4277             theObject = theObject.GetMesh()
4278         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4279             Axis = self.smeshpyD.GetAxisStruct(Axis)
4280         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4281         Parameters = Axis.parameters + ":" + Parameters
4282         mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4283                                                        MakeGroups, NewMeshName)
4284         self.mesh.SetParameters(Parameters)
4285         return Mesh( self.smeshpyD, self.geompyD, mesh )
4286
4287     ## Finds groups of adjacent nodes within Tolerance.
4288     #  @param Tolerance the value of tolerance
4289     #  @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4290     #  @ingroup l2_modif_trsf
4291     def FindCoincidentNodes (self, Tolerance):
4292         return self.editor.FindCoincidentNodes(Tolerance)
4293
4294     ## Finds groups of ajacent nodes within Tolerance.
4295     #  @param Tolerance the value of tolerance
4296     #  @param SubMeshOrGroup SubMesh or Group
4297     #  @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4298     #  @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4299     #  @ingroup l2_modif_trsf
4300     def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance, exceptNodes=[]):
4301         unRegister = genObjUnRegister()
4302         if (isinstance( SubMeshOrGroup, Mesh )):
4303             SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4304         if not isinstance( exceptNodes, list):
4305             exceptNodes = [ exceptNodes ]
4306         if exceptNodes and isinstance( exceptNodes[0], int):
4307             exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE)]
4308             unRegister.set( exceptNodes )
4309         return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,exceptNodes)
4310
4311     ## Merges nodes
4312     #  @param GroupsOfNodes a list of pairs of nodes IDs for merging
4313     #         (e.g. [[1,12],[25,4]], then nodes 12 and 4 will be removed and replaced
4314     #         by nodes 1 and 25 correspondingly in all elements and groups
4315     #  @ingroup l2_modif_trsf
4316     def MergeNodes (self, GroupsOfNodes):
4317         self.editor.MergeNodes(GroupsOfNodes)
4318
4319     ## Finds the elements built on the same nodes.
4320     #  @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4321     #  @return the list of pairs of equal elements IDs (e.g. [[1,12],[25,4]])
4322     #  @ingroup l2_modif_trsf
4323     def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4324         if not MeshOrSubMeshOrGroup:
4325             MeshOrSubMeshOrGroup=self.mesh
4326         elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4327             MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4328         return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4329
4330     ## Merges elements in each given group.
4331     #  @param GroupsOfElementsID a list of pairs of elements IDs for merging
4332     #        (e.g. [[1,12],[25,4]], then elements 12 and 4 will be removed and
4333     #        replaced by elements 1 and 25 in all groups)
4334     #  @ingroup l2_modif_trsf
4335     def MergeElements(self, GroupsOfElementsID):
4336         self.editor.MergeElements(GroupsOfElementsID)
4337
4338     ## Leaves one element and removes all other elements built on the same nodes.
4339     #  @ingroup l2_modif_trsf
4340     def MergeEqualElements(self):
4341         self.editor.MergeEqualElements()
4342
4343     ## Sews free borders
4344     #  @return SMESH::Sew_Error
4345     #  @ingroup l2_modif_trsf
4346     def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4347                         FirstNodeID2, SecondNodeID2, LastNodeID2,
4348                         CreatePolygons, CreatePolyedrs):
4349         return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4350                                           FirstNodeID2, SecondNodeID2, LastNodeID2,
4351                                           CreatePolygons, CreatePolyedrs)
4352
4353     ## Sews conform free borders
4354     #  @return SMESH::Sew_Error
4355     #  @ingroup l2_modif_trsf
4356     def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4357                                FirstNodeID2, SecondNodeID2):
4358         return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4359                                                  FirstNodeID2, SecondNodeID2)
4360
4361     ## Sews border to side
4362     #  @return SMESH::Sew_Error
4363     #  @ingroup l2_modif_trsf
4364     def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4365                          FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4366         return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4367                                            FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4368
4369     ## Sews two sides of a mesh. The nodes belonging to Side1 are
4370     #  merged with the nodes of elements of Side2.
4371     #  The number of elements in theSide1 and in theSide2 must be
4372     #  equal and they should have similar nodal connectivity.
4373     #  The nodes to merge should belong to side borders and
4374     #  the first node should be linked to the second.
4375     #  @return SMESH::Sew_Error
4376     #  @ingroup l2_modif_trsf
4377     def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4378                          NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4379                          NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4380         return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4381                                            NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4382                                            NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4383
4384     ## Sets new nodes for the given element.
4385     #  @param ide the element id
4386     #  @param newIDs nodes ids
4387     #  @return If the number of nodes does not correspond to the type of element - returns false
4388     #  @ingroup l2_modif_edit
4389     def ChangeElemNodes(self, ide, newIDs):
4390         return self.editor.ChangeElemNodes(ide, newIDs)
4391
4392     ## If during the last operation of MeshEditor some nodes were
4393     #  created, this method returns the list of their IDs, \n
4394     #  if new nodes were not created - returns empty list
4395     #  @return the list of integer values (can be empty)
4396     #  @ingroup l1_auxiliary
4397     def GetLastCreatedNodes(self):
4398         return self.editor.GetLastCreatedNodes()
4399
4400     ## If during the last operation of MeshEditor some elements were
4401     #  created this method returns the list of their IDs, \n
4402     #  if new elements were not created - returns empty list
4403     #  @return the list of integer values (can be empty)
4404     #  @ingroup l1_auxiliary
4405     def GetLastCreatedElems(self):
4406         return self.editor.GetLastCreatedElems()
4407
4408     ## Clears sequences of nodes and elements created by mesh edition oparations
4409     #  @ingroup l1_auxiliary
4410     def ClearLastCreated(self):
4411         self.editor.ClearLastCreated()
4412
4413     ## Creates Duplicates given elements, i.e. creates new elements based on the 
4414     #  same nodes as the given ones.
4415     #  @param theElements - container of elements to duplicate. It can be a Mesh,
4416     #         sub-mesh, group, filter or a list of element IDs.
4417     # @param theGroupName - a name of group to contain the generated elements.
4418     #                    If a group with such a name already exists, the new elements
4419     #                    are added to the existng group, else a new group is created.
4420     #                    If \a theGroupName is empty, new elements are not added 
4421     #                    in any group.
4422     # @return a group where the new elements are added. None if theGroupName == "".
4423     #  @ingroup l2_modif_edit
4424     def DoubleElements(self, theElements, theGroupName=""):
4425         unRegister = genObjUnRegister()
4426         if isinstance( theElements, Mesh ):
4427             theElements = theElements.mesh
4428         elif isinstance( theElements, list ):
4429             theElements = self.GetIDSource( theElements, SMESH.ALL )
4430             unRegister.set( theElements )
4431         return self.editor.DoubleElements(theElements, theGroupName)
4432
4433     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4434     #  @param theNodes identifiers of nodes to be doubled
4435     #  @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4436     #         nodes. If list of element identifiers is empty then nodes are doubled but
4437     #         they not assigned to elements
4438     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4439     #  @ingroup l2_modif_edit
4440     def DoubleNodes(self, theNodes, theModifiedElems):
4441         return self.editor.DoubleNodes(theNodes, theModifiedElems)
4442
4443     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4444     #  This method provided for convenience works as DoubleNodes() described above.
4445     #  @param theNodeId identifiers of node to be doubled
4446     #  @param theModifiedElems identifiers of elements to be updated
4447     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4448     #  @ingroup l2_modif_edit
4449     def DoubleNode(self, theNodeId, theModifiedElems):
4450         return self.editor.DoubleNode(theNodeId, theModifiedElems)
4451
4452     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4453     #  This method provided for convenience works as DoubleNodes() described above.
4454     #  @param theNodes group of nodes to be doubled
4455     #  @param theModifiedElems group of elements to be updated.
4456     #  @param theMakeGroup forces the generation of a group containing new nodes.
4457     #  @return TRUE or a created group if operation has been completed successfully,
4458     #          FALSE or None otherwise
4459     #  @ingroup l2_modif_edit
4460     def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4461         if theMakeGroup:
4462             return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4463         return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4464
4465     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4466     #  This method provided for convenience works as DoubleNodes() described above.
4467     #  @param theNodes list of groups of nodes to be doubled
4468     #  @param theModifiedElems list of groups of elements to be updated.
4469     #  @param theMakeGroup forces the generation of a group containing new nodes.
4470     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4471     #  @ingroup l2_modif_edit
4472     def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4473         if theMakeGroup:
4474             return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4475         return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4476
4477     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4478     #  @param theElems - the list of elements (edges or faces) to be replicated
4479     #         The nodes for duplication could be found from these elements
4480     #  @param theNodesNot - list of nodes to NOT replicate
4481     #  @param theAffectedElems - the list of elements (cells and edges) to which the
4482     #         replicated nodes should be associated to.
4483     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4484     #  @ingroup l2_modif_edit
4485     def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4486         return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4487
4488     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4489     #  @param theElems - the list of elements (edges or faces) to be replicated
4490     #         The nodes for duplication could be found from these elements
4491     #  @param theNodesNot - list of nodes to NOT replicate
4492     #  @param theShape - shape to detect affected elements (element which geometric center
4493     #         located on or inside shape).
4494     #         The replicated nodes should be associated to affected elements.
4495     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4496     #  @ingroup l2_modif_edit
4497     def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4498         return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4499
4500     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4501     #  This method provided for convenience works as DoubleNodes() described above.
4502     #  @param theElems - group of of elements (edges or faces) to be replicated
4503     #  @param theNodesNot - group of nodes not to replicated
4504     #  @param theAffectedElems - group of elements to which the replicated nodes
4505     #         should be associated to.
4506     #  @param theMakeGroup forces the generation of a group containing new elements.
4507     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
4508     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
4509     #          FALSE or None otherwise
4510     #  @ingroup l2_modif_edit
4511     def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4512                              theMakeGroup=False, theMakeNodeGroup=False):
4513         if theMakeGroup or theMakeNodeGroup:
4514             twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4515                                                             theAffectedElems,
4516                                                             theMakeGroup, theMakeNodeGroup)
4517             if theMakeGroup and theMakeNodeGroup:
4518                 return twoGroups
4519             else:
4520                 return twoGroups[ int(theMakeNodeGroup) ]
4521         return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4522
4523     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4524     #  This method provided for convenience works as DoubleNodes() described above.
4525     #  @param theElems - group of of elements (edges or faces) to be replicated
4526     #  @param theNodesNot - group of nodes not to replicated
4527     #  @param theShape - shape to detect affected elements (element which geometric center
4528     #         located on or inside shape).
4529     #         The replicated nodes should be associated to affected elements.
4530     #  @ingroup l2_modif_edit
4531     def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4532         return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4533
4534     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4535     #  This method provided for convenience works as DoubleNodes() described above.
4536     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4537     #  @param theNodesNot - list of groups of nodes not to replicated
4538     #  @param theAffectedElems - group of elements to which the replicated nodes
4539     #         should be associated to.
4540     #  @param theMakeGroup forces the generation of a group containing new elements.
4541     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
4542     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
4543     #          FALSE or None otherwise
4544     #  @ingroup l2_modif_edit
4545     def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4546                              theMakeGroup=False, theMakeNodeGroup=False):
4547         if theMakeGroup or theMakeNodeGroup:
4548             twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4549                                                              theAffectedElems,
4550                                                              theMakeGroup, theMakeNodeGroup)
4551             if theMakeGroup and theMakeNodeGroup:
4552                 return twoGroups
4553             else:
4554                 return twoGroups[ int(theMakeNodeGroup) ]
4555         return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4556
4557     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4558     #  This method provided for convenience works as DoubleNodes() described above.
4559     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4560     #  @param theNodesNot - list of groups of nodes not to replicated
4561     #  @param theShape - shape to detect affected elements (element which geometric center
4562     #         located on or inside shape).
4563     #         The replicated nodes should be associated to affected elements.
4564     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4565     #  @ingroup l2_modif_edit
4566     def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4567         return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4568
4569     ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4570     #  This method is the first step of DoubleNodeElemGroupsInRegion.
4571     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4572     #  @param theNodesNot - list of groups of nodes not to replicated
4573     #  @param theShape - shape to detect affected elements (element which geometric center
4574     #         located on or inside shape).
4575     #         The replicated nodes should be associated to affected elements.
4576     #  @return groups of affected elements
4577     #  @ingroup l2_modif_edit
4578     def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4579         return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4580
4581     ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4582     # The list of groups must describe a partition of the mesh volumes.
4583     # The nodes of the internal faces at the boundaries of the groups are doubled.
4584     # In option, the internal faces are replaced by flat elements.
4585     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4586     # @param theDomains - list of groups of volumes
4587     # @param createJointElems - if TRUE, create the elements
4588     # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4589     #        the boundary between \a theDomains and the rest mesh
4590     # @return TRUE if operation has been completed successfully, FALSE otherwise
4591     def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4592        return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4593
4594     ## Double nodes on some external faces and create flat elements.
4595     # Flat elements are mainly used by some types of mechanic calculations.
4596     #
4597     # Each group of the list must be constituted of faces.
4598     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4599     # @param theGroupsOfFaces - list of groups of faces
4600     # @return TRUE if operation has been completed successfully, FALSE otherwise
4601     def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4602         return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4603     
4604     ## identify all the elements around a geom shape, get the faces delimiting the hole
4605     #
4606     def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4607         return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4608
4609     def _getFunctor(self, funcType ):
4610         fn = self.functors[ funcType._v ]
4611         if not fn:
4612             fn = self.smeshpyD.GetFunctor(funcType)
4613             fn.SetMesh(self.mesh)
4614             self.functors[ funcType._v ] = fn
4615         return fn
4616
4617     ## Returns value of a functor for a given element
4618     #  @param funcType an item of SMESH.FunctorType enum
4619     #  @param elemId element or node ID
4620     #  @param isElem @a elemId is ID of element or node
4621     #  @return the functor value or zero in case of invalid arguments
4622     def FunctorValue(self, funcType, elemId, isElem=True):
4623         fn = self._getFunctor( funcType )
4624         if fn.GetElementType() == self.GetElementType(elemId, isElem):
4625             val = fn.GetValue(elemId)
4626         else:
4627             val = 0
4628         return val
4629
4630     ## Get length of 1D element or sum of lengths of all 1D mesh elements
4631     #  @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4632     #  @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4633     #  @ingroup l1_measurements
4634     def GetLength(self, elemId=None):
4635         length = 0
4636         if elemId == None:
4637             length = self.smeshpyD.GetLength(self)
4638         else:
4639             length = self.FunctorValue(SMESH.FT_Length, elemId)
4640         return length
4641
4642     ## Get area of 2D element or sum of areas of all 2D mesh elements
4643     #  @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4644     #  @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4645     #  @ingroup l1_measurements
4646     def GetArea(self, elemId=None):
4647         area = 0
4648         if elemId == None:
4649             area = self.smeshpyD.GetArea(self)
4650         else:
4651             area = self.FunctorValue(SMESH.FT_Area, elemId)
4652         return area
4653
4654     ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4655     #  @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4656     #  @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4657     #  @ingroup l1_measurements
4658     def GetVolume(self, elemId=None):
4659         volume = 0
4660         if elemId == None:
4661             volume = self.smeshpyD.GetVolume(self)
4662         else:
4663             volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
4664         return volume
4665
4666     ## Get maximum element length.
4667     #  @param elemId mesh element ID
4668     #  @return element's maximum length value
4669     #  @ingroup l1_measurements
4670     def GetMaxElementLength(self, elemId):
4671         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4672             ftype = SMESH.FT_MaxElementLength3D
4673         else:
4674             ftype = SMESH.FT_MaxElementLength2D
4675         return self.FunctorValue(ftype, elemId)
4676
4677     ## Get aspect ratio of 2D or 3D element.
4678     #  @param elemId mesh element ID
4679     #  @return element's aspect ratio value
4680     #  @ingroup l1_measurements
4681     def GetAspectRatio(self, elemId):
4682         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4683             ftype = SMESH.FT_AspectRatio3D
4684         else:
4685             ftype = SMESH.FT_AspectRatio
4686         return self.FunctorValue(ftype, elemId)
4687
4688     ## Get warping angle of 2D element.
4689     #  @param elemId mesh element ID
4690     #  @return element's warping angle value
4691     #  @ingroup l1_measurements
4692     def GetWarping(self, elemId):
4693         return self.FunctorValue(SMESH.FT_Warping, elemId)
4694
4695     ## Get minimum angle of 2D element.
4696     #  @param elemId mesh element ID
4697     #  @return element's minimum angle value
4698     #  @ingroup l1_measurements
4699     def GetMinimumAngle(self, elemId):
4700         return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
4701
4702     ## Get taper of 2D element.
4703     #  @param elemId mesh element ID
4704     #  @return element's taper value
4705     #  @ingroup l1_measurements
4706     def GetTaper(self, elemId):
4707         return self.FunctorValue(SMESH.FT_Taper, elemId)
4708
4709     ## Get skew of 2D element.
4710     #  @param elemId mesh element ID
4711     #  @return element's skew value
4712     #  @ingroup l1_measurements
4713     def GetSkew(self, elemId):
4714         return self.FunctorValue(SMESH.FT_Skew, elemId)
4715
4716     ## Return minimal and maximal value of a given functor.
4717     #  @param funType a functor type, an item of SMESH.FunctorType enum
4718     #         (one of SMESH.FunctorType._items)
4719     #  @param meshPart a part of mesh (group, sub-mesh) to treat
4720     #  @return tuple (min,max)
4721     #  @ingroup l1_measurements
4722     def GetMinMax(self, funType, meshPart=None):
4723         unRegister = genObjUnRegister()
4724         if isinstance( meshPart, list ):
4725             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
4726             unRegister.set( meshPart )
4727         if isinstance( meshPart, Mesh ):
4728             meshPart = meshPart.mesh
4729         fun = self._getFunctor( funType )
4730         if fun:
4731             if meshPart:
4732                 hist = fun.GetLocalHistogram( 1, False, meshPart )
4733             else:
4734                 hist = fun.GetHistogram( 1, False )
4735             if hist:
4736                 return hist[0].min, hist[0].max
4737         return None
4738
4739     pass # end of Mesh class
4740
4741 ## class used to add to SMESH_MeshEditor methods removed from its CORBA API
4742 #
4743 class meshEditor(SMESH._objref_SMESH_MeshEditor):
4744     def __init__(self):
4745         SMESH._objref_SMESH_MeshEditor.__init__(self)
4746         self.mesh = None
4747     def __getattr__(self, name ): # method called if an attribute not found
4748         if not self.mesh:         # look for name() method in Mesh class
4749             self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
4750         if hasattr( self.mesh, name ):
4751             return getattr( self.mesh, name )
4752         if name == "ExtrusionAlongPathObjX":
4753             return getattr( self.mesh, "ExtrusionAlongPathX" )
4754         print name, "NOT FOUND"
4755         return None
4756     pass
4757 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
4758
4759 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4760 #
4761 class Pattern(SMESH._objref_SMESH_Pattern):
4762
4763     def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4764         decrFun = lambda i: i-1
4765         theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4766         theMesh.SetParameters(Parameters)
4767         return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4768
4769     def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4770         decrFun = lambda i: i-1
4771         theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4772         theMesh.SetParameters(Parameters)
4773         return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4774
4775 # Registering the new proxy for Pattern
4776 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4777
4778 ## Private class used to bind methods creating algorithms to the class Mesh
4779 #
4780 class algoCreator:
4781     def __init__(self):
4782         self.mesh = None
4783         self.defaultAlgoType = ""
4784         self.algoTypeToClass = {}
4785
4786     # Stores a python class of algorithm
4787     def add(self, algoClass):
4788         if type( algoClass ).__name__ == 'classobj' and \
4789            hasattr( algoClass, "algoType"):
4790             self.algoTypeToClass[ algoClass.algoType ] = algoClass
4791             if not self.defaultAlgoType and \
4792                hasattr( algoClass, "isDefault") and algoClass.isDefault:
4793                 self.defaultAlgoType = algoClass.algoType
4794             #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4795
4796     # creates a copy of self and assign mesh to the copy
4797     def copy(self, mesh):
4798         other = algoCreator()
4799         other.defaultAlgoType = self.defaultAlgoType
4800         other.algoTypeToClass  = self.algoTypeToClass
4801         other.mesh = mesh
4802         return other
4803
4804     # creates an instance of algorithm
4805     def __call__(self,algo="",geom=0,*args):
4806         algoType = self.defaultAlgoType
4807         for arg in args + (algo,geom):
4808             if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
4809                 geom = arg
4810             if isinstance( arg, str ) and arg:
4811                 algoType = arg
4812         if not algoType and self.algoTypeToClass:
4813             algoType = self.algoTypeToClass.keys()[0]
4814         if self.algoTypeToClass.has_key( algoType ):
4815             #print "Create algo",algoType
4816             return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4817         raise RuntimeError, "No class found for algo type %s" % algoType
4818         return None
4819
4820 # Private class used to substitute and store variable parameters of hypotheses.
4821 #
4822 class hypMethodWrapper:
4823     def __init__(self, hyp, method):
4824         self.hyp    = hyp
4825         self.method = method
4826         #print "REBIND:", method.__name__
4827         return
4828
4829     # call a method of hypothesis with calling SetVarParameter() before
4830     def __call__(self,*args):
4831         if not args:
4832             return self.method( self.hyp, *args ) # hypothesis method with no args
4833
4834         #print "MethWrapper.__call__",self.method.__name__, args
4835         try:
4836             parsed = ParseParameters(*args)     # replace variables with their values
4837             self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4838             result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4839         except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4840             # maybe there is a replaced string arg which is not variable
4841             result = self.method( self.hyp, *args )
4842         except ValueError, detail: # raised by ParseParameters()
4843             try:
4844                 result = self.method( self.hyp, *args )
4845             except omniORB.CORBA.BAD_PARAM:
4846                 raise ValueError, detail # wrong variable name
4847
4848         return result
4849     pass
4850
4851 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
4852 class genObjUnRegister:
4853
4854     def __init__(self, genObj=None):
4855         self.genObjList = []
4856         self.set( genObj )
4857         return
4858
4859     def set(self, genObj):
4860         "Store one or a list of of SALOME.GenericObj'es"
4861         if isinstance( genObj, list ):
4862             self.genObjList.extend( genObj )
4863         else:
4864             self.genObjList.append( genObj )
4865         return
4866
4867     def __del__(self):
4868         for genObj in self.genObjList:
4869             if genObj and hasattr( genObj, "UnRegister" ):
4870                 genObj.UnRegister()
4871
4872 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
4873     #
4874     #print "pluginName: ", pluginName
4875     pluginBuilderName = pluginName + "Builder"
4876     try:
4877         exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
4878     except Exception, e:
4879         from salome_utils import verbose
4880         if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
4881         continue
4882     exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
4883     plugin = eval( pluginBuilderName )
4884     #print "  plugin:" , str(plugin)
4885
4886     # add methods creating algorithms to Mesh
4887     for k in dir( plugin ):
4888         if k[0] == '_': continue
4889         algo = getattr( plugin, k )
4890         #print "             algo:", str(algo)
4891         if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
4892             #print "                     meshMethod:" , str(algo.meshMethod)
4893             if not hasattr( Mesh, algo.meshMethod ):
4894                 setattr( Mesh, algo.meshMethod, algoCreator() )
4895                 pass
4896             getattr( Mesh, algo.meshMethod ).add( algo )
4897             pass
4898         pass
4899     pass
4900 del pluginName