Salome HOME
Merge remote-tracking branch 'origin/master' into V8_5_BR
[modules/smesh.git] / src / SMESH_SWIG / smeshBuilder.py
1 # Copyright (C) 2007-2016  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 import salome
24 from salome.geom import geomBuilder
25
26 import SMESH # This is necessary for back compatibility
27 from   SMESH import *
28 from   salome.smesh.smesh_algorithm import Mesh_Algorithm
29
30 import SALOME
31 import SALOMEDS
32 import os
33
34 class MeshMeta(type):
35     """Private class used to workaround a problem that sometimes isinstance(m, Mesh) returns False
36     """
37     def __instancecheck__(cls, inst):
38         """Implement isinstance(inst, cls)."""
39         return any(cls.__subclasscheck__(c)
40                    for c in {type(inst), inst.__class__})
41
42     def __subclasscheck__(cls, sub):
43         """Implement issubclass(sub, cls)."""
44         return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
45
46 def DegreesToRadians(AngleInDegrees):
47     """Convert an angle from degrees to radians
48     """
49     from math import pi
50     return AngleInDegrees * pi / 180.0
51
52 import salome_notebook
53 notebook = salome_notebook.notebook
54 # Salome notebook variable separator
55 var_separator = ":"
56
57 def ParseParameters(*args):
58     """
59     Return list of variable values from salome notebook.
60     The last argument, if is callable, is used to modify values got from notebook
61     """
62     Result = []
63     Parameters = ""
64     hasVariables = False
65     varModifFun=None
66     if args and callable( args[-1] ):
67         args, varModifFun = args[:-1], args[-1]
68     for parameter in args:
69
70         Parameters += str(parameter) + var_separator
71
72         if isinstance(parameter,str):
73             # check if there is an inexistent variable name
74             if not notebook.isVariable(parameter):
75                 raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
76             parameter = notebook.get(parameter)
77             hasVariables = True
78             if varModifFun:
79                 parameter = varModifFun(parameter)
80                 pass
81             pass
82         Result.append(parameter)
83
84         pass
85     Parameters = Parameters[:-1]
86     Result.append( Parameters )
87     Result.append( hasVariables )
88     return Result
89
90 def ParseAngles(*args):
91     """
92     Parse parameters while converting variables to radians
93     """
94     return ParseParameters( *( args + (DegreesToRadians, )))
95
96 def __initPointStruct(point,*args):
97     """
98     Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
99     Parameters are stored in PointStruct.parameters attribute
100     """
101     point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
102     pass
103 SMESH.PointStruct.__init__ = __initPointStruct
104
105 def __initAxisStruct(ax,*args):
106     """
107     Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
108     Parameters are stored in AxisStruct.parameters attribute
109     """
110     if len( args ) != 6:
111         raise RuntimeError,\
112               "Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args ))
113     ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
114     pass
115 SMESH.AxisStruct.__init__ = __initAxisStruct
116
117 smeshPrecisionConfusion = 1.e-07
118 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
119     """Compare real values using smeshPrecisionConfusion as tolerance
120     """
121     if abs(val1 - val2) < tol:
122         return True
123     return False
124
125 NO_NAME = "NoName"
126
127 def GetName(obj):
128     """
129     Returns:
130         object name
131     """
132     if obj:
133         # object not null
134         if isinstance(obj, SALOMEDS._objref_SObject):
135             # study object
136             return obj.GetName()
137         try:
138             ior  = salome.orb.object_to_string(obj)
139         except:
140             ior = None
141         if ior:
142             # CORBA object
143             studies = salome.myStudyManager.GetOpenStudies()
144             for sname in studies:
145                 s = salome.myStudyManager.GetStudyByName(sname)
146                 if not s: continue
147                 sobj = s.FindObjectIOR(ior)
148                 if not sobj: continue
149                 return sobj.GetName()
150             if hasattr(obj, "GetName"):
151                 # unknown CORBA object, having GetName() method
152                 return obj.GetName()
153             else:
154                 # unknown CORBA object, no GetName() method
155                 return NO_NAME
156             pass
157         if hasattr(obj, "GetName"):
158             # unknown non-CORBA object, having GetName() method
159             return obj.GetName()
160         pass
161     raise RuntimeError, "Null or invalid object"
162
163 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
164     """
165     Print error message if a hypothesis was not assigned.
166     """
167     if isAlgo:
168         hypType = "algorithm"
169     else:
170         hypType = "hypothesis"
171         pass
172     reason = ""
173     if hasattr( status, "__getitem__" ):
174         status,reason = status[0],status[1]
175     if status == HYP_UNKNOWN_FATAL :
176         reason = "for unknown reason"
177     elif status == HYP_INCOMPATIBLE :
178         reason = "this hypothesis mismatches the algorithm"
179     elif status == HYP_NOTCONFORM :
180         reason = "a non-conform mesh would be built"
181     elif status == HYP_ALREADY_EXIST :
182         if isAlgo: return # it does not influence anything
183         reason = hypType + " of the same dimension is already assigned to this shape"
184     elif status == HYP_BAD_DIM :
185         reason = hypType + " mismatches the shape"
186     elif status == HYP_CONCURRENT :
187         reason = "there are concurrent hypotheses on sub-shapes"
188     elif status == HYP_BAD_SUBSHAPE :
189         reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
190     elif status == HYP_BAD_GEOMETRY:
191         reason = "the algorithm is not applicable to this geometry"
192     elif status == HYP_HIDDEN_ALGO:
193         reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
194     elif status == HYP_HIDING_ALGO:
195         reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
196     elif status == HYP_NEED_SHAPE:
197         reason = "algorithm can't work without shape"
198     elif status == HYP_INCOMPAT_HYPS:
199         pass
200     else:
201         return
202     where = geomName
203     if where:
204         where = '"%s"' % geomName
205         if mesh:
206             meshName = GetName( mesh )
207             if meshName and meshName != NO_NAME:
208                 where = '"%s" shape in "%s" mesh ' % ( geomName, meshName )
209     if status < HYP_UNKNOWN_FATAL and where:
210         print '"%s" was assigned to %s but %s' %( hypName, where, reason )
211     elif where:
212         print '"%s" was not assigned to %s : %s' %( hypName, where, reason )
213     else:
214         print '"%s" was not assigned : %s' %( hypName, reason )
215         pass
216
217 def AssureGeomPublished(mesh, geom, name=''):
218     """
219     Private method. Add geom (sub-shape of the main shape) into the study if not yet there
220     """
221     if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
222         return
223     if not geom.GetStudyEntry() and \
224            mesh.smeshpyD.GetCurrentStudy():
225         ## set the study
226         studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
227         if studyID != mesh.geompyD.myStudyId:
228             mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
229         ## get a name
230         if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
231             # for all groups SubShapeName() return "Compound_-1"
232             name = mesh.geompyD.SubShapeName(geom, mesh.geom)
233         if not name:
234             name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
235         ## publish
236         mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
237     return
238
239 def FirstVertexOnCurve(mesh, edge):
240     """
241     Returns:
242         the first vertex of a geometrical edge by ignoring orientation
243     """
244     vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
245     if not vv:
246         raise TypeError, "Given object has no vertices"
247     if len( vv ) == 1: return vv[0]
248     v0   = mesh.geompyD.MakeVertexOnCurve(edge,0.)
249     xyz  = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
250     xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
251     xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
252     dist1, dist2 = 0,0
253     for i in range(3):
254         dist1 += abs( xyz[i] - xyz1[i] )
255         dist2 += abs( xyz[i] - xyz2[i] )
256     if dist1 < dist2:
257         return vv[0]
258     else:
259         return vv[1]
260
261 smeshInst = None
262 """
263 Warning:
264     smeshInst is a singleton
265 """
266 engine = None
267 doLcc = False
268 created = False
269
270 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
271     """
272     This class allows to create, load or manipulate meshes.
273     It has a set of methods to create, load or copy meshes, to combine several meshes, etc.
274     It also has methods to get infos and measure meshes.
275     """
276
277     # MirrorType enumeration
278     POINT = SMESH_MeshEditor.POINT
279     AXIS =  SMESH_MeshEditor.AXIS
280     PLANE = SMESH_MeshEditor.PLANE
281
282     # Smooth_Method enumeration
283     LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
284     CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
285
286     PrecisionConfusion = smeshPrecisionConfusion
287
288     # TopAbs_State enumeration
289     [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
290
291     # Methods of splitting a hexahedron into tetrahedra
292     Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
293
294     def __new__(cls):
295         global engine
296         global smeshInst
297         global doLcc
298         #print "==== __new__", engine, smeshInst, doLcc
299
300         if smeshInst is None:
301             # smesh engine is either retrieved from engine, or created
302             smeshInst = engine
303             # Following test avoids a recursive loop
304             if doLcc:
305                 if smeshInst is not None:
306                     # smesh engine not created: existing engine found
307                     doLcc = False
308                 if doLcc:
309                     doLcc = False
310                     # FindOrLoadComponent called:
311                     # 1. CORBA resolution of server
312                     # 2. the __new__ method is called again
313                     #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
314                     smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
315             else:
316                 # FindOrLoadComponent not called
317                 if smeshInst is None:
318                     # smeshBuilder instance is created from lcc.FindOrLoadComponent
319                     #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
320                     smeshInst = super(smeshBuilder,cls).__new__(cls)
321                 else:
322                     # smesh engine not created: existing engine found
323                     #print "==== existing ", engine, smeshInst, doLcc
324                     pass
325             #print "====1 ", smeshInst
326             return smeshInst
327
328         #print "====2 ", smeshInst
329         return smeshInst
330
331     def __init__(self):
332         global created
333         #print "--------------- smeshbuilder __init__ ---", created
334         if not created:
335           created = True
336           SMESH._objref_SMESH_Gen.__init__(self)
337
338     def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
339         """
340         Dump component to the Python script
341             This method overrides IDL function to allow default values for the parameters.
342         """
343
344         return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
345
346     def SetDumpPythonHistorical(self, isHistorical):
347         """
348         Set mode of DumpPython(), *historical* or *snapshot*.
349             In the *historical* mode, the Python Dump script includes all commands
350             performed by SMESH engine. In the *snapshot* mode, commands
351             relating to objects removed from the Study are excluded from the script
352             as well as commands not influencing the current state of meshes
353         """
354
355         if isHistorical: val = "true"
356         else:            val = "false"
357         SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
358
359     def init_smesh(self,theStudy,geompyD = None):
360         """
361         Set the current study and Geometry component
362         """
363
364         #print "init_smesh"
365         self.SetCurrentStudy(theStudy,geompyD)
366         if theStudy:
367             global notebook
368             notebook.myStudy = theStudy
369
370     def Mesh(self, obj=0, name=0):
371         """
372         Create a mesh. This can be either an empty mesh, possibly having an underlying geometry,
373         or a mesh wrapping a CORBA mesh given as a parameter.
374
375         Parameters:
376             obj: either (1) a CORBA mesh: (SMESH._objref_SMESH_Mesh) got e.g. by calling
377                 salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
378                 (2) a Geometrical object: for meshing or (3) none:.
379             name: the name for the new mesh.
380
381         Returns:
382             an instance of Mesh class.
383         """
384
385         if isinstance(obj,str):
386             obj,name = name,obj
387         return Mesh(self,self.geompyD,obj,name)
388
389     def EnumToLong(self,theItem):
390         """
391         Return a long value from enumeration
392         """
393
394         return theItem._v
395
396     def ColorToString(self,c):
397         """
398         Returns:
399             a string representation of the color.
400         To be used with filters.
401
402         Parametrs:
403             c: color value (SALOMEDS.Color)
404         """
405
406         val = ""
407         if isinstance(c, SALOMEDS.Color):
408             val = "%s;%s;%s" % (c.R, c.G, c.B)
409         elif isinstance(c, str):
410             val = c
411         else:
412             raise ValueError, "Color value should be of string or SALOMEDS.Color type"
413         return val
414
415     def GetPointStruct(self,theVertex):
416         """
417         Get PointStruct from vertex
418
419         Parameters:
420                 theVertex: a GEOM object(vertex)
421
422         Returns:
423                 SMESH.PointStruct
424         """
425
426         [x, y, z] = self.geompyD.PointCoordinates(theVertex)
427         return PointStruct(x,y,z)
428
429     def GetDirStruct(self,theVector):
430         """
431         Get DirStruct from vector
432
433         Parameters:
434                 theVector: a GEOM object(vector)
435
436         Returns:
437                 SMESH.DirStruct
438         """
439
440         vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
441         if(len(vertices) != 2):
442             print "Error: vector object is incorrect."
443             return None
444         p1 = self.geompyD.PointCoordinates(vertices[0])
445         p2 = self.geompyD.PointCoordinates(vertices[1])
446         pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
447         dirst = DirStruct(pnt)
448         return dirst
449
450     def MakeDirStruct(self,x,y,z):
451         """
452         Make DirStruct from a triplet
453
454         Parameters:
455                 x,y,z: vector components
456
457         Returns:
458                 SMESH.DirStruct
459         """
460
461         pnt = PointStruct(x,y,z)
462         return DirStruct(pnt)
463
464     def GetAxisStruct(self,theObj):
465         """
466         Get AxisStruct from object
467
468         Parameters:
469             theObj: a GEOM object (line or plane)
470
471         Returns:
472             SMESH.AxisStruct
473         """
474         import GEOM
475         edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
476         axis = None
477         if len(edges) > 1:
478             vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
479             vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
480             vertex1 = self.geompyD.PointCoordinates(vertex1)
481             vertex2 = self.geompyD.PointCoordinates(vertex2)
482             vertex3 = self.geompyD.PointCoordinates(vertex3)
483             vertex4 = self.geompyD.PointCoordinates(vertex4)
484             v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
485             v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
486             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] ]
487             axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
488             axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
489         elif len(edges) == 1:
490             vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
491             p1 = self.geompyD.PointCoordinates( vertex1 )
492             p2 = self.geompyD.PointCoordinates( vertex2 )
493             axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
494             axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
495         elif theObj.GetShapeType() == GEOM.VERTEX:
496             x,y,z = self.geompyD.PointCoordinates( theObj )
497             axis = AxisStruct( x,y,z, 1,0,0,)
498             axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
499         return axis
500
501     # From SMESH_Gen interface:
502     # ------------------------
503
504     def SetName(self, obj, name):
505         """
506         Set the given name to the object
507
508         Parameters:
509                 obj: the object to rename
510                 name: a new object name
511         """
512
513         if isinstance( obj, Mesh ):
514             obj = obj.GetMesh()
515         elif isinstance( obj, Mesh_Algorithm ):
516             obj = obj.GetAlgorithm()
517         ior  = salome.orb.object_to_string(obj)
518         SMESH._objref_SMESH_Gen.SetName(self, ior, name)
519
520     def SetEmbeddedMode( self,theMode ):
521         """
522         Set the current mode
523         """
524
525         SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
526
527     def IsEmbeddedMode(self):
528         """
529         Get the current mode
530         """
531
532         return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
533
534     def SetCurrentStudy( self, theStudy, geompyD = None ):
535         """
536         Set the current study. Calling SetCurrentStudy( None ) allows to
537                 switch OFF automatic pubilishing in the Study of mesh objects.
538         """
539
540         if not geompyD:
541             from salome.geom import geomBuilder
542             geompyD = geomBuilder.geom
543             pass
544         self.geompyD=geompyD
545         self.SetGeomEngine(geompyD)
546         SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
547         global notebook
548         if theStudy:
549             notebook = salome_notebook.NoteBook( theStudy )
550         else:
551             notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
552         if theStudy:
553             sb = theStudy.NewBuilder()
554             sc = theStudy.FindComponent("SMESH")
555             if sc: sb.LoadWith(sc, self)
556             pass
557         pass
558
559     def GetCurrentStudy(self):
560         """
561         Get the current study
562         """
563
564         return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
565
566     def CreateMeshesFromUNV( self,theFileName ):
567         """
568         Create a Mesh object importing data from the given UNV file
569
570         Returns:
571                 an instance of Mesh class
572         """
573
574         aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
575         aMesh = Mesh(self, self.geompyD, aSmeshMesh)
576         return aMesh
577
578     def CreateMeshesFromMED( self,theFileName ):
579         """
580         Create a Mesh object(s) importing data from the given MED file
581
582         Returns:
583                 a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
584         """
585
586         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
587         aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
588         return aMeshes, aStatus
589
590     def CreateMeshesFromSAUV( self,theFileName ):
591         """
592         Create a Mesh object(s) importing data from the given SAUV file
593
594         Returns:
595                 a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
596         """
597
598         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
599         aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
600         return aMeshes, aStatus
601
602     def CreateMeshesFromSTL( self, theFileName ):
603         """
604         Create a Mesh object importing data from the given STL file
605
606         Returns:
607                 an instance of Mesh class
608         """
609
610         aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
611         aMesh = Mesh(self, self.geompyD, aSmeshMesh)
612         return aMesh
613
614     def CreateMeshesFromCGNS( self, theFileName ):
615         """
616         Create Mesh objects importing data from the given CGNS file
617
618         Returns:
619                 a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
620         """
621
622         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
623         aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
624         return aMeshes, aStatus
625
626     def CreateMeshesFromGMF( self, theFileName ):
627         """
628         Create a Mesh object importing data from the given GMF file.
629         GMF files must have .mesh extension for the ASCII format and .meshb for
630         the binary format.
631
632         Returns:
633                 [ an instance of Mesh class, SMESH.ComputeError ]
634         """
635
636         aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
637                                                                         theFileName,
638                                                                         True)
639         if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
640         return Mesh(self, self.geompyD, aSmeshMesh), error
641
642     def Concatenate( self, meshes, uniteIdenticalGroups,
643                      mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
644                      name = ""):
645         """
646         Concatenate the given meshes into one mesh. All groups of input meshes will be
647                 present in the new mesh.
648
649         Parameters:
650                 meshes: the meshes, sub-meshes and groups to combine into one mesh
651                 uniteIdenticalGroups: if true, groups with same names are united, else they are renamed
652                 mergeNodesAndElements: if true, equal nodes and elements are merged
653                 mergeTolerance: tolerance for merging nodes
654                 allGroups: forces creation of groups corresponding to every input mesh
655                 name: name of a new mesh
656
657         Returns:
658                 an instance of Mesh class
659         """
660
661         if not meshes: return None
662         for i,m in enumerate(meshes):
663             if isinstance(m, Mesh):
664                 meshes[i] = m.GetMesh()
665         mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
666         meshes[0].SetParameters(Parameters)
667         if allGroups:
668             aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
669                 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
670         else:
671             aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
672                 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
673         aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
674         return aMesh
675
676     def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
677         """
678         Create a mesh by copying a part of another mesh.
679
680         Parameters:
681                 meshPart: a part of mesh to copy, either a Mesh, a sub-mesh or a group;
682                         to copy nodes or elements not contained in any mesh object,
683                         pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
684                 meshName: a name of the new mesh
685                 toCopyGroups: to create in the new mesh groups the copied elements belongs to
686                 toKeepIDs: to preserve order of the copied elements or not
687
688         Returns:
689                 an instance of Mesh class
690         """
691
692         if (isinstance( meshPart, Mesh )):
693             meshPart = meshPart.GetMesh()
694         mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
695         return Mesh(self, self.geompyD, mesh)
696
697     def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
698         """
699         Return IDs of sub-shapes
700
701         Returns:
702                 the list of integer values
703         """
704
705         return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
706
707     def GetPattern(self):
708         """
709         Create a pattern mapper.
710
711         Returns:
712                 an instance of SMESH_Pattern
713
714         `Example of Patterns usage <../tui_modifying_meshes_page.html#tui_pattern_mapping>`_
715         """
716
717         return SMESH._objref_SMESH_Gen.GetPattern(self)
718
719     def SetBoundaryBoxSegmentation(self, nbSegments):
720         """
721         Set number of segments per diagonal of boundary box of geometry, by which
722         default segment length of appropriate 1D hypotheses is defined in GUI.
723         Default value is 10.
724         """
725
726         SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
727
728     # Filtering. Auxiliary functions:
729     # ------------------------------
730
731     def GetEmptyCriterion(self):
732         """
733         Create an empty criterion
734
735         Returns:
736                 SMESH.Filter.Criterion
737         """
738
739         Type = self.EnumToLong(FT_Undefined)
740         Compare = self.EnumToLong(FT_Undefined)
741         Threshold = 0
742         ThresholdStr = ""
743         ThresholdID = ""
744         UnaryOp = self.EnumToLong(FT_Undefined)
745         BinaryOp = self.EnumToLong(FT_Undefined)
746         Tolerance = 1e-07
747         TypeOfElement = ALL
748         Precision = -1 ##@1e-07
749         return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
750                                 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
751
752     def GetCriterion(self,elementType,
753                      CritType,
754                      Compare = FT_EqualTo,
755                      Threshold="",
756                      UnaryOp=FT_Undefined,
757                      BinaryOp=FT_Undefined,
758                      Tolerance=1e-07):
759         """
760         Create a criterion by the given parameters
761         Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
762
763         Parameters:
764                 elementType: the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
765                 CritType: the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
766                         Type SMESH.FunctorType._items in the Python Console to see all values.
767                         Note that the items starting from FT_LessThan are not suitable for CritType.
768                 Compare:  belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
769                 Threshold: the threshold value (range of ids as string, shape, numeric)
770                 UnaryOp:  SMESH.FT_LogicalNOT or SMESH.FT_Undefined
771                 BinaryOp: a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or
772                         SMESH.FT_Undefined
773                 Tolerance: the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
774                         SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
775
776         Returns:
777                 SMESH.Filter.Criterion
778
779          href="../tui_filters_page.html#combining_filters"
780         """
781
782         if not CritType in SMESH.FunctorType._items:
783             raise TypeError, "CritType should be of SMESH.FunctorType"
784         aCriterion               = self.GetEmptyCriterion()
785         aCriterion.TypeOfElement = elementType
786         aCriterion.Type          = self.EnumToLong(CritType)
787         aCriterion.Tolerance     = Tolerance
788
789         aThreshold = Threshold
790
791         if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
792             aCriterion.Compare = self.EnumToLong(Compare)
793         elif Compare == "=" or Compare == "==":
794             aCriterion.Compare = self.EnumToLong(FT_EqualTo)
795         elif Compare == "<":
796             aCriterion.Compare = self.EnumToLong(FT_LessThan)
797         elif Compare == ">":
798             aCriterion.Compare = self.EnumToLong(FT_MoreThan)
799         elif Compare != FT_Undefined:
800             aCriterion.Compare = self.EnumToLong(FT_EqualTo)
801             aThreshold = Compare
802
803         if CritType in [FT_BelongToGeom,     FT_BelongToPlane, FT_BelongToGenSurface,
804                         FT_BelongToCylinder, FT_LyingOnGeom]:
805             # Check that Threshold is GEOM object
806             if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
807                 aCriterion.ThresholdStr = GetName(aThreshold)
808                 aCriterion.ThresholdID  = aThreshold.GetStudyEntry()
809                 if not aCriterion.ThresholdID:
810                     name = aCriterion.ThresholdStr
811                     if not name:
812                         name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
813                     aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
814             # or a name of GEOM object
815             elif isinstance( aThreshold, str ):
816                 aCriterion.ThresholdStr = aThreshold
817             else:
818                 raise TypeError, "The Threshold should be a shape."
819             if isinstance(UnaryOp,float):
820                 aCriterion.Tolerance = UnaryOp
821                 UnaryOp = FT_Undefined
822                 pass
823         elif CritType == FT_BelongToMeshGroup:
824             # Check that Threshold is a group
825             if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
826                 if aThreshold.GetType() != elementType:
827                     raise ValueError, "Group type mismatches Element type"
828                 aCriterion.ThresholdStr = aThreshold.GetName()
829                 aCriterion.ThresholdID  = salome.orb.object_to_string( aThreshold )
830                 study = self.GetCurrentStudy()
831                 if study:
832                     so = study.FindObjectIOR( aCriterion.ThresholdID )
833                     if so:
834                         entry = so.GetID()
835                         if entry:
836                             aCriterion.ThresholdID = entry
837             else:
838                 raise TypeError, "The Threshold should be a Mesh Group"
839         elif CritType == FT_RangeOfIds:
840             # Check that Threshold is string
841             if isinstance(aThreshold, str):
842                 aCriterion.ThresholdStr = aThreshold
843             else:
844                 raise TypeError, "The Threshold should be a string."
845         elif CritType == FT_CoplanarFaces:
846             # Check the Threshold
847             if isinstance(aThreshold, int):
848                 aCriterion.ThresholdID = str(aThreshold)
849             elif isinstance(aThreshold, str):
850                 ID = int(aThreshold)
851                 if ID < 1:
852                     raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
853                 aCriterion.ThresholdID = aThreshold
854             else:
855                 raise TypeError,\
856                       "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
857         elif CritType == FT_ConnectedElements:
858             # Check the Threshold
859             if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
860                 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
861                 if not aCriterion.ThresholdID:
862                     name = aThreshold.GetName()
863                     if not name:
864                         name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
865                     aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
866             elif isinstance(aThreshold, int): # node id
867                 aCriterion.Threshold = aThreshold
868             elif isinstance(aThreshold, list): # 3 point coordinates
869                 if len( aThreshold ) < 3:
870                     raise ValueError, "too few point coordinates, must be 3"
871                 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
872             elif isinstance(aThreshold, str):
873                 if aThreshold.isdigit():
874                     aCriterion.Threshold = aThreshold # node id
875                 else:
876                     aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
877             else:
878                 raise TypeError,\
879                       "The Threshold should either a VERTEX, or a node ID, "\
880                       "or a list of point coordinates and not '%s'"%aThreshold
881         elif CritType == FT_ElemGeomType:
882             # Check the Threshold
883             try:
884                 aCriterion.Threshold = self.EnumToLong(aThreshold)
885                 assert( aThreshold in SMESH.GeometryType._items )
886             except:
887                 if isinstance(aThreshold, int):
888                     aCriterion.Threshold = aThreshold
889                 else:
890                     raise TypeError, "The Threshold should be an integer or SMESH.GeometryType."
891                 pass
892             pass
893         elif CritType == FT_EntityType:
894             # Check the Threshold
895             try:
896                 aCriterion.Threshold = self.EnumToLong(aThreshold)
897                 assert( aThreshold in SMESH.EntityType._items )
898             except:
899                 if isinstance(aThreshold, int):
900                     aCriterion.Threshold = aThreshold
901                 else:
902                     raise TypeError, "The Threshold should be an integer or SMESH.EntityType."
903                 pass
904             pass
905
906         elif CritType == FT_GroupColor:
907             # Check the Threshold
908             try:
909                 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
910             except:
911                 raise TypeError, "The threshold value should be of SALOMEDS.Color type"
912             pass
913         elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
914                           FT_LinearOrQuadratic, FT_BadOrientedVolume,
915                           FT_BareBorderFace, FT_BareBorderVolume,
916                           FT_OverConstrainedFace, FT_OverConstrainedVolume,
917                           FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
918             # At this point the Threshold is unnecessary
919             if aThreshold ==  FT_LogicalNOT:
920                 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
921             elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
922                 aCriterion.BinaryOp = aThreshold
923         else:
924             # Check Threshold
925             try:
926                 aThreshold = float(aThreshold)
927                 aCriterion.Threshold = aThreshold
928             except:
929                 raise TypeError, "The Threshold should be a number."
930                 return None
931
932         if Threshold ==  FT_LogicalNOT or UnaryOp ==  FT_LogicalNOT:
933             aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
934
935         if Threshold in [FT_LogicalAND, FT_LogicalOR]:
936             aCriterion.BinaryOp = self.EnumToLong(Threshold)
937
938         if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
939             aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
940
941         if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
942             aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
943
944         return aCriterion
945
946     def GetFilter(self,elementType,
947                   CritType=FT_Undefined,
948                   Compare=FT_EqualTo,
949                   Threshold="",
950                   UnaryOp=FT_Undefined,
951                   Tolerance=1e-07,
952                   mesh=None):
953         """
954         Create a filter with the given parameters
955
956         Parameters:
957                 elementType: the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
958                 CritType: the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
959                         Type SMESH.FunctorType._items in the Python Console to see all values.
960                         Note that the items starting from FT_LessThan are not suitable for CritType.
961                 Compare: belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
962                 Threshold: the threshold value (range of ids as string, shape, numeric)
963                 UnaryOp:  SMESH.FT_LogicalNOT or SMESH.FT_Undefined
964                 Tolerance: the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
965                         SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
966                 mesh: the mesh to initialize the filter with
967
968         Returns:
969                 SMESH_Filter
970
971         `Example of Filters usage <../tui_filters_page.html#tui_filters>`_
972         """
973
974         aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
975         aFilterMgr = self.CreateFilterManager()
976         aFilter = aFilterMgr.CreateFilter()
977         aCriteria = []
978         aCriteria.append(aCriterion)
979         aFilter.SetCriteria(aCriteria)
980         if mesh:
981             if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
982             else                       : aFilter.SetMesh( mesh )
983         aFilterMgr.UnRegister()
984         return aFilter
985
986     def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
987         """
988         Create a filter from criteria
989
990         Parameters:
991                 criteria: a list of criteria
992                 binOp: binary operator used when binary operator of criteria is undefined
993
994         Returns:
995                 SMESH_Filter
996
997         `Example of Filters usage <../tui_filters_page.html#tui_filters>`_
998         """
999
1000         for i in range( len( criteria ) - 1 ):
1001             if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
1002                 criteria[i].BinaryOp = self.EnumToLong( binOp )
1003         aFilterMgr = self.CreateFilterManager()
1004         aFilter = aFilterMgr.CreateFilter()
1005         aFilter.SetCriteria(criteria)
1006         aFilterMgr.UnRegister()
1007         return aFilter
1008
1009     def GetFunctor(self,theCriterion):
1010         """
1011         Create a numerical functor by its type
1012
1013         Parameters:
1014                 theCriterion: functor type - an item of SMESH.FunctorType enumeration.
1015                         Type SMESH.FunctorType._items in the Python Console to see all items.
1016                         Note that not all items correspond to numerical functors.
1017
1018         Returns:
1019                 SMESH_NumericalFunctor
1020         """
1021
1022         if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
1023             return theCriterion
1024         aFilterMgr = self.CreateFilterManager()
1025         functor = None
1026         if theCriterion == FT_AspectRatio:
1027             functor = aFilterMgr.CreateAspectRatio()
1028         elif theCriterion == FT_AspectRatio3D:
1029             functor = aFilterMgr.CreateAspectRatio3D()
1030         elif theCriterion == FT_Warping:
1031             functor = aFilterMgr.CreateWarping()
1032         elif theCriterion == FT_MinimumAngle:
1033             functor = aFilterMgr.CreateMinimumAngle()
1034         elif theCriterion == FT_Taper:
1035             functor = aFilterMgr.CreateTaper()
1036         elif theCriterion == FT_Skew:
1037             functor = aFilterMgr.CreateSkew()
1038         elif theCriterion == FT_Area:
1039             functor = aFilterMgr.CreateArea()
1040         elif theCriterion == FT_Volume3D:
1041             functor = aFilterMgr.CreateVolume3D()
1042         elif theCriterion == FT_MaxElementLength2D:
1043             functor = aFilterMgr.CreateMaxElementLength2D()
1044         elif theCriterion == FT_MaxElementLength3D:
1045             functor = aFilterMgr.CreateMaxElementLength3D()
1046         elif theCriterion == FT_MultiConnection:
1047             functor = aFilterMgr.CreateMultiConnection()
1048         elif theCriterion == FT_MultiConnection2D:
1049             functor = aFilterMgr.CreateMultiConnection2D()
1050         elif theCriterion == FT_Length:
1051             functor = aFilterMgr.CreateLength()
1052         elif theCriterion == FT_Length2D:
1053             functor = aFilterMgr.CreateLength2D()
1054         elif theCriterion == FT_Deflection2D:
1055             functor = aFilterMgr.CreateDeflection2D()
1056         elif theCriterion == FT_NodeConnectivityNumber:
1057             functor = aFilterMgr.CreateNodeConnectivityNumber()
1058         elif theCriterion == FT_BallDiameter:
1059             functor = aFilterMgr.CreateBallDiameter()
1060         else:
1061             print "Error: given parameter is not numerical functor type."
1062         aFilterMgr.UnRegister()
1063         return functor
1064
1065     def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
1066         """
1067         Create hypothesis
1068
1069         Parameters:
1070                 theHType: mesh hypothesis type (string)
1071                 theLibName: mesh plug-in library name
1072
1073         Returns:
1074                 created hypothesis instance
1075         """
1076         hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
1077
1078         if isinstance( hyp, SMESH._objref_SMESH_Algo ):
1079             return hyp
1080
1081         # wrap hypothesis methods
1082         #print "HYPOTHESIS", theHType
1083         for meth_name in dir( hyp.__class__ ):
1084             if not meth_name.startswith("Get") and \
1085                not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
1086                 method = getattr ( hyp.__class__, meth_name )
1087                 if callable(method):
1088                     setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
1089
1090         return hyp
1091
1092     def GetMeshInfo(self, obj):
1093         """
1094         Get the mesh statistic
1095
1096         Returns:
1097                 dictionary "element type" - "count of elements"
1098         """
1099
1100         if isinstance( obj, Mesh ):
1101             obj = obj.GetMesh()
1102         d = {}
1103         if hasattr(obj, "GetMeshInfo"):
1104             values = obj.GetMeshInfo()
1105             for i in range(SMESH.Entity_Last._v):
1106                 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1107             pass
1108         return d
1109
1110     def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1111         """
1112         Get minimum distance between two objects
1113
1114         If *src2* is None, and *id2* = 0, distance from *src1* / *id1* to the origin is computed.
1115         If *src2* None, and *id2* != 0, it is assumed that both *id1* and *id2* belong to *src1*.
1116
1117         Parameters:
1118                 src1: first source object
1119                 src2: second source object
1120                 id1: node/element id from the first source
1121                 id2: node/element id from the second (or first) source
1122                 isElem1: *True* if *id1* is element id, *False* if it is node id
1123                 isElem2: *True* if *id2* is element id, *False* if it is node id
1124
1125         Returns:
1126                 minimum distance value *GetMinDistance()*
1127         """
1128
1129         result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1130         if result is None:
1131             result = 0.0
1132         else:
1133             result = result.value
1134         return result
1135
1136     def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1137         """
1138         Get measure structure specifying minimum distance data between two objects
1139
1140         If *src2* is None, and *id2*  = 0, distance from *src1* / *id1* to the origin is computed.
1141         If *src2* is None, and *id2* != 0, it is assumed that both *id1* and *id2* belong to *src1*.
1142
1143
1144         Parameters:
1145                 src1: first source object
1146                 src2: second source object
1147                 id1: node/element id from the first source
1148                 id2: node/element id from the second (or first) source
1149                 isElem1: *True* if **id1** is element id, *False* if it is node id
1150                 isElem2: *True* if **id2** is element id, *False* if it is node id
1151
1152         Returns:
1153                 Measure structure or None if input data is invalid **MinDistance()**
1154         """
1155
1156         if isinstance(src1, Mesh): src1 = src1.mesh
1157         if isinstance(src2, Mesh): src2 = src2.mesh
1158         if src2 is None and id2 != 0: src2 = src1
1159         if not hasattr(src1, "_narrow"): return None
1160         src1 = src1._narrow(SMESH.SMESH_IDSource)
1161         if not src1: return None
1162         unRegister = genObjUnRegister()
1163         if id1 != 0:
1164             m = src1.GetMesh()
1165             e = m.GetMeshEditor()
1166             if isElem1:
1167                 src1 = e.MakeIDSource([id1], SMESH.FACE)
1168             else:
1169                 src1 = e.MakeIDSource([id1], SMESH.NODE)
1170             unRegister.set( src1 )
1171             pass
1172         if hasattr(src2, "_narrow"):
1173             src2 = src2._narrow(SMESH.SMESH_IDSource)
1174             if src2 and id2 != 0:
1175                 m = src2.GetMesh()
1176                 e = m.GetMeshEditor()
1177                 if isElem2:
1178                     src2 = e.MakeIDSource([id2], SMESH.FACE)
1179                 else:
1180                     src2 = e.MakeIDSource([id2], SMESH.NODE)
1181                 unRegister.set( src2 )
1182                 pass
1183             pass
1184         aMeasurements = self.CreateMeasurements()
1185         unRegister.set( aMeasurements )
1186         result = aMeasurements.MinDistance(src1, src2)
1187         return result
1188
1189     def BoundingBox(self, objects):
1190         """
1191         Get bounding box of the specified object(s)
1192
1193         Parameters:
1194                 objects: single source object or list of source objects
1195
1196         Returns:
1197                 tuple of six values (minX, minY, minZ, maxX, maxY, maxZ) **GetBoundingBox()**
1198         """
1199
1200         result = self.GetBoundingBox(objects)
1201         if result is None:
1202             result = (0.0,)*6
1203         else:
1204             result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1205         return result
1206
1207     def GetBoundingBox(self, objects):
1208         """
1209         Get measure structure specifying bounding box data of the specified object(s)
1210
1211         Parameters:
1212                 objects: single source object or list of source objects
1213
1214         Returns:
1215                 Measure structure **BoundingBox()**
1216         """
1217
1218         if isinstance(objects, tuple):
1219             objects = list(objects)
1220         if not isinstance(objects, list):
1221             objects = [objects]
1222         srclist = []
1223         for o in objects:
1224             if isinstance(o, Mesh):
1225                 srclist.append(o.mesh)
1226             elif hasattr(o, "_narrow"):
1227                 src = o._narrow(SMESH.SMESH_IDSource)
1228                 if src: srclist.append(src)
1229                 pass
1230             pass
1231         aMeasurements = self.CreateMeasurements()
1232         result = aMeasurements.BoundingBox(srclist)
1233         aMeasurements.UnRegister()
1234         return result
1235
1236     def GetLength(self, obj):
1237         """
1238         Get sum of lengths of all 1D elements in the mesh object.
1239
1240         Parameters:
1241                 obj: mesh, submesh or group
1242
1243         Returns:
1244                 sum of lengths of all 1D elements
1245         """
1246
1247         if isinstance(obj, Mesh): obj = obj.mesh
1248         if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1249         aMeasurements = self.CreateMeasurements()
1250         value = aMeasurements.Length(obj)
1251         aMeasurements.UnRegister()
1252         return value
1253
1254     def GetArea(self, obj):
1255         """
1256         Get sum of areas of all 2D elements in the mesh object.
1257
1258         Parameters:
1259                 obj: mesh, submesh or group
1260
1261         Returns:
1262                 sum of areas of all 2D elements
1263         """
1264
1265         if isinstance(obj, Mesh): obj = obj.mesh
1266         if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1267         aMeasurements = self.CreateMeasurements()
1268         value = aMeasurements.Area(obj)
1269         aMeasurements.UnRegister()
1270         return value
1271
1272     def GetVolume(self, obj):
1273         """
1274         Get sum of volumes of all 3D elements in the mesh object.
1275
1276         Parameters:
1277                 obj: mesh, submesh or group
1278
1279         Returns:
1280                 sum of volumes of all 3D elements
1281         """
1282
1283         if isinstance(obj, Mesh): obj = obj.mesh
1284         if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1285         aMeasurements = self.CreateMeasurements()
1286         value = aMeasurements.Volume(obj)
1287         aMeasurements.UnRegister()
1288         return value
1289
1290     def GetGravityCenter(self, obj):
1291         """
1292         Get gravity center of all nodes of the mesh object.
1293         
1294         Parameters:            
1295             obj: mesh, submesh or group
1296
1297         Returns:        
1298             Three components of the gravity center: x,y,z
1299         """
1300         if isinstance(obj, Mesh): obj = obj.mesh
1301         if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1302         aMeasurements = self.CreateMeasurements()
1303         pointStruct = aMeasurements.GravityCenter(obj)
1304         aMeasurements.UnRegister()
1305         return pointStruct.x, pointStruct.y, pointStruct.z
1306
1307     pass # end of class smeshBuilder
1308
1309 import omniORB
1310 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1311 """Registering the new proxy for SMESH_Gen"""
1312
1313
1314 def New( study, instance=None, instanceGeom=None):
1315     """
1316     Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1317     interface to create or load meshes.
1318
1319     Typical use is:
1320         import salome
1321         salome.salome_init()
1322         from salome.smesh import smeshBuilder
1323         smesh = smeshBuilder.New(salome.myStudy)
1324
1325     Parameters:
1326         study:         SALOME study, generally obtained by salome.myStudy.
1327         instance:      CORBA proxy of SMESH Engine. If None, the default Engine is used.
1328         instanceGeom:  CORBA proxy of GEOM  Engine. If None, the default Engine is used.
1329     Returns:
1330         smeshBuilder instance
1331     """
1332     global engine
1333     global smeshInst
1334     global doLcc
1335     engine = instance
1336     if engine is None:
1337       doLcc = True
1338     smeshInst = smeshBuilder()
1339     assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1340     smeshInst.init_smesh(study, instanceGeom)
1341     return smeshInst
1342
1343
1344 # Public class: Mesh
1345 # ==================
1346
1347 class Mesh:
1348     """
1349     This class allows defining and managing a mesh.
1350     It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1351     It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1352     new nodes and elements and by changing the existing entities), to get information
1353     about a mesh and to export a mesh in different formats.
1354     """
1355     __metaclass__ = MeshMeta
1356
1357     geom = 0
1358     mesh = 0
1359     editor = 0
1360
1361     def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1362         """
1363         Constructor
1364
1365         Create a mesh on the shape *obj* (or an empty mesh if *obj* is equal to 0) and
1366                 sets the GUI name of this mesh to *name*.
1367
1368         Parameters:
1369                 smeshpyD: an instance of smeshBuilder class
1370                 geompyD: an instance of geomBuilder class
1371                 obj: Shape to be meshed or SMESH_Mesh object
1372                 name: Study name of the mesh
1373         """
1374
1375         self.smeshpyD=smeshpyD
1376         self.geompyD=geompyD
1377         if obj is None:
1378             obj = 0
1379         objHasName = False
1380         if obj != 0:
1381             if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1382                 self.geom = obj
1383                 objHasName = True
1384                 # publish geom of mesh (issue 0021122)
1385                 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1386                     objHasName = False
1387                     studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1388                     if studyID != geompyD.myStudyId:
1389                         geompyD.init_geom( smeshpyD.GetCurrentStudy())
1390                         pass
1391                     if name:
1392                         geo_name = name + " shape"
1393                     else:
1394                         geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1395                     geompyD.addToStudy( self.geom, geo_name )
1396                 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1397
1398             elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1399                 self.SetMesh(obj)
1400         else:
1401             self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1402         if name:
1403             self.smeshpyD.SetName(self.mesh, name)
1404         elif objHasName:
1405             self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1406
1407         if not self.geom:
1408             self.geom = self.mesh.GetShapeToMesh()
1409
1410         self.editor   = self.mesh.GetMeshEditor()
1411         self.functors = [None] * SMESH.FT_Undefined._v
1412
1413         # set self to algoCreator's
1414         for attrName in dir(self):
1415             attr = getattr( self, attrName )
1416             if isinstance( attr, algoCreator ):
1417                 setattr( self, attrName, attr.copy( self ))
1418                 pass
1419             pass
1420         pass
1421
1422     def __del__(self):
1423         """
1424         Destructor. Clean-up resources
1425         """
1426         if self.mesh:
1427             #self.mesh.UnRegister()
1428             pass
1429         pass
1430
1431     def SetMesh(self, theMesh):
1432         """
1433         Initialize the Mesh object from an instance of SMESH_Mesh interface
1434
1435         Parameters:
1436                 theMesh: a SMESH_Mesh object
1437         """
1438
1439
1440         # do not call Register() as this prevents mesh servant deletion at closing study
1441         #if self.mesh: self.mesh.UnRegister()
1442         self.mesh = theMesh
1443         if self.mesh:
1444             #self.mesh.Register()
1445             self.geom = self.mesh.GetShapeToMesh()
1446         pass
1447
1448     def GetMesh(self):
1449         """
1450         Return the mesh, that is an instance of SMESH_Mesh interface
1451
1452         Returns:
1453                 a SMESH_Mesh object
1454         """
1455
1456         return self.mesh
1457
1458     def GetName(self):
1459         """
1460         Get the name of the mesh
1461
1462         Returns:
1463                 the name of the mesh as a string
1464         """
1465
1466         name = GetName(self.GetMesh())
1467         return name
1468
1469     def SetName(self, name):
1470         """
1471         Set a name to the mesh
1472
1473         Parameters:
1474                 name: a new name of the mesh
1475         """
1476
1477         self.smeshpyD.SetName(self.GetMesh(), name)
1478
1479     def GetSubMesh(self, geom, name):
1480         """
1481         Get a sub-mesh object associated to a *geom* geometrical object.
1482
1483         Parameters:
1484                 geom: a geometrical object (shape)
1485                 name: a name for the sub-mesh in the Object Browser
1486
1487         Returns:
1488                 an object of type SMESH.SMESH_subMesh, representing a part of mesh,
1489                         which lies on the given shape
1490
1491         The sub-mesh object gives access to the IDs of nodes and elements.
1492         The sub-mesh object has the following methods:
1493
1494                 - SMESH.SMESH_subMesh.GetNumberOfElements()
1495                 - SMESH.SMESH_subMesh.GetNumberOfNodes( all )
1496                 - SMESH.SMESH_subMesh.GetElementsId()
1497                 - SMESH.SMESH_subMesh.GetElementsByType( ElementType )
1498                 - SMESH.SMESH_subMesh.GetNodesId()
1499                 - SMESH.SMESH_subMesh.GetSubShape()
1500                 - SMESH.SMESH_subMesh.GetFather()
1501                 - SMESH.SMESH_subMesh.GetId()
1502
1503         Note:
1504                 A sub-mesh is implicitly created when a sub-shape is specified at
1505                         creating an algorithm, for example: algo1D = mesh.Segment(geom=Edge_1)
1506                         creates a sub-mesh on *Edge_1* and assign Wire Discretization algorithm to it.
1507                         The created sub-mesh can be retrieved from the algorithm:
1508                         submesh = algo1D.GetSubMesh()
1509         """
1510
1511         AssureGeomPublished( self, geom, name )
1512         submesh = self.mesh.GetSubMesh( geom, name )
1513         return submesh
1514
1515     def GetShape(self):
1516         """
1517         Return the shape associated to the mesh
1518
1519         Returns:
1520                 a GEOM_Object
1521         """
1522
1523         return self.geom
1524
1525     def SetShape(self, geom):
1526         """
1527         Associate the given shape to the mesh (entails the recreation of the mesh)
1528
1529         Parameters:
1530                 geom: the shape to be meshed (GEOM_Object)
1531         """
1532
1533         self.mesh = self.smeshpyD.CreateMesh(geom)
1534
1535     def Load(self):
1536         """
1537         Load mesh from the study after opening the study
1538         """
1539         self.mesh.Load()
1540
1541     def IsReadyToCompute(self, theSubObject):
1542         """
1543         Return true if the hypotheses are defined well
1544
1545         Parameters:
1546                 theSubObject: a sub-shape of a mesh shape
1547
1548         Returns:
1549                 True or False
1550         """
1551
1552         return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1553
1554     def GetAlgoState(self, theSubObject):
1555         """
1556         Return errors of hypotheses definition.
1557         The list of errors is empty if everything is OK.
1558
1559         Parameters:
1560                 theSubObject: a sub-shape of a mesh shape
1561
1562         Returns:
1563                 a list of errors
1564         """
1565
1566         return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1567
1568     def GetGeometryByMeshElement(self, theElementID, theGeomName):
1569         """
1570         Return a geometrical object on which the given element was built.
1571         The returned geometrical object, if not nil, is either found in the
1572         study or published by this method with the given name
1573
1574         Parameters:
1575             theElementID: the id of the mesh element
1576             theGeomName: the user-defined name of the geometrical object
1577
1578         Returns:
1579             GEOM::GEOM_Object instance
1580         """
1581
1582         return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1583
1584     def MeshDimension(self):
1585         """
1586         Return the mesh dimension depending on the dimension of the underlying shape
1587                 or, if the mesh is not based on any shape, basing on deimension of elements
1588
1589         Returns:
1590                 mesh dimension as an integer value [0,3]
1591         """
1592
1593         if self.mesh.HasShapeToMesh():
1594             shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1595             if len( shells ) > 0 :
1596                 return 3
1597             elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1598                 return 2
1599             elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1600                 return 1
1601             else:
1602                 return 0;
1603         else:
1604             if self.NbVolumes() > 0: return 3
1605             if self.NbFaces()   > 0: return 2
1606             if self.NbEdges()   > 0: return 1
1607         return 0
1608
1609     def Evaluate(self, geom=0):
1610         """
1611         Evaluate size of prospective mesh on a shape
1612
1613         Returns:
1614                 a list where i-th element is a number of elements of i-th SMESH.EntityType
1615                 To know predicted number of e.g. edges, inquire it this way
1616                 Evaluate()[ EnumToLong( Entity_Edge )]
1617         """
1618
1619         if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1620             if self.geom == 0:
1621                 geom = self.mesh.GetShapeToMesh()
1622             else:
1623                 geom = self.geom
1624         return self.smeshpyD.Evaluate(self.mesh, geom)
1625
1626
1627     def Compute(self, geom=0, discardModifs=False, refresh=False):
1628         """
1629         Compute the mesh and return the status of the computation
1630
1631         Parameters:
1632                 geom: geomtrical shape on which mesh data should be computed
1633                 discardModifs: if True and the mesh has been edited since
1634                         a last total re-compute and that may prevent successful partial re-compute,
1635                         then the mesh is cleaned before Compute()
1636                 refresh: if *True*, Object browser is automatically updated (when running in GUI)
1637
1638         Returns:
1639                 True or False
1640         """
1641
1642         if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1643             if self.geom == 0:
1644                 geom = self.mesh.GetShapeToMesh()
1645             else:
1646                 geom = self.geom
1647         ok = False
1648         try:
1649             if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1650                 self.mesh.Clear()
1651             ok = self.smeshpyD.Compute(self.mesh, geom)
1652         except SALOME.SALOME_Exception, ex:
1653             print "Mesh computation failed, exception caught:"
1654             print "    ", ex.details.text
1655         except:
1656             import traceback
1657             print "Mesh computation failed, exception caught:"
1658             traceback.print_exc()
1659         if True:#not ok:
1660             allReasons = ""
1661
1662             # Treat compute errors
1663             computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1664             shapeText = ""
1665             for err in computeErrors:
1666                 if self.mesh.HasShapeToMesh():
1667                     shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1668                 errText = ""
1669                 stdErrors = ["OK",                   #COMPERR_OK
1670                              "Invalid input mesh",   #COMPERR_BAD_INPUT_MESH
1671                              "std::exception",       #COMPERR_STD_EXCEPTION
1672                              "OCC exception",        #COMPERR_OCC_EXCEPTION
1673                              "..",                   #COMPERR_SLM_EXCEPTION
1674                              "Unknown exception",    #COMPERR_EXCEPTION
1675                              "Memory allocation problem", #COMPERR_MEMORY_PB
1676                              "Algorithm failed",     #COMPERR_ALGO_FAILED
1677                              "Unexpected geometry",  #COMPERR_BAD_SHAPE
1678                              "Warning",              #COMPERR_WARNING
1679                              "Computation cancelled",#COMPERR_CANCELED
1680                              "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1681                 if err.code > 0:
1682                     if err.code < len(stdErrors): errText = stdErrors[err.code]
1683                 else:
1684                     errText = "code %s" % -err.code
1685                 if errText: errText += ". "
1686                 errText += err.comment
1687                 if allReasons: allReasons += "\n"
1688                 if ok:
1689                     allReasons += '-  "%s"%s - %s' %(err.algoName, shapeText, errText)
1690                 else:
1691                     allReasons += '-  "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1692                 pass
1693
1694             # Treat hyp errors
1695             errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1696             for err in errors:
1697                 if err.isGlobalAlgo:
1698                     glob = "global"
1699                 else:
1700                     glob = "local"
1701                     pass
1702                 dim = err.algoDim
1703                 name = err.algoName
1704                 if len(name) == 0:
1705                     reason = '%s %sD algorithm is missing' % (glob, dim)
1706                 elif err.state == HYP_MISSING:
1707                     reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1708                               % (glob, dim, name, dim))
1709                 elif err.state == HYP_NOTCONFORM:
1710                     reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1711                 elif err.state == HYP_BAD_PARAMETER:
1712                     reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1713                               % ( glob, dim, name ))
1714                 elif err.state == HYP_BAD_GEOMETRY:
1715                     reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1716                               'geometry' % ( glob, dim, name ))
1717                 elif err.state == HYP_HIDDEN_ALGO:
1718                     reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1719                               'algorithm of upper dimension generating %sD mesh'
1720                               % ( glob, dim, name, glob, dim ))
1721                 else:
1722                     reason = ("For unknown reason. "
1723                               "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1724                     pass
1725                 if allReasons: allReasons += "\n"
1726                 allReasons += "-  " + reason
1727                 pass
1728             if not ok or allReasons != "":
1729                 msg = '"' + GetName(self.mesh) + '"'
1730                 if ok: msg += " has been computed with warnings"
1731                 else:  msg += " has not been computed"
1732                 if allReasons != "": msg += ":"
1733                 else:                msg += "."
1734                 print msg
1735                 print allReasons
1736             pass
1737         if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1738             if not isinstance( refresh, list): # not a call from subMesh.Compute()
1739                 smeshgui = salome.ImportComponentGUI("SMESH")
1740                 smeshgui.Init(self.mesh.GetStudyId())
1741                 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1742                 if refresh: salome.sg.updateObjBrowser(True)
1743
1744         return ok
1745
1746     def GetComputeErrors(self, shape=0 ):
1747         """
1748         Return a list of error messages (SMESH.ComputeError) of the last Compute()
1749         """
1750
1751         if shape == 0:
1752             shape = self.mesh.GetShapeToMesh()
1753         return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1754
1755     def GetSubShapeName(self, subShapeID ):
1756         """
1757         Return a name of a sub-shape by its ID
1758
1759         Parameters:
1760                 subShapeID: a unique ID of a sub-shape
1761
1762         Returns:
1763                 a string describing the sub-shape; possible variants:
1764
1765                         - "Face_12"    (published sub-shape)
1766                         - FACE #3      (not published sub-shape)
1767                         - sub-shape #3 (invalid sub-shape ID)
1768                         - #3           (error in this function)
1769         """
1770
1771         if not self.mesh.HasShapeToMesh():
1772             return ""
1773         try:
1774             shapeText = ""
1775             mainIOR  = salome.orb.object_to_string( self.GetShape() )
1776             for sname in salome.myStudyManager.GetOpenStudies():
1777                 s = salome.myStudyManager.GetStudyByName(sname)
1778                 if not s: continue
1779                 mainSO = s.FindObjectIOR(mainIOR)
1780                 if not mainSO: continue
1781                 if subShapeID == 1:
1782                     shapeText = '"%s"' % mainSO.GetName()
1783                 subIt = s.NewChildIterator(mainSO)
1784                 while subIt.More():
1785                     subSO = subIt.Value()
1786                     subIt.Next()
1787                     obj = subSO.GetObject()
1788                     if not obj: continue
1789                     go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1790                     if not go: continue
1791                     try:
1792                         ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1793                     except:
1794                         continue
1795                     if ids == subShapeID:
1796                         shapeText = '"%s"' % subSO.GetName()
1797                         break
1798             if not shapeText:
1799                 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1800                 if shape:
1801                     shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1802                 else:
1803                     shapeText = 'sub-shape #%s' % (subShapeID)
1804         except:
1805             shapeText = "#%s" % (subShapeID)
1806         return shapeText
1807
1808     def GetFailedShapes(self, publish=False):
1809         """
1810         Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1811         error of an algorithm
1812
1813         Parameters:
1814                 publish: if *True*, the returned groups will be published in the study
1815
1816         Returns:
1817                 a list of GEOM groups each named after a failed algorithm
1818         """
1819
1820
1821         algo2shapes = {}
1822         computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1823         for err in computeErrors:
1824             shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1825             if not shape: continue
1826             if err.algoName in algo2shapes:
1827                 algo2shapes[ err.algoName ].append( shape )
1828             else:
1829                 algo2shapes[ err.algoName ] = [ shape ]
1830             pass
1831
1832         groups = []
1833         for algoName, shapes in algo2shapes.items():
1834             while shapes:
1835                 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1836                 otherTypeShapes = []
1837                 sameTypeShapes  = []
1838                 group = self.geompyD.CreateGroup( self.geom, groupType )
1839                 for shape in shapes:
1840                     if shape.GetShapeType() == shapes[0].GetShapeType():
1841                         sameTypeShapes.append( shape )
1842                     else:
1843                         otherTypeShapes.append( shape )
1844                 self.geompyD.UnionList( group, sameTypeShapes )
1845                 if otherTypeShapes:
1846                     group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1847                 else:
1848                     group.SetName( algoName )
1849                 groups.append( group )
1850                 shapes = otherTypeShapes
1851             pass
1852         if publish:
1853             for group in groups:
1854                 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1855         return groups
1856
1857     def GetMeshOrder(self):
1858         """
1859         Return sub-mesh objects list in meshing order
1860
1861         Returns:
1862                 list of lists of sub-meshes
1863         """
1864
1865         return self.mesh.GetMeshOrder()
1866
1867     def SetMeshOrder(self, submeshes):
1868         """
1869         Set order in which concurrent sub-meshes should be meshed
1870
1871         Parameters:
1872                 submeshes list of lists of sub-meshes
1873         """
1874
1875         return self.mesh.SetMeshOrder(submeshes)
1876
1877     def Clear(self, refresh=False):
1878         """
1879         Remove all nodes and elements generated on geometry. Imported elements remain.
1880
1881         Parameters:
1882                 refresh if *True*, Object browser is automatically updated (when running in GUI)
1883         """
1884
1885         self.mesh.Clear()
1886         if ( salome.sg.hasDesktop() and
1887              salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1888             smeshgui = salome.ImportComponentGUI("SMESH")
1889             smeshgui.Init(self.mesh.GetStudyId())
1890             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1891             if refresh: salome.sg.updateObjBrowser(True)
1892
1893     def ClearSubMesh(self, geomId, refresh=False):
1894         """
1895         Remove all nodes and elements of indicated shape
1896
1897         Parameters:
1898                 refresh: if *True*, Object browser is automatically updated (when running in GUI)
1899                 geomId: the ID of a sub-shape to remove elements on
1900         """
1901
1902         self.mesh.ClearSubMesh(geomId)
1903         if salome.sg.hasDesktop():
1904             smeshgui = salome.ImportComponentGUI("SMESH")
1905             smeshgui.Init(self.mesh.GetStudyId())
1906             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1907             if refresh: salome.sg.updateObjBrowser(True)
1908
1909     def AutomaticTetrahedralization(self, fineness=0):
1910         """
1911         Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1912
1913         Parameters:
1914                 fineness: [0.0,1.0] defines mesh fineness
1915
1916         Returns:
1917                 True or False
1918         """
1919
1920         dim = self.MeshDimension()
1921         # assign hypotheses
1922         self.RemoveGlobalHypotheses()
1923         self.Segment().AutomaticLength(fineness)
1924         if dim > 1 :
1925             self.Triangle().LengthFromEdges()
1926             pass
1927         if dim > 2 :
1928             self.Tetrahedron()
1929             pass
1930         return self.Compute()
1931
1932     def AutomaticHexahedralization(self, fineness=0):
1933         """
1934         Compute an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1935
1936         Parameters:
1937                 fineness [0.0, 1.0] defines mesh fineness
1938
1939         Returns:
1940                 True or False
1941         """
1942
1943         dim = self.MeshDimension()
1944         # assign the hypotheses
1945         self.RemoveGlobalHypotheses()
1946         self.Segment().AutomaticLength(fineness)
1947         if dim > 1 :
1948             self.Quadrangle()
1949             pass
1950         if dim > 2 :
1951             self.Hexahedron()
1952             pass
1953         return self.Compute()
1954
1955     def AddHypothesis(self, hyp, geom=0):
1956         """
1957         Assign a hypothesis
1958
1959         Parameters:
1960                 hyp: a hypothesis to assign
1961                 geom: a subhape of mesh geometry
1962
1963         Returns:
1964                 SMESH.Hypothesis_Status
1965         """
1966
1967         if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1968             hyp, geom = geom, hyp
1969         if isinstance( hyp, Mesh_Algorithm ):
1970             hyp = hyp.GetAlgorithm()
1971             pass
1972         if not geom:
1973             geom = self.geom
1974             if not geom:
1975                 geom = self.mesh.GetShapeToMesh()
1976             pass
1977         isApplicable = True
1978         if self.mesh.HasShapeToMesh():
1979             hyp_type     = hyp.GetName()
1980             lib_name     = hyp.GetLibName()
1981             # checkAll    = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1982             # if checkAll and geom:
1983             #     checkAll = geom.GetType() == 37
1984             checkAll     = False
1985             isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1986         if isApplicable:
1987             AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1988             status = self.mesh.AddHypothesis(geom, hyp)
1989         else:
1990             status = HYP_BAD_GEOMETRY,""
1991         hyp_name = GetName( hyp )
1992         geom_name = ""
1993         if geom:
1994             geom_name = geom.GetName()
1995         isAlgo = hyp._narrow( SMESH_Algo )
1996         TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1997         return status
1998
1999     def IsUsedHypothesis(self, hyp, geom):
2000         """
2001         Return True if an algorithm of hypothesis is assigned to a given shape
2002
2003         Parameters:
2004                 hyp: a hypothesis to check
2005                 geom: a subhape of mesh geometry
2006
2007         Returns:
2008                 True of False
2009         """
2010
2011         if not hyp: # or not geom
2012             return False
2013         if isinstance( hyp, Mesh_Algorithm ):
2014             hyp = hyp.GetAlgorithm()
2015             pass
2016         hyps = self.GetHypothesisList(geom)
2017         for h in hyps:
2018             if h.GetId() == hyp.GetId():
2019                 return True
2020         return False
2021
2022     def RemoveHypothesis(self, hyp, geom=0):
2023         """
2024         Unassign a hypothesis
2025
2026         Parameters:
2027                 hyp: a hypothesis to unassign
2028                 geom: a sub-shape of mesh geometry
2029
2030         Returns:
2031                 SMESH.Hypothesis_Status
2032         """
2033
2034         if not hyp:
2035             return None
2036         if isinstance( hyp, Mesh_Algorithm ):
2037             hyp = hyp.GetAlgorithm()
2038             pass
2039         shape = geom
2040         if not shape:
2041             shape = self.geom
2042             pass
2043         if self.IsUsedHypothesis( hyp, shape ):
2044             return self.mesh.RemoveHypothesis( shape, hyp )
2045         hypName = GetName( hyp )
2046         geoName = GetName( shape )
2047         print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
2048         return None
2049
2050     def GetHypothesisList(self, geom):
2051         """
2052         Get the list of hypotheses added on a geometry
2053
2054         Parameters:
2055                 geom: a sub-shape of mesh geometry
2056
2057         Returns:
2058                 the sequence of SMESH_Hypothesis
2059         """
2060
2061         return self.mesh.GetHypothesisList( geom )
2062
2063     def RemoveGlobalHypotheses(self):
2064         """
2065         Remove all global hypotheses
2066         """
2067
2068         current_hyps = self.mesh.GetHypothesisList( self.geom )
2069         for hyp in current_hyps:
2070             self.mesh.RemoveHypothesis( self.geom, hyp )
2071             pass
2072         pass
2073
2074     def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
2075                   overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
2076         """
2077         Export the mesh in a file in MED format
2078                 allowing to overwrite the file if it exists or add the exported data to its contents
2079
2080         Parameters:
2081                 f: is the file name
2082                 auto_groups: boolean parameter for creating/not creating
2083                         the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
2084                         the typical use is auto_groups=False.
2085                 version: MED format version (MED_V2_1 or MED_V2_2,
2086                         the latter meaning any current version). The parameter is
2087                         obsolete since MED_V2_1 is no longer supported.
2088                 overwrite: boolean parameter for overwriting/not overwriting the file
2089                 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2090                 autoDimension: if *True* (default), a space dimension of a MED mesh can be either
2091
2092                         - 1D if all mesh nodes lie on OX coordinate axis, or
2093                         - 2D if all mesh nodes lie on XOY coordinate plane, or
2094                         - 3D in the rest cases.
2095
2096                         If *autoDimension* is *False*, the space dimension is always 3.
2097                 fields: list of GEOM fields defined on the shape to mesh.
2098                 geomAssocFields: each character of this string means a need to export a
2099                         corresponding field; correspondence between fields and characters is following:
2100
2101                                 - 'v' stands for "_vertices _" field;
2102                                 - 'e' stands for "_edges _" field;
2103                                 - 'f' stands for "_faces _" field;
2104                                 - 's' stands for "_solids _" field.
2105         """
2106
2107         if meshPart or fields or geomAssocFields:
2108             unRegister = genObjUnRegister()
2109             if isinstance( meshPart, list ):
2110                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2111                 unRegister.set( meshPart )
2112             self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
2113                                        fields, geomAssocFields)
2114         else:
2115             self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
2116
2117     def ExportSAUV(self, f, auto_groups=0):
2118         """
2119         Export the mesh in a file in SAUV format
2120
2121
2122         Parameters:
2123                 f: is the file name
2124                 auto_groups: boolean parameter for creating/not creating
2125                         the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
2126                         the typical use is auto_groups=false.
2127         """
2128
2129         self.mesh.ExportSAUV(f, auto_groups)
2130
2131     def ExportDAT(self, f, meshPart=None):
2132         """
2133         Export the mesh in a file in DAT format
2134
2135         Parameters:
2136                 f: the file name
2137                 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2138         """
2139
2140         if meshPart:
2141             unRegister = genObjUnRegister()
2142             if isinstance( meshPart, list ):
2143                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2144                 unRegister.set( meshPart )
2145             self.mesh.ExportPartToDAT( meshPart, f )
2146         else:
2147             self.mesh.ExportDAT(f)
2148
2149     def ExportUNV(self, f, meshPart=None):
2150         """
2151         Export the mesh in a file in UNV format
2152
2153         Parameters:
2154                 f: the file name
2155                 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2156         """
2157
2158         if meshPart:
2159             unRegister = genObjUnRegister()
2160             if isinstance( meshPart, list ):
2161                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2162                 unRegister.set( meshPart )
2163             self.mesh.ExportPartToUNV( meshPart, f )
2164         else:
2165             self.mesh.ExportUNV(f)
2166
2167     def ExportSTL(self, f, ascii=1, meshPart=None):
2168         """
2169         Export the mesh in a file in STL format
2170
2171         Parameters:
2172                 f: the file name
2173                 ascii: defines the file encoding
2174                 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2175         """
2176
2177         if meshPart:
2178             unRegister = genObjUnRegister()
2179             if isinstance( meshPart, list ):
2180                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2181                 unRegister.set( meshPart )
2182             self.mesh.ExportPartToSTL( meshPart, f, ascii )
2183         else:
2184             self.mesh.ExportSTL(f, ascii)
2185
2186     def ExportCGNS(self, f, overwrite=1, meshPart=None, groupElemsByType=False):
2187         """
2188         Export the mesh in a file in CGNS format
2189
2190         Parameters:
2191                 f: is the file name
2192                 overwrite: boolean parameter for overwriting/not overwriting the file
2193                 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2194                 groupElemsByType: if true all elements of same entity type are exported at ones,
2195                         else elements are exported in order of their IDs which can cause creation
2196                         of multiple cgns sections
2197         """
2198
2199         unRegister = genObjUnRegister()
2200         if isinstance( meshPart, list ):
2201             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2202             unRegister.set( meshPart )
2203         if isinstance( meshPart, Mesh ):
2204             meshPart = meshPart.mesh
2205         elif not meshPart:
2206             meshPart = self.mesh
2207         self.mesh.ExportCGNS(meshPart, f, overwrite, groupElemsByType)
2208
2209     def ExportGMF(self, f, meshPart=None):
2210         """
2211         Export the mesh in a file in GMF format.
2212         GMF files must have .mesh extension for the ASCII format and .meshb for
2213         the bynary format. Other extensions are not allowed.
2214
2215         Parameters:
2216                 f: is the file name
2217                 meshPart: a part of mesh (group, sub-mesh) to export instead of the mesh
2218         """
2219
2220         unRegister = genObjUnRegister()
2221         if isinstance( meshPart, list ):
2222             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
2223             unRegister.set( meshPart )
2224         if isinstance( meshPart, Mesh ):
2225             meshPart = meshPart.mesh
2226         elif not meshPart:
2227             meshPart = self.mesh
2228         self.mesh.ExportGMF(meshPart, f, True)
2229
2230     def ExportToMED(self, f, version=MED_V2_2, opt=0, overwrite=1, autoDimension=True):
2231         """
2232         Deprecated, used only for compatibility! Please, use ExportMED() method instead.
2233         Export the mesh in a file in MED format
2234         allowing to overwrite the file if it exists or add the exported data to its contents
2235
2236         Parameters:
2237                 f: the file name
2238                 version: MED format version (MED_V2_1 or MED_V2_2,
2239                         the latter meaning any current version). The parameter is
2240                         obsolete since MED_V2_1 is no longer supported.
2241                 opt: boolean parameter for creating/not creating
2242                         the groups Group_On_All_Nodes, Group_On_All_Faces, ...
2243                 overwrite: boolean parameter for overwriting/not overwriting the file
2244                 autoDimension: if *True* (default), a space dimension of a MED mesh can be either
2245
2246                         - 1D if all mesh nodes lie on OX coordinate axis, or
2247                         - 2D if all mesh nodes lie on XOY coordinate plane, or
2248                         - 3D in the rest cases.
2249
2250                         If **autoDimension** isc **False**, the space dimension is always 3.
2251         """
2252
2253         self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
2254
2255     # Operations with groups:
2256     # ----------------------
2257
2258     def CreateEmptyGroup(self, elementType, name):
2259         """
2260         Create an empty mesh group
2261
2262         Parameters:
2263                 elementType: the type of elements in the group; either of
2264                         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2265                 name: the name of the mesh group
2266
2267         Returns:
2268                 SMESH_Group
2269         """
2270
2271         return self.mesh.CreateGroup(elementType, name)
2272
2273     def Group(self, grp, name=""):
2274         """
2275         Create a mesh group based on the geometric object *grp*
2276         and gives a *name*,
2277         if this parameter is not defined
2278         the name is the same as the geometric group name
2279
2280         Note:
2281                 Works like GroupOnGeom().
2282
2283         Parameters:
2284                 grp:  a geometric group, a vertex, an edge, a face or a solid
2285                 name: the name of the mesh group
2286
2287         Returns:
2288                 SMESH_GroupOnGeom
2289         """
2290
2291         return self.GroupOnGeom(grp, name)
2292
2293     def GroupOnGeom(self, grp, name="", typ=None):
2294         """
2295         Create a mesh group based on the geometrical object *grp*
2296         and gives a *name*,
2297         if this parameter is not defined the name is the same as the geometrical group name
2298
2299         Parameters:
2300                 grp:  a geometrical group, a vertex, an edge, a face or a solid
2301                 name: the name of the mesh group
2302                 typ:  the type of elements in the group; either of
2303                         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
2304                         automatically detected by the type of the geometry
2305
2306         Returns:
2307                 SMESH_GroupOnGeom
2308         """
2309
2310         AssureGeomPublished( self, grp, name )
2311         if name == "":
2312             name = grp.GetName()
2313         if not typ:
2314             typ = self._groupTypeFromShape( grp )
2315         return self.mesh.CreateGroupFromGEOM(typ, name, grp)
2316
2317     def _groupTypeFromShape( self, shape ):
2318         """
2319         Pivate method to get a type of group on geometry
2320         """
2321         tgeo = str(shape.GetShapeType())
2322         if tgeo == "VERTEX":
2323             typ = NODE
2324         elif tgeo == "EDGE":
2325             typ = EDGE
2326         elif tgeo == "FACE" or tgeo == "SHELL":
2327             typ = FACE
2328         elif tgeo == "SOLID" or tgeo == "COMPSOLID":
2329             typ = VOLUME
2330         elif tgeo == "COMPOUND":
2331             sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
2332             if not sub:
2333                 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
2334             return self._groupTypeFromShape( sub[0] )
2335         else:
2336             raise ValueError, \
2337                   "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
2338         return typ
2339
2340     def GroupOnFilter(self, typ, name, filter):
2341         """
2342         Create a mesh group with given *name* based on the *filter* which
2343         is a special type of group dynamically updating it's contents during
2344         mesh modification
2345
2346         Parameters:
2347                 typ: the type of elements in the group; either of
2348                         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2349                 name: the name of the mesh group
2350                 filter: the filter defining group contents
2351
2352         Returns:
2353                 SMESH_GroupOnFilter
2354         """
2355
2356         return self.mesh.CreateGroupFromFilter(typ, name, filter)
2357
2358     def MakeGroupByIds(self, groupName, elementType, elemIDs):
2359         """
2360         Create a mesh group by the given ids of elements
2361
2362         Parameters:
2363                 groupName: the name of the mesh group
2364                 elementType: the type of elements in the group; either of
2365                         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2366                 elemIDs: either the list of ids, group, sub-mesh, or filter
2367
2368         Returns:
2369                 SMESH_Group
2370         """
2371
2372         group = self.mesh.CreateGroup(elementType, groupName)
2373         if isinstance( elemIDs, Mesh ):
2374             elemIDs = elemIDs.GetMesh()
2375         if hasattr( elemIDs, "GetIDs" ):
2376             if hasattr( elemIDs, "SetMesh" ):
2377                 elemIDs.SetMesh( self.GetMesh() )
2378             group.AddFrom( elemIDs )
2379         else:
2380             group.Add(elemIDs)
2381         return group
2382
2383     def MakeGroup(self,
2384                   groupName,
2385                   elementType,
2386                   CritType=FT_Undefined,
2387                   Compare=FT_EqualTo,
2388                   Threshold="",
2389                   UnaryOp=FT_Undefined,
2390                   Tolerance=1e-07):
2391         """
2392         Create a mesh group by the given conditions
2393
2394         Parameters:
2395                 groupName: the name of the mesh group
2396                 elementType: the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2397                 CritType: the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
2398                         Type SMESH.FunctorType._items in the Python Console to see all values.
2399                         Note that the items starting from FT_LessThan are not suitable for CritType.
2400                 Compare: belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
2401                 Threshold: the threshold value (range of ids as string, shape, numeric)
2402                 UnaryOp:  SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2403                 Tolerance: the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2404                         SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2405
2406         Returns:
2407                 SMESH_GroupOnFilter
2408         """
2409
2410         aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2411         group = self.MakeGroupByCriterion(groupName, aCriterion)
2412         return group
2413
2414     def MakeGroupByCriterion(self, groupName, Criterion):
2415         """
2416         Create a mesh group by the given criterion
2417
2418         Parameters:
2419                 groupName: the name of the mesh group
2420                 Criterion: the instance of Criterion class
2421
2422         Returns:
2423                 SMESH_GroupOnFilter
2424         """
2425
2426         return self.MakeGroupByCriteria( groupName, [Criterion] )
2427
2428     def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2429         """
2430         Create a mesh group by the given criteria (list of criteria)
2431
2432         Parameters:
2433                 groupName: the name of the mesh group
2434                 theCriteria: the list of criteria
2435                 binOp: binary operator used when binary operator of criteria is undefined
2436
2437         Returns:
2438                 SMESH_GroupOnFilter
2439         """
2440
2441         aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2442         group = self.MakeGroupByFilter(groupName, aFilter)
2443         return group
2444
2445     def MakeGroupByFilter(self, groupName, theFilter):
2446         """
2447         Create a mesh group by the given filter
2448
2449         Parameters:
2450                 groupName: the name of the mesh group
2451                 theFilter: the instance of Filter class
2452
2453         Returns:
2454                 SMESH_GroupOnFilter
2455         """
2456
2457         #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2458         #theFilter.SetMesh( self.mesh )
2459         #group.AddFrom( theFilter )
2460         group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2461         return group
2462
2463     def RemoveGroup(self, group):
2464         """
2465         Remove a group
2466         """
2467
2468         self.mesh.RemoveGroup(group)
2469
2470     def RemoveGroupWithContents(self, group):
2471         """
2472         Remove a group with its contents
2473         """
2474
2475         self.mesh.RemoveGroupWithContents(group)
2476
2477     def GetGroups(self, elemType = SMESH.ALL):
2478         """
2479         Get the list of groups existing in the mesh in the order
2480         of creation (starting from the oldest one)
2481
2482         Parameters:
2483                 elemType: type of elements the groups contain; either of
2484                         (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2485                         by default groups of elements of all types are returned
2486
2487         Returns:
2488                 a sequence of SMESH_GroupBase
2489         """
2490
2491         groups = self.mesh.GetGroups()
2492         if elemType == SMESH.ALL:
2493             return groups
2494         typedGroups = []
2495         for g in groups:
2496             if g.GetType() == elemType:
2497                 typedGroups.append( g )
2498                 pass
2499             pass
2500         return typedGroups
2501
2502     def NbGroups(self):
2503         """
2504         Get the number of groups existing in the mesh
2505
2506         Returns:
2507                 the quantity of groups as an integer value
2508         """
2509
2510         return self.mesh.NbGroups()
2511
2512     def GetGroupNames(self):
2513         """
2514         Get the list of names of groups existing in the mesh
2515
2516         Returns:
2517                 list of strings
2518         """
2519
2520         groups = self.GetGroups()
2521         names = []
2522         for group in groups:
2523             names.append(group.GetName())
2524         return names
2525
2526     def GetGroupByName(self, name, elemType = None):
2527         """
2528         Find groups by name and type
2529
2530         Parameters:
2531                 name: name of the group of interest
2532                 elemType: type of elements the groups contain; either of
2533                         (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2534                         by default one group of any type of elements is returned
2535                         if elemType == SMESH.ALL then all groups of any type are returned
2536
2537         Returns:
2538                 a list of SMESH_GroupBase's
2539         """
2540
2541         groups = []
2542         for group in self.GetGroups():
2543             if group.GetName() == name:
2544                 if elemType is None:
2545                     return [group]
2546                 if ( elemType == SMESH.ALL or
2547                      group.GetType() == elemType ):
2548                     groups.append( group )
2549         return groups
2550
2551     def UnionGroups(self, group1, group2, name):
2552         """
2553         Produce a union of two groups.
2554         A new group is created. All mesh elements that are
2555         present in the initial groups are added to the new one
2556
2557         Parameters:
2558                 an instance of SMESH_Group
2559         """
2560
2561         return self.mesh.UnionGroups(group1, group2, name)
2562
2563     def UnionListOfGroups(self, groups, name):
2564         """
2565         Produce a union list of groups.
2566         New group is created. All mesh elements that are present in
2567         initial groups are added to the new one
2568
2569
2570         Returns:
2571                 an instance of SMESH_Group
2572         """
2573
2574         return self.mesh.UnionListOfGroups(groups, name)
2575
2576     def IntersectGroups(self, group1, group2, name):
2577         """
2578         Prodice an intersection of two groups.
2579         A new group is created. All mesh elements that are common
2580         for the two initial groups are added to the new one.
2581
2582         Returns:
2583                 an instance of SMESH_Group
2584         """
2585
2586         return self.mesh.IntersectGroups(group1, group2, name)
2587
2588     def IntersectListOfGroups(self, groups, name):
2589         """
2590         Produce an intersection of groups.
2591         New group is created. All mesh elements that are present in all
2592         initial groups simultaneously are added to the new one
2593
2594         Returns:
2595                 an instance of SMESH_Group
2596         """
2597
2598         return self.mesh.IntersectListOfGroups(groups, name)
2599
2600     def CutGroups(self, main_group, tool_group, name):
2601         """
2602         Produce a cut of two groups.
2603         A new group is created. All mesh elements that are present in
2604         the main group but are not present in the tool group are added to the new one
2605
2606         Returns:
2607                 an instance of SMESH_Group
2608         """
2609
2610         return self.mesh.CutGroups(main_group, tool_group, name)
2611
2612     def CutListOfGroups(self, main_groups, tool_groups, name):
2613         """
2614         Produce a cut of groups.
2615         A new group is created. All mesh elements that are present in main groups
2616         but do not present in tool groups are added to the new one
2617
2618         Returns:
2619                 an instance of SMESH_Group
2620         """
2621
2622         return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2623
2624     def CreateDimGroup(self, groups, elemType, name,
2625                        nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2626         """
2627         Create a standalone group of entities basing on nodes of other groups.
2628
2629         Parameters:
2630                 groups: list of reference groups, sub-meshes or filters, of any type.
2631                 elemType: a type of elements to include to the new group; either of
2632                         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2633                 name: a name of the new group.
2634                 nbCommonNodes: a criterion of inclusion of an element to the new group
2635                         basing on number of element nodes common with reference *groups*.
2636                         Meaning of possible values are:
2637
2638                                 - SMESH.ALL_NODES - include if all nodes are common,
2639                                 - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2640                                 - SMESH.AT_LEAST_ONE - include if one or more node is common,
2641                                 - SMEHS.MAJORITY - include if half of nodes or more are common.
2642                 underlyingOnly: if *True* (default), an element is included to the
2643                         new group provided that it is based on nodes of an element of *groups*;
2644                         in this case the reference *groups* are supposed to be of higher dimension
2645                         than *elemType*, which can be useful for example to get all faces lying on
2646                         volumes of the reference *groups*.
2647
2648         Returns:
2649                 an instance of SMESH_Group
2650         """
2651
2652         if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2653             groups = [groups]
2654         return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2655
2656
2657     def ConvertToStandalone(self, group):
2658         """
2659         Convert group on geom into standalone group
2660         """
2661
2662         return self.mesh.ConvertToStandalone(group)
2663
2664     # Get some info about mesh:
2665     # ------------------------
2666
2667     def GetLog(self, clearAfterGet):
2668         """
2669         Return the log of nodes and elements added or removed
2670         since the previous clear of the log.
2671
2672         Parameters:
2673                 clearAfterGet: log is emptied after Get (safe if concurrents access)
2674
2675         Returns:
2676                 list of log_block structures:
2677                         commandType
2678                         number
2679                         coords
2680                         indexes
2681         """
2682
2683         return self.mesh.GetLog(clearAfterGet)
2684
2685     def ClearLog(self):
2686         """
2687         Clear the log of nodes and elements added or removed since the previous
2688         clear. Must be used immediately after GetLog if clearAfterGet is false.
2689         """
2690
2691         self.mesh.ClearLog()
2692
2693     def SetAutoColor(self, theAutoColor):
2694         """
2695         Toggle auto color mode on the object.
2696
2697         Parameters:
2698                 theAutoColor: the flag which toggles auto color mode.
2699         If switched on, a default color of a new group in Create Group dialog is chosen randomly.
2700         """
2701
2702         self.mesh.SetAutoColor(theAutoColor)
2703
2704     def GetAutoColor(self):
2705         """
2706         Get flag of object auto color mode.
2707
2708         Returns:
2709                 True or False
2710         """
2711
2712         return self.mesh.GetAutoColor()
2713
2714     def GetId(self):
2715         """
2716         Get the internal ID
2717
2718         Returns:
2719             integer value, which is the internal Id of the mesh
2720         """
2721
2722         return self.mesh.GetId()
2723
2724     def GetStudyId(self):
2725         """
2726         Get the study Id
2727
2728         Returns:
2729             integer value, which is the study Id of the mesh
2730         """
2731
2732         return self.mesh.GetStudyId()
2733
2734     def HasDuplicatedGroupNamesMED(self):
2735         """
2736         Check the group names for duplications.
2737         Consider the maximum group name length stored in MED file.
2738
2739         Returns:
2740             True or False
2741         """
2742
2743         return self.mesh.HasDuplicatedGroupNamesMED()
2744
2745     def GetMeshEditor(self):
2746         """
2747         Obtain the mesh editor tool
2748
2749         Returns:
2750             an instance of SMESH_MeshEditor
2751         """
2752
2753         return self.editor
2754
2755     def GetIDSource(self, ids, elemType = SMESH.ALL):
2756         """
2757         Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2758         can be passed as argument to a method accepting mesh, group or sub-mesh
2759
2760         Parameters:
2761                 ids: list of IDs
2762                 lemType: type of elements; this parameter is used to distinguish
2763                         IDs of nodes from IDs of elements; by default ids are treated as
2764                         IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2765
2766         Returns:
2767             an instance of SMESH_IDSource
2768
2769         Warning:
2770                 call UnRegister() for the returned object as soon as it is no more useful:
2771                         idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2772                         mesh.DoSomething( idSrc )
2773                         idSrc.UnRegister()
2774         """
2775
2776         if isinstance( ids, int ):
2777             ids = [ids]
2778         return self.editor.MakeIDSource(ids, elemType)
2779
2780
2781     # Get information about mesh contents:
2782     # ------------------------------------
2783
2784     def GetMeshInfo(self, obj = None):
2785         """
2786         Get the mesh statistic
2787
2788         Returns:
2789             dictionary type element - count of elements
2790         """
2791
2792         if not obj: obj = self.mesh
2793         return self.smeshpyD.GetMeshInfo(obj)
2794
2795     def NbNodes(self):
2796         """
2797         Return the number of nodes in the mesh
2798
2799         Returns:
2800             an integer value
2801         """
2802
2803         return self.mesh.NbNodes()
2804
2805     def NbElements(self):
2806         """
2807         Return the number of elements in the mesh
2808
2809         Returns:
2810             an integer value
2811         """
2812
2813         return self.mesh.NbElements()
2814
2815     def Nb0DElements(self):
2816         """
2817         Return the number of 0d elements in the mesh
2818
2819         Returns:
2820             an integer value
2821         """
2822
2823         return self.mesh.Nb0DElements()
2824
2825     def NbBalls(self):
2826         """
2827         Return the number of ball discrete elements in the mesh
2828
2829         Returns:
2830             an integer value
2831         """
2832
2833         return self.mesh.NbBalls()
2834
2835     def NbEdges(self):
2836         """
2837         Return the number of edges in the mesh
2838
2839         Returns:
2840             an integer value
2841         """
2842
2843         return self.mesh.NbEdges()
2844
2845     def NbEdgesOfOrder(self, elementOrder):
2846         """
2847         Return the number of edges with the given order in the mesh
2848
2849         Parameters:
2850                 elementOrder: the order of elements:
2851                 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2852
2853         Returns:
2854             an integer value
2855         """
2856
2857         return self.mesh.NbEdgesOfOrder(elementOrder)
2858
2859     def NbFaces(self):
2860         """
2861         Return the number of faces in the mesh
2862
2863         Returns:
2864             an integer value
2865         """
2866
2867         return self.mesh.NbFaces()
2868
2869     def NbFacesOfOrder(self, elementOrder):
2870         """
2871         Return the number of faces with the given order in the mesh
2872
2873         Parameters:
2874                 elementOrder: the order of elements:
2875                         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2876
2877         Returns:
2878             an integer value
2879         """
2880
2881         return self.mesh.NbFacesOfOrder(elementOrder)
2882
2883     def NbTriangles(self):
2884         """
2885         Return the number of triangles in the mesh
2886
2887         Returns:
2888             an integer value
2889         """
2890
2891         return self.mesh.NbTriangles()
2892
2893     def NbTrianglesOfOrder(self, elementOrder):
2894         """
2895         Return the number of triangles with the given order in the mesh
2896
2897         Parameters:
2898                 elementOrder: is the order of elements:
2899                         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2900
2901         Returns:
2902             an integer value
2903         """
2904
2905         return self.mesh.NbTrianglesOfOrder(elementOrder)
2906
2907     def NbBiQuadTriangles(self):
2908         """
2909         Return the number of biquadratic triangles in the mesh
2910
2911         Returns:
2912             an integer value
2913         """
2914
2915         return self.mesh.NbBiQuadTriangles()
2916
2917     def NbQuadrangles(self):
2918         """
2919         Return the number of quadrangles in the mesh
2920
2921         Returns:
2922             an integer value
2923         """
2924
2925         return self.mesh.NbQuadrangles()
2926
2927     def NbQuadranglesOfOrder(self, elementOrder):
2928         """
2929         Return the number of quadrangles with the given order in the mesh
2930
2931         Parameters:
2932                 elementOrder the order of elements:
2933                         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2934
2935         Returns:
2936             an integer value
2937         """
2938
2939         return self.mesh.NbQuadranglesOfOrder(elementOrder)
2940
2941     def NbBiQuadQuadrangles(self):
2942         """
2943         Return the number of biquadratic quadrangles in the mesh
2944
2945         Returns:
2946             an integer value
2947         """
2948
2949         return self.mesh.NbBiQuadQuadrangles()
2950
2951     def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2952         """
2953         Return the number of polygons of given order in the mesh
2954
2955         Parameters:
2956                 elementOrder: the order of elements:
2957                         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2958
2959         Returns:
2960             an integer value
2961         """
2962
2963         return self.mesh.NbPolygonsOfOrder(elementOrder)
2964
2965     def NbVolumes(self):
2966         """
2967         Return the number of volumes in the mesh
2968
2969         Returns:
2970             an integer value
2971         """
2972
2973         return self.mesh.NbVolumes()
2974
2975
2976     def NbVolumesOfOrder(self, elementOrder):
2977         """
2978         Return the number of volumes with the given order in the mesh
2979
2980         Parameters:
2981                 elementOrder:  the order of elements:
2982                 SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2983
2984         Returns:
2985             an integer value
2986         """
2987
2988         return self.mesh.NbVolumesOfOrder(elementOrder)
2989
2990     def NbTetras(self):
2991         """
2992         Return the number of tetrahedrons in the mesh
2993
2994         Returns:
2995             an integer value
2996         """
2997
2998         return self.mesh.NbTetras()
2999
3000     def NbTetrasOfOrder(self, elementOrder):
3001         """
3002         Return the number of tetrahedrons with the given order in the mesh
3003
3004         Parameters:
3005                 elementOrder:  the order of elements:
3006                         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
3007
3008         Returns:
3009             an integer value
3010         """
3011
3012         return self.mesh.NbTetrasOfOrder(elementOrder)
3013
3014     def NbHexas(self):
3015         """
3016         Return the number of hexahedrons in the mesh
3017
3018         Returns:
3019             an integer value
3020         """
3021
3022         return self.mesh.NbHexas()
3023
3024     def NbHexasOfOrder(self, elementOrder):
3025         """
3026         Return the number of hexahedrons with the given order in the mesh
3027
3028         Parameters:
3029                 elementOrder:  the order of elements:
3030                         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
3031
3032         Returns:
3033             an integer value
3034         """
3035
3036         return self.mesh.NbHexasOfOrder(elementOrder)
3037
3038     def NbTriQuadraticHexas(self):
3039         """
3040         Return the number of triquadratic hexahedrons in the mesh
3041
3042         Returns:
3043             an integer value
3044         """
3045
3046         return self.mesh.NbTriQuadraticHexas()
3047
3048     def NbPyramids(self):
3049         """
3050         Return the number of pyramids in the mesh
3051
3052         Returns:
3053             an integer value
3054         """
3055
3056         return self.mesh.NbPyramids()
3057
3058     def NbPyramidsOfOrder(self, elementOrder):
3059         """
3060         Return the number of pyramids with the given order in the mesh
3061
3062         Parameters:
3063                 elementOrder:  the order of elements:
3064                         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
3065
3066         Returns:
3067             an integer value
3068         """
3069
3070         return self.mesh.NbPyramidsOfOrder(elementOrder)
3071
3072     def NbPrisms(self):
3073         """
3074         Return the number of prisms in the mesh
3075
3076         Returns:
3077             an integer value
3078         """
3079
3080         return self.mesh.NbPrisms()
3081
3082     def NbPrismsOfOrder(self, elementOrder):
3083         """
3084         Return the number of prisms with the given order in the mesh
3085
3086         Parameters:
3087                 elementOrder:  the order of elements:
3088                         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
3089
3090         Returns:
3091             an integer value
3092         """
3093
3094         return self.mesh.NbPrismsOfOrder(elementOrder)
3095
3096     def NbHexagonalPrisms(self):
3097         """
3098         Return the number of hexagonal prisms in the mesh
3099
3100         Returns:
3101             an integer value
3102         """
3103
3104         return self.mesh.NbHexagonalPrisms()
3105
3106     def NbPolyhedrons(self):
3107         """
3108         Return the number of polyhedrons in the mesh
3109
3110         Returns:
3111             an integer value
3112         """
3113
3114         return self.mesh.NbPolyhedrons()
3115
3116     def NbSubMesh(self):
3117         """
3118         Return the number of submeshes in the mesh
3119
3120         Returns:
3121             an integer value
3122         """
3123
3124         return self.mesh.NbSubMesh()
3125
3126     def GetElementsId(self):
3127         """
3128         Return the list of mesh elements IDs
3129
3130         Returns:
3131             the list of integer values
3132         """
3133
3134         return self.mesh.GetElementsId()
3135
3136     def GetElementsByType(self, elementType):
3137         """
3138         Return the list of IDs of mesh elements with the given type
3139
3140         Parameters:
3141                 elementType:  the required type of elements, either of
3142                         (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
3143
3144         Returns:
3145             list of integer values
3146         """
3147
3148         return self.mesh.GetElementsByType(elementType)
3149
3150     def GetNodesId(self):
3151         """
3152         Return the list of mesh nodes IDs
3153
3154         Returns:
3155             the list of integer values
3156         """
3157
3158         return self.mesh.GetNodesId()
3159
3160     # Get the information about mesh elements:
3161     # ------------------------------------
3162
3163     def GetElementType(self, id, iselem=True):
3164         """
3165         Return the type of mesh element
3166
3167         Returns:
3168             the value from SMESH::ElementType enumeration
3169                 Type SMESH.ElementType._items in the Python Console to see all possible values.
3170         """
3171
3172         return self.mesh.GetElementType(id, iselem)
3173
3174     def GetElementGeomType(self, id):
3175         """
3176         Return the geometric type of mesh element
3177
3178         Returns:
3179             the value from SMESH::EntityType enumeration
3180                 Type SMESH.EntityType._items in the Python Console to see all possible values.
3181         """
3182
3183         return self.mesh.GetElementGeomType(id)
3184
3185     def GetElementShape(self, id):
3186         """
3187         Return the shape type of mesh element
3188
3189         Returns:
3190             the value from SMESH::GeometryType enumeration.
3191                 Type SMESH.GeometryType._items in the Python Console to see all possible values.
3192         """
3193
3194         return self.mesh.GetElementShape(id)
3195
3196     def GetSubMeshElementsId(self, Shape):
3197         """
3198         Return the list of submesh elements IDs
3199
3200         Parameters:
3201                 Shape: a geom object(sub-shape)
3202                         Shape must be the sub-shape of a ShapeToMesh()
3203
3204         Returns:
3205             the list of integer values
3206         """
3207
3208         if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
3209             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3210         else:
3211             ShapeID = Shape
3212         return self.mesh.GetSubMeshElementsId(ShapeID)
3213
3214     def GetSubMeshNodesId(self, Shape, all):
3215         """
3216         Return the list of submesh nodes IDs
3217
3218         Parameters:
3219                 Shape: a geom object(sub-shape)
3220                         Shape must be the sub-shape of a ShapeToMesh()
3221                 all: If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
3222
3223         Returns:
3224             the list of integer values
3225         """
3226
3227         if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
3228             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3229         else:
3230             ShapeID = Shape
3231         return self.mesh.GetSubMeshNodesId(ShapeID, all)
3232
3233     def GetSubMeshElementType(self, Shape):
3234         """
3235         Return type of elements on given shape
3236
3237         Parameters:
3238                 Shape: a geom object(sub-shape)
3239                         Shape must be a sub-shape of a ShapeToMesh()
3240
3241         Returns:
3242             element type
3243         """
3244
3245         if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
3246             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3247         else:
3248             ShapeID = Shape
3249         return self.mesh.GetSubMeshElementType(ShapeID)
3250
3251     def Dump(self):
3252         """
3253         Get the mesh description
3254
3255         Returns:
3256             string value
3257         """
3258
3259         return self.mesh.Dump()
3260
3261
3262     # Get the information about nodes and elements of a mesh by its IDs:
3263     # -----------------------------------------------------------
3264
3265     def GetNodeXYZ(self, id):
3266         """
3267         Get XYZ coordinates of a node
3268         If there is no nodes for the given ID - return an empty list
3269
3270         Returns:
3271             a list of double precision values
3272         """
3273
3274         return self.mesh.GetNodeXYZ(id)
3275
3276     def GetNodeInverseElements(self, id):
3277         """
3278         Return list of IDs of inverse elements for the given node
3279         If there is no node for the given ID - return an empty list
3280
3281         Returns:
3282             a list of integer values
3283         """
3284
3285         return self.mesh.GetNodeInverseElements(id)
3286
3287     def GetNodePosition(self,NodeID):
3288         """
3289         Return the position of a node on the shape
3290
3291         Returns:
3292             SMESH::NodePosition
3293         """
3294
3295         return self.mesh.GetNodePosition(NodeID)
3296
3297     def GetElementPosition(self,ElemID):
3298         """
3299         Return the position of an element on the shape
3300
3301         Returns:
3302             SMESH::ElementPosition
3303         """
3304
3305         return self.mesh.GetElementPosition(ElemID)
3306
3307     def GetShapeID(self, id):
3308         """
3309         Return the ID of the shape, on which the given node was generated.
3310
3311         Returns:
3312             an integer value > 0 or -1 if there is no node for the given
3313                 ID or the node is not assigned to any geometry
3314         """
3315
3316         return self.mesh.GetShapeID(id)
3317
3318     def GetShapeIDForElem(self,id):
3319         """
3320         Return the ID of the shape, on which the given element was generated.
3321
3322         Returns:
3323             an integer value > 0 or -1 if there is no element for the given
3324                 ID or the element is not assigned to any geometry
3325         """
3326
3327         return self.mesh.GetShapeIDForElem(id)
3328
3329     def GetElemNbNodes(self, id):
3330         """
3331         Return the number of nodes of the given element
3332
3333         Returns:
3334             an integer value > 0 or -1 if there is no element for the given ID
3335         """
3336
3337         return self.mesh.GetElemNbNodes(id)
3338
3339     def GetElemNode(self, id, index):
3340         """
3341         Return the node ID the given (zero based) index for the given element
3342         If there is no element for the given ID - return -1
3343         If there is no node for the given index - return -2
3344
3345         Returns:
3346             an integer value
3347         """
3348
3349         return self.mesh.GetElemNode(id, index)
3350
3351     def GetElemNodes(self, id):
3352         """
3353         Return the IDs of nodes of the given element
3354
3355         Returns:
3356             a list of integer values
3357         """
3358
3359         return self.mesh.GetElemNodes(id)
3360
3361     def IsMediumNode(self, elementID, nodeID):
3362         """
3363         Return true if the given node is the medium node in the given quadratic element
3364         """
3365
3366         return self.mesh.IsMediumNode(elementID, nodeID)
3367
3368     def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
3369         """
3370         Return true if the given node is the medium node in one of quadratic elements
3371
3372         Parameters:
3373                 nodeID: ID of the node
3374                 elementType:  the type of elements to check a state of the node, either of
3375                         (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
3376         """
3377
3378         return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
3379
3380     def ElemNbEdges(self, id):
3381         """
3382         Return the number of edges for the given element
3383         """
3384
3385         return self.mesh.ElemNbEdges(id)
3386
3387     def ElemNbFaces(self, id):
3388         """
3389         Return the number of faces for the given element
3390         """
3391
3392         return self.mesh.ElemNbFaces(id)
3393
3394     def GetElemFaceNodes(self,elemId, faceIndex):
3395         """
3396         Return nodes of given face (counted from zero) for given volumic element.
3397         """
3398
3399         return self.mesh.GetElemFaceNodes(elemId, faceIndex)
3400
3401     def GetFaceNormal(self, faceId, normalized=False):
3402         """
3403         Return three components of normal of given mesh face
3404                 (or an empty array in KO case)
3405         """
3406
3407         return self.mesh.GetFaceNormal(faceId,normalized)
3408
3409     def FindElementByNodes(self, nodes):
3410         """
3411         Return an element based on all given nodes.
3412         """
3413
3414         return self.mesh.FindElementByNodes(nodes)
3415
3416     def GetElementsByNodes(self, nodes, elemType=SMESH.ALL):
3417         """
3418         Return elements including all given nodes.
3419         """
3420
3421         return self.mesh.GetElementsByNodes( nodes, elemType )
3422
3423     def IsPoly(self, id):
3424         """
3425         Return true if the given element is a polygon
3426         """
3427
3428         return self.mesh.IsPoly(id)
3429
3430     def IsQuadratic(self, id):
3431         """
3432         Return true if the given element is quadratic
3433         """
3434
3435         return self.mesh.IsQuadratic(id)
3436
3437     def GetBallDiameter(self, id):
3438         """
3439         Return diameter of a ball discrete element or zero in case of an invalid *id*
3440         """
3441
3442         return self.mesh.GetBallDiameter(id)
3443
3444     def BaryCenter(self, id):
3445         """
3446         Return XYZ coordinates of the barycenter of the given element
3447         If there is no element for the given ID - return an empty list
3448
3449         Returns:
3450             a list of three double values
3451         """
3452
3453         return self.mesh.BaryCenter(id)
3454
3455     def GetIdsFromFilter(self, theFilter):
3456         """
3457         Pass mesh elements through the given filter and return IDs of fitting elements
3458
3459         Parameters:
3460                 theFilter: SMESH_Filter
3461
3462         Returns:
3463             a list of ids
3464         """
3465
3466         theFilter.SetMesh( self.mesh )
3467         return theFilter.GetIDs()
3468
3469     # Get mesh measurements information:
3470     # ------------------------------------
3471
3472     def GetFreeBorders(self):
3473         """
3474         Verify whether a 2D mesh element has free edges (edges connected to one face only)\n
3475         Return a list of special structures (borders).
3476
3477         Returns:
3478             a list of SMESH.FreeEdges. Border structure:: edge id and ids of two its nodes.
3479         """
3480
3481         aFilterMgr = self.smeshpyD.CreateFilterManager()
3482         aPredicate = aFilterMgr.CreateFreeEdges()
3483         aPredicate.SetMesh(self.mesh)
3484         aBorders = aPredicate.GetBorders()
3485         aFilterMgr.UnRegister()
3486         return aBorders
3487
3488     def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
3489         """
3490         Get minimum distance between two nodes, elements or distance to the origin
3491
3492         Parameters:
3493                 id1: first node/element id
3494                 id2: second node/element id (if 0, distance from *id1* to the origin is computed)
3495                 isElem1: *True* if *id1* is element id, *False* if it is node id
3496                 isElem2: *True* if *id2* is element id, *False* if it is node id
3497
3498         Returns:
3499             minimum distance value **GetMinDistance()**
3500         """
3501
3502         aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
3503         return aMeasure.value
3504
3505     def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
3506         """
3507         Get measure structure specifying minimum distance data between two objects
3508
3509         Parameters:
3510                 id1: first node/element id
3511                 id2: second node/element id (if 0, distance from *id1* to the origin is computed)
3512                 isElem1: *True* if *id1* is element id, *False* if it is node id
3513                 isElem2: *True* if *id2* is element id, *False* if it is node id
3514
3515         Returns:
3516             Measure structure **MinDistance()**
3517         """
3518
3519         if isElem1:
3520             id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
3521         else:
3522             id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
3523         if id2 != 0:
3524             if isElem2:
3525                 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
3526             else:
3527                 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
3528             pass
3529         else:
3530             id2 = None
3531
3532         aMeasurements = self.smeshpyD.CreateMeasurements()
3533         aMeasure = aMeasurements.MinDistance(id1, id2)
3534         genObjUnRegister([aMeasurements,id1, id2])
3535         return aMeasure
3536
3537     def BoundingBox(self, objects=None, isElem=False):
3538         """
3539         Get bounding box of the specified object(s)
3540
3541         Parameters:
3542                 objects: single source object or list of source objects or list of nodes/elements IDs
3543                 isElem: if *objects* is a list of IDs, *True* value in this parameters specifies that *objects* are elements,
3544                         *False* specifies that *objects* are nodes
3545
3546         Returns:
3547             tuple of six values (minX, minY, minZ, maxX, maxY, maxZ) **GetBoundingBox()**
3548         """
3549
3550         result = self.GetBoundingBox(objects, isElem)
3551         if result is None:
3552             result = (0.0,)*6
3553         else:
3554             result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
3555         return result
3556
3557     def GetBoundingBox(self, IDs=None, isElem=False):
3558         """
3559         Get measure structure specifying bounding box data of the specified object(s)
3560
3561         Parameters:
3562                 IDs: single source object or list of source objects or list of nodes/elements IDs
3563                 isElem: if *IDs* is a list of IDs, *True* value in this parameters specifies that *objects* are elements,
3564                         *False* specifies that *objects* are nodes
3565
3566         Returns:
3567             Measure structure **BoundingBox()**
3568         """
3569
3570         if IDs is None:
3571             IDs = [self.mesh]
3572         elif isinstance(IDs, tuple):
3573             IDs = list(IDs)
3574         if not isinstance(IDs, list):
3575             IDs = [IDs]
3576         if len(IDs) > 0 and isinstance(IDs[0], int):
3577             IDs = [IDs]
3578         srclist = []
3579         unRegister = genObjUnRegister()
3580         for o in IDs:
3581             if isinstance(o, Mesh):
3582                 srclist.append(o.mesh)
3583             elif hasattr(o, "_narrow"):
3584                 src = o._narrow(SMESH.SMESH_IDSource)
3585                 if src: srclist.append(src)
3586                 pass
3587             elif isinstance(o, list):
3588                 if isElem:
3589                     srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
3590                 else:
3591                     srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
3592                 unRegister.set( srclist[-1] )
3593                 pass
3594             pass
3595         aMeasurements = self.smeshpyD.CreateMeasurements()
3596         unRegister.set( aMeasurements )
3597         aMeasure = aMeasurements.BoundingBox(srclist)
3598         return aMeasure
3599
3600     # Mesh edition (SMESH_MeshEditor functionality):
3601     # ---------------------------------------------
3602
3603     def RemoveElements(self, IDsOfElements):
3604         """
3605         Remove the elements from the mesh by ids
3606
3607         Parameters:
3608                 IDsOfElements: is a list of ids of elements to remove
3609
3610         Returns:
3611             True or False
3612         """
3613
3614         return self.editor.RemoveElements(IDsOfElements)
3615
3616     def RemoveNodes(self, IDsOfNodes):
3617         """
3618         Remove nodes from mesh by ids
3619
3620         Parameters:
3621                 IDsOfNodes: is a list of ids of nodes to remove
3622
3623         Returns:
3624             True or False
3625         """
3626
3627         return self.editor.RemoveNodes(IDsOfNodes)
3628
3629     def RemoveOrphanNodes(self):
3630         """
3631         Remove all orphan (free) nodes from mesh
3632
3633         Returns:
3634             number of the removed nodes
3635         """
3636
3637         return self.editor.RemoveOrphanNodes()
3638
3639     def AddNode(self, x, y, z):
3640         """
3641         Add a node to the mesh by coordinates
3642
3643         Returns:
3644             Id of the new node
3645         """
3646
3647         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3648         if hasVars: self.mesh.SetParameters(Parameters)
3649         return self.editor.AddNode( x, y, z)
3650
3651     def Add0DElement( self, IDOfNode, DuplicateElements=True ):
3652         """
3653         Create a 0D element on a node with given number.
3654
3655         Parameters:
3656                 IDOfNode: the ID of node for creation of the element.
3657                 DuplicateElements: to add one more 0D element to a node or not
3658
3659         Returns:
3660             the Id of the new 0D element
3661         """
3662
3663         return self.editor.Add0DElement( IDOfNode, DuplicateElements )
3664
3665     def Add0DElementsToAllNodes(self, theObject, theGroupName="", DuplicateElements=False):
3666         """
3667         Create 0D elements on all nodes of the given elements except those
3668         nodes on which a 0D element already exists.
3669
3670         Parameters:
3671                 theObject: an object on whose nodes 0D elements will be created.
3672                         It can be mesh, sub-mesh, group, list of element IDs or a holder
3673                         of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
3674                 theGroupName: optional name of a group to add 0D elements created
3675                         and/or found on nodes of *theObject*.
3676                 DuplicateElements: to add one more 0D element to a node or not
3677
3678         Returns:
3679             an object (a new group or a temporary SMESH_IDSource) holding
3680                 IDs of new and/or found 0D elements. IDs of 0D elements
3681                 can be retrieved from the returned object by calling GetIDs()
3682         """
3683
3684         unRegister = genObjUnRegister()
3685         if isinstance( theObject, Mesh ):
3686             theObject = theObject.GetMesh()
3687         elif isinstance( theObject, list ):
3688             theObject = self.GetIDSource( theObject, SMESH.ALL )
3689             unRegister.set( theObject )
3690         return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName, DuplicateElements )
3691
3692     def AddBall(self, IDOfNode, diameter):
3693         """
3694         Create a ball element on a node with given ID.
3695
3696         Parameters:
3697                 IDOfNode: the ID of node for creation of the element.
3698                 diameter: the bal diameter.
3699
3700         Returns:
3701             the Id of the new ball element
3702         """
3703
3704         return self.editor.AddBall( IDOfNode, diameter )
3705
3706     def AddEdge(self, IDsOfNodes):
3707         """
3708         Create a linear or quadratic edge (this is determined
3709                 by the number of given nodes).
3710
3711         Parameters:
3712                 IDsOfNodes: the list of node IDs for creation of the element.
3713                         The order of nodes in this list should correspond to the description
3714                         of MED.
3715                         This description is located by the following link:
3716                         http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3717
3718         Returns:
3719             the Id of the new edge
3720         """
3721
3722         return self.editor.AddEdge(IDsOfNodes)
3723
3724     def AddFace(self, IDsOfNodes):
3725         """
3726         Create a linear or quadratic face (this is determined
3727         by the number of given nodes).
3728
3729         Parameters:
3730                 IDsOfNodes: the list of node IDs for creation of the element.
3731                         The order of nodes in this list should correspond to the description
3732                         of MED.
3733                         This description is located by the following link:
3734                         http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3735
3736         Returns:
3737             the Id of the new face
3738         """
3739
3740         return self.editor.AddFace(IDsOfNodes)
3741
3742     def AddPolygonalFace(self, IdsOfNodes):
3743         """
3744         Add a polygonal face to the mesh by the list of node IDs
3745
3746         Parameters:
3747                 IdsOfNodes: the list of node IDs for creation of the element.
3748
3749         Returns:
3750             the Id of the new face
3751         """
3752
3753         return self.editor.AddPolygonalFace(IdsOfNodes)
3754
3755     def AddQuadPolygonalFace(self, IdsOfNodes):
3756         """
3757         Add a quadratic polygonal face to the mesh by the list of node IDs
3758
3759         Parameters:
3760                 IdsOfNodes: the list of node IDs for creation of the element;
3761                         corner nodes follow first.
3762
3763         Returns:
3764             the Id of the new face
3765         """
3766
3767         return self.editor.AddQuadPolygonalFace(IdsOfNodes)
3768
3769     def AddVolume(self, IDsOfNodes):
3770         """
3771         Create both simple and quadratic volume (this is determined
3772                 by the number of given nodes).
3773
3774         Parameters:
3775                 IDsOfNodes: the list of node IDs for creation of the element.
3776                         The order of nodes in this list should correspond to the description
3777                         of MED.
3778                         This description is located by the following link:
3779                         http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3780
3781         Returns:
3782             the Id of the new volumic element
3783         """
3784
3785         return self.editor.AddVolume(IDsOfNodes)
3786
3787     def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
3788         """
3789         Create a volume of many faces, giving nodes for each face.
3790
3791         Parameters:
3792                 IdsOfNodes: the list of node IDs for volume creation face by face.
3793                 Quantities: the list of integer values, Quantities[i]
3794                         gives the quantity of nodes in face number i.
3795
3796         Returns:
3797             the Id of the new volumic element
3798         """
3799
3800         return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
3801
3802     def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
3803         """
3804         Create a volume of many faces, giving the IDs of the existing faces.
3805
3806         Parameters:
3807                 IdsOfFaces: the list of face IDs for volume creation.
3808
3809         Note:
3810                 The created volume will refer only to the nodes
3811                         of the given faces, not to the faces themselves.
3812
3813         Returns:
3814             the Id of the new volumic element
3815         """
3816
3817         return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
3818
3819
3820     def SetNodeOnVertex(self, NodeID, Vertex):
3821         """
3822         **Binds** a node to a vertex
3823
3824         Parameters:
3825                 NodeID: a node ID
3826                 Vertex: a vertex or vertex ID
3827
3828         Returns:
3829             True if succeed else raises an exception
3830         """
3831
3832         if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
3833             VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
3834         else:
3835             VertexID = Vertex
3836         try:
3837             self.editor.SetNodeOnVertex(NodeID, VertexID)
3838         except SALOME.SALOME_Exception, inst:
3839             raise ValueError, inst.details.text
3840         return True
3841
3842
3843     def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
3844         """
3845         **Stores** the node position on an edge
3846
3847         Parameters:
3848                 NodeID: a node ID
3849                 Edge: an edge or edge ID
3850                 paramOnEdge: a parameter on the edge where the node is located
3851
3852         Returns:
3853             True if succeed else raises an exception
3854         """
3855
3856         if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
3857             EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
3858         else:
3859             EdgeID = Edge
3860         try:
3861             self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
3862         except SALOME.SALOME_Exception, inst:
3863             raise ValueError, inst.details.text
3864         return True
3865
3866     def SetNodeOnFace(self, NodeID, Face, u, v):
3867         """
3868         **Stores** node position on a face
3869
3870         Parameters:
3871                 NodeID: a node ID
3872                 Face: a face or face ID
3873                 u: U parameter on the face where the node is located
3874                 v: V parameter on the face where the node is located
3875
3876         Returns:
3877             True if succeed else raises an exception
3878         """
3879
3880         if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
3881             FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
3882         else:
3883             FaceID = Face
3884         try:
3885             self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
3886         except SALOME.SALOME_Exception, inst:
3887             raise ValueError, inst.details.text
3888         return True
3889
3890     def SetNodeInVolume(self, NodeID, Solid):
3891         """
3892         **Binds** a node to a solid
3893
3894         Parameters:
3895                 NodeID: a node ID
3896                 Solid:  a solid or solid ID
3897
3898         Returns:
3899             True if succeed else raises an exception
3900         """
3901
3902         if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
3903             SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
3904         else:
3905             SolidID = Solid
3906         try:
3907             self.editor.SetNodeInVolume(NodeID, SolidID)
3908         except SALOME.SALOME_Exception, inst:
3909             raise ValueError, inst.details.text
3910         return True
3911
3912     def SetMeshElementOnShape(self, ElementID, Shape):
3913         """
3914         **Bind** an element to a shape
3915
3916         Parameters:
3917                 ElementID: an element ID
3918                 Shape: a shape or shape ID
3919
3920         Returns:
3921             True if succeed else raises an exception
3922         """
3923
3924         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
3925             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3926         else:
3927             ShapeID = Shape
3928         try:
3929             self.editor.SetMeshElementOnShape(ElementID, ShapeID)
3930         except SALOME.SALOME_Exception, inst:
3931             raise ValueError, inst.details.text
3932         return True
3933
3934
3935     def MoveNode(self, NodeID, x, y, z):
3936         """
3937         Move the node with the given id
3938
3939         Parameters:
3940                 NodeID: the id of the node
3941                 x:  a new X coordinate
3942                 y:  a new Y coordinate
3943                 z:  a new Z coordinate
3944
3945         Returns:
3946             True if succeed else False
3947         """
3948
3949         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3950         if hasVars: self.mesh.SetParameters(Parameters)
3951         return self.editor.MoveNode(NodeID, x, y, z)
3952
3953     def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3954         """
3955         Find the node closest to a point and moves it to a point location
3956
3957         Parameters:
3958                 x:  the X coordinate of a point
3959                 y:  the Y coordinate of a point
3960                 z:  the Z coordinate of a point
3961                 NodeID: if specified (>0), the node with this ID is moved,
3962                         otherwise, the node closest to point (*x*, *y*, *z*) is moved
3963
3964         Returns:
3965             the ID of a node
3966         """
3967
3968         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3969         if hasVars: self.mesh.SetParameters(Parameters)
3970         return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3971
3972     def FindNodeClosestTo(self, x, y, z):
3973         """
3974         Find the node closest to a point
3975
3976         Parameters:
3977                 x:  the X coordinate of a point
3978                 y:  the Y coordinate of a point
3979                 z:  the Z coordinate of a point
3980
3981         Returns:
3982             the ID of a node
3983         """
3984
3985         #preview = self.mesh.GetMeshEditPreviewer()
3986         #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3987         return self.editor.FindNodeClosestTo(x, y, z)
3988
3989     def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3990         """
3991         Find the elements where a point lays IN or ON
3992
3993         Parameters:
3994                 x:  the X coordinate of a point
3995                 y:  the Y coordinate of a point
3996                 z:  the Z coordinate of a point
3997                 elementType: type of elements to find; either of
3998                         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3999                         means elements of any type excluding nodes, discrete and 0D elements.
4000                 meshPart: a part of mesh (group, sub-mesh) to search within
4001
4002         Returns:
4003             list of IDs of found elements
4004         """
4005
4006         if meshPart:
4007             return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
4008         else:
4009             return self.editor.FindElementsByPoint(x, y, z, elementType)
4010
4011     def GetPointState(self, x, y, z):
4012         """
4013         Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
4014         0-IN, 1-OUT, 2-ON, 3-UNKNOWN
4015         UNKNOWN state means that either mesh is wrong or the analysis fails.
4016         """
4017
4018         return self.editor.GetPointState(x, y, z)
4019
4020     def IsManifold(self):
4021         """
4022         Check if a 2D mesh is manifold
4023         """
4024
4025         return self.editor.IsManifold()
4026
4027     def IsCoherentOrientation2D(self):
4028         """
4029         Check if orientation of 2D elements is coherent
4030         """
4031
4032         return self.editor.IsCoherentOrientation2D()
4033
4034     def MeshToPassThroughAPoint(self, x, y, z):
4035         """
4036         Find the node closest to a point and moves it to a point location
4037
4038         Parameters:
4039                 x:  the X coordinate of a point
4040                 y:  the Y coordinate of a point
4041                 z:  the Z coordinate of a point
4042
4043         Returns:
4044             the ID of a moved node
4045         """
4046
4047         return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
4048
4049     def InverseDiag(self, NodeID1, NodeID2):
4050         """
4051         Replace two neighbour triangles sharing Node1-Node2 link
4052         with the triangles built on the same 4 nodes but having other common link.
4053
4054         Parameters:
4055                 NodeID1:  the ID of the first node
4056                 NodeID2:  the ID of the second node
4057
4058         Returns:
4059             false if proper faces were not found
4060         """
4061         return self.editor.InverseDiag(NodeID1, NodeID2)
4062
4063     def DeleteDiag(self, NodeID1, NodeID2):
4064         """
4065         Replace two neighbour triangles sharing Node1-Node2 link
4066         with a quadrangle built on the same 4 nodes.
4067
4068         Parameters:
4069                 NodeID1:  the ID of the first node
4070                 NodeID2:  the ID of the second node
4071
4072         Returns:
4073             false if proper faces were not found
4074         """
4075
4076         return self.editor.DeleteDiag(NodeID1, NodeID2)
4077
4078     def Reorient(self, IDsOfElements=None):
4079         """
4080         Reorient elements by ids
4081
4082         Parameters:
4083                 IDsOfElements: if undefined reorients all mesh elements
4084
4085         Returns:
4086             True if succeed else False
4087         """
4088
4089         if IDsOfElements == None:
4090             IDsOfElements = self.GetElementsId()
4091         return self.editor.Reorient(IDsOfElements)
4092
4093     def ReorientObject(self, theObject):
4094         """
4095         Reorient all elements of the object
4096
4097         Parameters:
4098                 theObject: mesh, submesh or group
4099
4100         Returns:
4101             True if succeed else False
4102         """
4103
4104         if ( isinstance( theObject, Mesh )):
4105             theObject = theObject.GetMesh()
4106         return self.editor.ReorientObject(theObject)
4107
4108     def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
4109         """
4110         Reorient faces contained in *the2DObject*.
4111
4112         Parameters:
4113                 the2DObject: is a mesh, sub-mesh, group or list of IDs of 2D elements
4114                 theDirection: is a desired direction of normal of *theFace*.
4115                         It can be either a GEOM vector or a list of coordinates [x,y,z].
4116                 theFaceOrPoint: defines a face of *the2DObject* whose normal will be
4117                         compared with theDirection. It can be either ID of face or a point
4118                         by which the face will be found. The point can be given as either
4119                         a GEOM vertex or a list of point coordinates.
4120
4121         Returns:
4122             number of reoriented faces
4123         """
4124
4125         unRegister = genObjUnRegister()
4126         # check the2DObject
4127         if isinstance( the2DObject, Mesh ):
4128             the2DObject = the2DObject.GetMesh()
4129         if isinstance( the2DObject, list ):
4130             the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
4131             unRegister.set( the2DObject )
4132         # check theDirection
4133         if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
4134             theDirection = self.smeshpyD.GetDirStruct( theDirection )
4135         if isinstance( theDirection, list ):
4136             theDirection = self.smeshpyD.MakeDirStruct( *theDirection  )
4137         # prepare theFace and thePoint
4138         theFace = theFaceOrPoint
4139         thePoint = PointStruct(0,0,0)
4140         if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
4141             thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
4142             theFace = -1
4143         if isinstance( theFaceOrPoint, list ):
4144             thePoint = PointStruct( *theFaceOrPoint )
4145             theFace = -1
4146         if isinstance( theFaceOrPoint, PointStruct ):
4147             thePoint = theFaceOrPoint
4148             theFace = -1
4149         return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
4150
4151     def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
4152         """
4153         Reorient faces according to adjacent volumes.
4154
4155         Parameters:
4156                 the2DObject: is a mesh, sub-mesh, group or list of
4157                         either IDs of faces or face groups.
4158                 the3DObject: is a mesh, sub-mesh, group or list of IDs of volumes.
4159                 theOutsideNormal: to orient faces to have their normals
4160                         pointing either *outside* or *inside* the adjacent volumes.
4161
4162         Returns:
4163             number of reoriented faces.
4164         """
4165
4166         unRegister = genObjUnRegister()
4167         # check the2DObject
4168         if not isinstance( the2DObject, list ):
4169             the2DObject = [ the2DObject ]
4170         elif the2DObject and isinstance( the2DObject[0], int ):
4171             the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
4172             unRegister.set( the2DObject )
4173             the2DObject = [ the2DObject ]
4174         for i,obj2D in enumerate( the2DObject ):
4175             if isinstance( obj2D, Mesh ):
4176                 the2DObject[i] = obj2D.GetMesh()
4177             if isinstance( obj2D, list ):
4178                 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
4179                 unRegister.set( the2DObject[i] )
4180         # check the3DObject
4181         if isinstance( the3DObject, Mesh ):
4182             the3DObject = the3DObject.GetMesh()
4183         if isinstance( the3DObject, list ):
4184             the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
4185             unRegister.set( the3DObject )
4186         return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
4187
4188     def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
4189         """
4190         Fuse the neighbouring triangles into quadrangles.
4191
4192         Parameters:
4193                 IDsOfElements: The triangles to be fused.
4194                 theCriterion:  a numerical functor, in terms of enum SMESH.FunctorType, used to
4195                         applied to possible quadrangles to choose a neighbour to fuse with.
4196                         Type SMESH.FunctorType._items in the Python Console to see all items.
4197                         Note that not all items correspond to numerical functors.
4198                 MaxAngle: is the maximum angle between element normals at which the fusion
4199                         is still performed; theMaxAngle is measured in radians.
4200                         Also it could be a name of variable which defines angle in degrees.
4201
4202         Returns:
4203             TRUE in case of success, FALSE otherwise.
4204         """
4205
4206         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
4207         self.mesh.SetParameters(Parameters)
4208         if not IDsOfElements:
4209             IDsOfElements = self.GetElementsId()
4210         Functor = self.smeshpyD.GetFunctor(theCriterion)
4211         return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
4212
4213     def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
4214         """
4215         Fuse the neighbouring triangles of the object into quadrangles
4216
4217         Parameters:
4218                 theObject: is mesh, submesh or group
4219                 theCriterion: is a numerical functor, in terms of enum SMESH.FunctorType,
4220                         applied to possible quadrangles to choose a neighbour to fuse with.
4221                         Type SMESH.FunctorType._items in the Python Console to see all items.
4222                         Note that not all items correspond to numerical functors.
4223                 MaxAngle: a max angle between element normals at which the fusion
4224                         is still performed; theMaxAngle is measured in radians.
4225
4226         Returns:
4227             TRUE in case of success, FALSE otherwise.
4228         """
4229
4230         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
4231         self.mesh.SetParameters(Parameters)
4232         if isinstance( theObject, Mesh ):
4233             theObject = theObject.GetMesh()
4234         Functor = self.smeshpyD.GetFunctor(theCriterion)
4235         return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
4236
4237     def QuadToTri (self, IDsOfElements, theCriterion = None):
4238         """
4239         Split quadrangles into triangles.
4240
4241         Parameters:
4242                 IDsOfElements: the faces to be splitted.
4243                 theCriterion: is a numerical functor, in terms of enum SMESH.FunctorType, used to
4244                         choose a diagonal for splitting. If *theCriterion* is None, which is a default
4245                         value, then quadrangles will be split by the smallest diagonal.
4246                         Type SMESH.FunctorType._items in the Python Console to see all items.
4247                         Note that not all items correspond to numerical functors.
4248
4249         Returns:
4250             TRUE in case of success, FALSE otherwise.
4251         """
4252         if IDsOfElements == []:
4253             IDsOfElements = self.GetElementsId()
4254         if theCriterion is None:
4255             theCriterion = FT_MaxElementLength2D
4256         Functor = self.smeshpyD.GetFunctor(theCriterion)
4257         return self.editor.QuadToTri(IDsOfElements, Functor)
4258
4259     def QuadToTriObject (self, theObject, theCriterion = None):
4260         """
4261         Split quadrangles into triangles.
4262
4263         Parameters:
4264                 theObject: the object from which the list of elements is taken,
4265                         this is mesh, submesh or group
4266                 theCriterion: is a numerical functor, in terms of enum SMESH.FunctorType, used to
4267                         choose a diagonal for splitting. If *theCriterion* is None, which is a default
4268                         value, then quadrangles will be split by the smallest diagonal.
4269                         Type SMESH.FunctorType._items in the Python Console to see all items.
4270                         Note that not all items correspond to numerical functors.
4271
4272         Returns:
4273             TRUE in case of success, FALSE otherwise.
4274         """
4275         if ( isinstance( theObject, Mesh )):
4276             theObject = theObject.GetMesh()
4277         if theCriterion is None:
4278             theCriterion = FT_MaxElementLength2D
4279         Functor = self.smeshpyD.GetFunctor(theCriterion)
4280         return self.editor.QuadToTriObject(theObject, Functor)
4281
4282     def QuadTo4Tri (self, theElements=[]):
4283         """
4284         Split each of given quadrangles into 4 triangles. A node is added at the center of
4285                 a quadrangle.
4286
4287         Parameters:
4288                 theElements: the faces to be splitted. This can be either mesh, sub-mesh,
4289                         group or a list of face IDs. By default all quadrangles are split
4290         """
4291         unRegister = genObjUnRegister()
4292         if isinstance( theElements, Mesh ):
4293             theElements = theElements.mesh
4294         elif not theElements:
4295             theElements = self.mesh
4296         elif isinstance( theElements, list ):
4297             theElements = self.GetIDSource( theElements, SMESH.FACE )
4298             unRegister.set( theElements )
4299         return self.editor.QuadTo4Tri( theElements )
4300
4301     def SplitQuad (self, IDsOfElements, Diag13):
4302         """
4303         Split quadrangles into triangles.
4304
4305         Parameters:
4306                 IDsOfElements: the faces to be splitted
4307                 Diag13:        is used to choose a diagonal for splitting.
4308
4309         Returns:
4310             TRUE in case of success, FALSE otherwise.
4311         """
4312         if IDsOfElements == []:
4313             IDsOfElements = self.GetElementsId()
4314         return self.editor.SplitQuad(IDsOfElements, Diag13)
4315
4316     def SplitQuadObject (self, theObject, Diag13):
4317         """
4318         Split quadrangles into triangles.
4319
4320         Parameters:
4321                 theObject: the object from which the list of elements is taken,
4322                         this is mesh, submesh or group
4323                 Diag13:    is used to choose a diagonal for splitting.
4324
4325         Returns:
4326             TRUE in case of success, FALSE otherwise.
4327         """
4328         if ( isinstance( theObject, Mesh )):
4329             theObject = theObject.GetMesh()
4330         return self.editor.SplitQuadObject(theObject, Diag13)
4331
4332     def BestSplit (self, IDOfQuad, theCriterion):
4333         """
4334         Find a better splitting of the given quadrangle.
4335
4336         Parameters:
4337                 IDOfQuad:   the ID of the quadrangle to be splitted.
4338                 theCriterion:  is a numerical functor, in terms of enum SMESH.FunctorType, used to
4339                         choose a diagonal for splitting.
4340                         Type SMESH.FunctorType._items in the Python Console to see all items.
4341                         Note that not all items correspond to numerical functors.
4342
4343         Returns:
4344             1 if 1-3 diagonal is better, 2 if 2-4
4345                 diagonal is better, 0 if error occurs.
4346         """
4347         return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
4348
4349     def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
4350         """
4351         Split volumic elements into tetrahedrons
4352
4353         Parameters:
4354                 elems: either a list of elements or a mesh or a group or a submesh or a filter
4355                 method:  flags passing splitting method:
4356                         smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
4357                         smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
4358         """
4359         unRegister = genObjUnRegister()
4360         if isinstance( elems, Mesh ):
4361             elems = elems.GetMesh()
4362         if ( isinstance( elems, list )):
4363             elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
4364             unRegister.set( elems )
4365         self.editor.SplitVolumesIntoTetra(elems, method)
4366         return
4367
4368     def SplitBiQuadraticIntoLinear(self, elems=None):
4369         """
4370         Split bi-quadratic elements into linear ones without creation of additional nodes:
4371
4372             - bi-quadratic triangle will be split into 3 linear quadrangles;
4373             - bi-quadratic quadrangle will be split into 4 linear quadrangles;
4374             - tri-quadratic hexahedron will be split into 8 linear hexahedra.
4375
4376         Quadratic elements of lower dimension  adjacent to the split bi-quadratic element
4377         will be split in order to keep the mesh conformal.
4378
4379         Parameters:
4380             elems: elements to split\: sub-meshes, groups, filters or element IDs;
4381                 if None (default), all bi-quadratic elements will be split
4382         """
4383         unRegister = genObjUnRegister()
4384         if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
4385             elems = self.editor.MakeIDSource(elems, SMESH.ALL)
4386             unRegister.set( elems )
4387         if elems is None:
4388             elems = [ self.GetMesh() ]
4389         if isinstance( elems, Mesh ):
4390             elems = [ elems.GetMesh() ]
4391         if not isinstance( elems, list ):
4392             elems = [elems]
4393         self.editor.SplitBiQuadraticIntoLinear( elems )
4394
4395     def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
4396                                  method=smeshBuilder.Hex_2Prisms, allDomains=False ):
4397         """
4398         Split hexahedra into prisms
4399
4400         Parameters:
4401                 elems: either a list of elements or a mesh or a group or a submesh or a filter
4402                 startHexPoint: a point used to find a hexahedron for which *facetNormal*
4403                         gives a normal vector defining facets to split into triangles.
4404                         **startHexPoint** can be either a triple of coordinates or a vertex.
4405                 facetNormal: a normal to a facet to split into triangles of a
4406                         hexahedron found by *startHexPoint*.
4407                         **facetNormal** can be either a triple of coordinates or an edge.
4408                 method:  flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
4409                         smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
4410                 allDomains: if :code:`False`, only hexahedra adjacent to one closest
4411                         to **startHexPoint** are split, else **startHexPoint**
4412                         is used to find the facet to split in all domains present in *elems*.
4413         """
4414         # IDSource
4415         unRegister = genObjUnRegister()
4416         if isinstance( elems, Mesh ):
4417             elems = elems.GetMesh()
4418         if ( isinstance( elems, list )):
4419             elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
4420             unRegister.set( elems )
4421             pass
4422         # axis
4423         if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
4424             startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
4425         elif isinstance( startHexPoint, list ):
4426             startHexPoint = SMESH.PointStruct( startHexPoint[0],
4427                                                startHexPoint[1],
4428                                                startHexPoint[2])
4429         if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
4430             facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
4431         elif isinstance( facetNormal, list ):
4432             facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
4433                                                        facetNormal[1],
4434                                                        facetNormal[2])
4435         self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
4436
4437         self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
4438
4439     def SplitQuadsNearTriangularFacets(self):
4440         """
4441         Split quadrangle faces near triangular facets of volumes
4442         """
4443         faces_array = self.GetElementsByType(SMESH.FACE)
4444         for face_id in faces_array:
4445             if self.GetElemNbNodes(face_id) == 4: # quadrangle
4446                 quad_nodes = self.mesh.GetElemNodes(face_id)
4447                 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
4448                 isVolumeFound = False
4449                 for node1_elem in node1_elems:
4450                     if not isVolumeFound:
4451                         if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
4452                             nb_nodes = self.GetElemNbNodes(node1_elem)
4453                             if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
4454                                 volume_elem = node1_elem
4455                                 volume_nodes = self.mesh.GetElemNodes(volume_elem)
4456                                 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
4457                                     if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
4458                                         isVolumeFound = True
4459                                         if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
4460                                             self.SplitQuad([face_id], False) # diagonal 2-4
4461                                     elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
4462                                         isVolumeFound = True
4463                                         self.SplitQuad([face_id], True) # diagonal 1-3
4464                                 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
4465                                     if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
4466                                         isVolumeFound = True
4467                                         self.SplitQuad([face_id], True) # diagonal 1-3
4468
4469     def SplitHexaToTetras (self, theObject, theNode000, theNode001):
4470         """
4471         **Splits** hexahedrons into tetrahedrons.
4472
4473         This operation uses pattern mapping functionality for splitting.
4474
4475         Parameters:
4476                 theObject: the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
4477                 theNode000,theNode001: within the range [0,7]; gives the orientation of the
4478                         pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
4479                         will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
4480                         key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
4481                         The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
4482
4483         Returns:
4484             TRUE in case of success, FALSE otherwise.
4485         """
4486 #    Pattern:
4487 #                     5.---------.6
4488 #                    /|#*      /|
4489 #                   / | #*    / |
4490 #                  /  |  # * /  |
4491 #                 /   |   # /*  |
4492 #       (0,0,1) 4.---------.7 * |
4493 #                |#*  |1   | # *|
4494 #                | # *.----|---#.2
4495 #                |  #/ *   |   /
4496 #                |  /#  *  |  /
4497 #                | /   # * | /
4498 #                |/      #*|/
4499 #        (0,0,0) 0.---------.3
4500         pattern_tetra = "!!! Nb of points: \n 8 \n\
4501         !!! Points: \n\
4502         0 0 0  !- 0 \n\
4503         0 1 0  !- 1 \n\
4504         1 1 0  !- 2 \n\
4505         1 0 0  !- 3 \n\
4506         0 0 1  !- 4 \n\
4507         0 1 1  !- 5 \n\
4508         1 1 1  !- 6 \n\
4509         1 0 1  !- 7 \n\
4510         !!! Indices of points of 6 tetras: \n\
4511         0 3 4 1 \n\
4512         7 4 3 1 \n\
4513         4 7 5 1 \n\
4514         6 2 5 7 \n\
4515         1 5 2 7 \n\
4516         2 3 1 7 \n"
4517
4518         pattern = self.smeshpyD.GetPattern()
4519         isDone  = pattern.LoadFromFile(pattern_tetra)
4520         if not isDone:
4521             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
4522             return isDone
4523
4524         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
4525         isDone = pattern.MakeMesh(self.mesh, False, False)
4526         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
4527
4528         # split quafrangle faces near triangular facets of volumes
4529         self.SplitQuadsNearTriangularFacets()
4530
4531         return isDone
4532
4533     def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
4534         """
4535         **Split** hexahedrons into prisms.
4536
4537         Uses the pattern mapping functionality for splitting.
4538
4539         Parameters:
4540                 theObject: the object (mesh, submesh or group) from where the list of hexahedrons is taken;
4541                 theNode000,theNode001: (within the range [0,7]) gives the orientation of the
4542                         pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
4543                         will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
4544                         will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
4545                         Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
4546
4547         Returns:
4548             TRUE in case of success, FALSE otherwise.
4549         """
4550 #        Pattern:     5.---------.6
4551 #                     /|#       /|
4552 #                    / | #     / |
4553 #                   /  |  #   /  |
4554 #                  /   |   # /   |
4555 #        (0,0,1) 4.---------.7   |
4556 #                 |    |    |    |
4557 #                 |   1.----|----.2
4558 #                 |   / *   |   /
4559 #                 |  /   *  |  /
4560 #                 | /     * | /
4561 #                 |/       *|/
4562 #        (0,0,0) 0.---------.3
4563         pattern_prism = "!!! Nb of points: \n 8 \n\
4564         !!! Points: \n\
4565         0 0 0  !- 0 \n\
4566         0 1 0  !- 1 \n\
4567         1 1 0  !- 2 \n\
4568         1 0 0  !- 3 \n\
4569         0 0 1  !- 4 \n\
4570         0 1 1  !- 5 \n\
4571         1 1 1  !- 6 \n\
4572         1 0 1  !- 7 \n\
4573         !!! Indices of points of 2 prisms: \n\
4574         0 1 3 4 5 7 \n\
4575         2 3 1 6 7 5 \n"
4576
4577         pattern = self.smeshpyD.GetPattern()
4578         isDone  = pattern.LoadFromFile(pattern_prism)
4579         if not isDone:
4580             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
4581             return isDone
4582
4583         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
4584         isDone = pattern.MakeMesh(self.mesh, False, False)
4585         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
4586
4587         # Split quafrangle faces near triangular facets of volumes
4588         self.SplitQuadsNearTriangularFacets()
4589
4590         return isDone
4591
4592     def Smooth(self, IDsOfElements, IDsOfFixedNodes,
4593                MaxNbOfIterations, MaxAspectRatio, Method):
4594         """
4595         Smooth elements
4596
4597         Parameters:
4598                 IDsOfElements: the list if ids of elements to smooth
4599                 IDsOfFixedNodes: the list of ids of fixed nodes.
4600                         Note that nodes built on edges and boundary nodes are always fixed.
4601                 MaxNbOfIterations: the maximum number of iterations
4602                 MaxAspectRatio: varies in range [1.0, inf]
4603                 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4604                         or Centroidal (smesh.CENTROIDAL_SMOOTH)
4605
4606         Returns:
4607             TRUE in case of success, FALSE otherwise.
4608         """
4609
4610         if IDsOfElements == []:
4611             IDsOfElements = self.GetElementsId()
4612         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
4613         self.mesh.SetParameters(Parameters)
4614         return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
4615                                   MaxNbOfIterations, MaxAspectRatio, Method)
4616
4617     def SmoothObject(self, theObject, IDsOfFixedNodes,
4618                      MaxNbOfIterations, MaxAspectRatio, Method):
4619         """
4620         Smooth elements which belong to the given object
4621
4622         Parameters:
4623                 theObject: the object to smooth
4624                 IDsOfFixedNodes: the list of ids of fixed nodes.
4625                         Note that nodes built on edges and boundary nodes are always fixed.
4626                 MaxNbOfIterations: the maximum number of iterations
4627                 MaxAspectRatio: varies in range [1.0, inf]
4628                 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4629                         or Centroidal (smesh.CENTROIDAL_SMOOTH)
4630
4631         Returns:
4632             TRUE in case of success, FALSE otherwise.
4633         """
4634
4635         if ( isinstance( theObject, Mesh )):
4636             theObject = theObject.GetMesh()
4637         return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
4638                                         MaxNbOfIterations, MaxAspectRatio, Method)
4639
4640     def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
4641                          MaxNbOfIterations, MaxAspectRatio, Method):
4642         """
4643         Parametrically smooth the given elements
4644
4645         Parameters:
4646                 IDsOfElements: the list if ids of elements to smooth
4647                 IDsOfFixedNodes: the list of ids of fixed nodes.
4648                         Note that nodes built on edges and boundary nodes are always fixed.
4649                 MaxNbOfIterations: the maximum number of iterations
4650                 MaxAspectRatio: varies in range [1.0, inf]
4651                 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4652                         or Centroidal (smesh.CENTROIDAL_SMOOTH)
4653
4654         Returns:
4655             TRUE in case of success, FALSE otherwise.
4656         """
4657
4658         if IDsOfElements == []:
4659             IDsOfElements = self.GetElementsId()
4660         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
4661         self.mesh.SetParameters(Parameters)
4662         return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
4663                                             MaxNbOfIterations, MaxAspectRatio, Method)
4664
4665     def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
4666                                MaxNbOfIterations, MaxAspectRatio, Method):
4667         """
4668         Parametrically smooth the elements which belong to the given object
4669
4670         Parameters:
4671                 theObject: the object to smooth
4672                 IDsOfFixedNodes: the list of ids of fixed nodes.
4673                         Note that nodes built on edges and boundary nodes are always fixed.
4674                 MaxNbOfIterations: the maximum number of iterations
4675                 MaxAspectRatio: varies in range [1.0, inf]
4676                 Method: is either Laplacian (smesh.LAPLACIAN_SMOOTH)
4677                         or Centroidal (smesh.CENTROIDAL_SMOOTH)
4678
4679         Returns:
4680             TRUE in case of success, FALSE otherwise.
4681         """
4682
4683         if ( isinstance( theObject, Mesh )):
4684             theObject = theObject.GetMesh()
4685         return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
4686                                                   MaxNbOfIterations, MaxAspectRatio, Method)
4687
4688     def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
4689         """
4690         Convert the mesh to quadratic or bi-quadratic, deletes old elements, replacing
4691                 them with quadratic with the same id.
4692
4693         Parameters:
4694                 theForce3d: new node creation method:
4695                         0 - the medium node lies at the geometrical entity from which the mesh element is built
4696                         1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
4697                 theSubMesh: a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
4698                 theToBiQuad: If True, converts the mesh to bi-quadratic
4699
4700         Returns:
4701             SMESH.ComputeError which can hold a warning
4702         """
4703
4704         if isinstance( theSubMesh, Mesh ):
4705             theSubMesh = theSubMesh.mesh
4706         if theToBiQuad:
4707             self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
4708         else:
4709             if theSubMesh:
4710                 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
4711             else:
4712                 self.editor.ConvertToQuadratic(theForce3d)
4713         error = self.editor.GetLastError()
4714         if error and error.comment:
4715             print error.comment
4716         return error
4717
4718     def ConvertFromQuadratic(self, theSubMesh=None):
4719         """
4720         Convert the mesh from quadratic to ordinary,
4721         deletes old quadratic elements,
4722         replacing them with ordinary mesh elements with the same id.
4723
4724         Parameters:
4725             theSubMesh: a group or a sub-mesh to convert;
4726
4727         Warning:
4728             in this case the mesh can become not conformal
4729         """
4730
4731         if theSubMesh:
4732             self.editor.ConvertFromQuadraticObject(theSubMesh)
4733         else:
4734             return self.editor.ConvertFromQuadratic()
4735
4736     def Make2DMeshFrom3D(self):
4737         """
4738         Create 2D mesh as skin on boundary faces of a 3D mesh
4739
4740         Returns:
4741             TRUE if operation has been completed successfully, FALSE otherwise
4742         """
4743
4744         return self.editor.Make2DMeshFrom3D()
4745
4746     def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
4747                          toCopyElements=False, toCopyExistingBondary=False):
4748         """
4749         Create missing boundary elements
4750
4751         Parameters:
4752                 elements: elements whose boundary is to be checked:
4753                         mesh, group, sub-mesh or list of elements
4754                         if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
4755                 dimension: defines type of boundary elements to create, either of
4756                         { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
4757                         SMESH.BND_1DFROM3D create mesh edges on all borders of free facets of 3D cells
4758                 groupName: a name of group to store created boundary elements in,
4759                         "" means not to create the group
4760                 meshName: a name of new mesh to store created boundary elements in,
4761                         "" means not to create the new mesh
4762                 toCopyElements: if true, the checked elements will be copied into
4763                         the new mesh else only boundary elements will be copied into the new mesh
4764                 toCopyExistingBondary: if true, not only new but also pre-existing
4765                         boundary elements will be copied into the new mesh
4766
4767         Returns:
4768             tuple (mesh, group) where boundary elements were added to
4769         """
4770
4771         unRegister = genObjUnRegister()
4772         if isinstance( elements, Mesh ):
4773             elements = elements.GetMesh()
4774         if ( isinstance( elements, list )):
4775             elemType = SMESH.ALL
4776             if elements: elemType = self.GetElementType( elements[0], iselem=True)
4777             elements = self.editor.MakeIDSource(elements, elemType)
4778             unRegister.set( elements )
4779         mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
4780                                                    toCopyElements,toCopyExistingBondary)
4781         if mesh: mesh = self.smeshpyD.Mesh(mesh)
4782         return mesh, group
4783
4784     def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
4785                              toCopyAll=False, groups=[]):
4786         """
4787         **Create** missing boundary elements around either the whole mesh or
4788                 groups of elements
4789
4790         Parameters:
4791                 dimension: defines type of boundary elements to create, either of
4792                         { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
4793                 groupName: a name of group to store all boundary elements in,
4794                         "" means not to create the group
4795                 meshName: a name of a new mesh, which is a copy of the initial
4796                         mesh + created boundary elements; "" means not to create the new mesh
4797                 toCopyAll: if true, the whole initial mesh will be copied into
4798                         the new mesh else only boundary elements will be copied into the new mesh
4799                 groups: groups of elements to make boundary around
4800
4801         Returns:
4802                 tuple( long, mesh, groups )
4803                         long - number of added boundary elements
4804                         mesh - the mesh where elements were added to
4805                         group - the group of boundary elements or None
4806         """
4807
4808         nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
4809                                                            toCopyAll,groups)
4810         if mesh: mesh = self.smeshpyD.Mesh(mesh)
4811         return nb, mesh, group
4812
4813     def RenumberNodes(self):
4814         """
4815         Renumber mesh nodes (Obsolete, does nothing)
4816         """
4817         self.editor.RenumberNodes()
4818
4819     def RenumberElements(self):
4820         """
4821         Renumber mesh elements (Obsole, does nothing)
4822         """
4823         self.editor.RenumberElements()
4824
4825     def _getIdSourceList(self, arg, idType, unRegister):
4826         """
4827         Private method converting *arg* into a list of SMESH_IdSource's
4828         """
4829         if arg and isinstance( arg, list ):
4830             if isinstance( arg[0], int ):
4831                 arg = self.GetIDSource( arg, idType )
4832                 unRegister.set( arg )
4833             elif isinstance( arg[0], Mesh ):
4834                 arg[0] = arg[0].GetMesh()
4835         elif isinstance( arg, Mesh ):
4836             arg = arg.GetMesh()
4837         if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
4838             arg = [arg]
4839         return arg
4840
4841     def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
4842                              MakeGroups=False, TotalAngle=False):
4843         """
4844         Generate new elements by rotation of the given elements and nodes around the axis
4845
4846         Parameters:
4847                 nodes: nodes to revolve: a list including ids, groups, sub-meshes or a mesh
4848                 edges: edges to revolve: a list including ids, groups, sub-meshes or a mesh
4849                 faces: faces to revolve: a list including ids, groups, sub-meshes or a mesh
4850                 Axis: the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
4851                 AngleInRadians: the angle of Rotation (in radians) or a name of variable
4852                         which defines angle in degrees
4853                 NbOfSteps: the number of steps
4854                 Tolerance: tolerance
4855                 MakeGroups: forces the generation of new groups from existing ones
4856                 TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
4857                         of all steps, else - size of each step
4858
4859         Returns:
4860             the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4861         """
4862
4863         unRegister = genObjUnRegister()
4864         nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
4865         edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
4866         faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
4867
4868         if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
4869             Axis = self.smeshpyD.GetAxisStruct( Axis )
4870         if isinstance( Axis, list ):
4871             Axis = SMESH.AxisStruct( *Axis )
4872
4873         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
4874         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
4875         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
4876         self.mesh.SetParameters(Parameters)
4877         if TotalAngle and NbOfSteps:
4878             AngleInRadians /= NbOfSteps
4879         return self.editor.RotationSweepObjects( nodes, edges, faces,
4880                                                  Axis, AngleInRadians,
4881                                                  NbOfSteps, Tolerance, MakeGroups)
4882
4883     def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
4884                       MakeGroups=False, TotalAngle=False):
4885         """
4886         Generate new elements by rotation of the elements around the axis
4887
4888         Parameters:
4889             IDsOfElements: the list of ids of elements to sweep
4890             Axis: the axis of rotation, AxisStruct or line(geom object)
4891             AngleInRadians: the angle of Rotation (in radians) or a name of variable which defines angle in degrees
4892             NbOfSteps: the number of steps
4893             Tolerance: tolerance
4894             MakeGroups: forces the generation of new groups from existing ones
4895             TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
4896                 of all steps, else - size of each step
4897
4898         Returns:
4899             the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4900         """
4901
4902         return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
4903                                          AngleInRadians, NbOfSteps, Tolerance,
4904                                          MakeGroups, TotalAngle)
4905
4906     def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
4907                             MakeGroups=False, TotalAngle=False):
4908         """
4909         Generate new elements by rotation of the elements of object around the axis
4910             theObject object which elements should be sweeped.
4911                 It can be a mesh, a sub mesh or a group.
4912
4913         Parameters:
4914             Axis: the axis of rotation, AxisStruct or line(geom object)
4915             AngleInRadians: the angle of Rotation
4916             NbOfSteps: number of steps
4917             Tolerance: tolerance
4918             MakeGroups: forces the generation of new groups from existing ones
4919             TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
4920                 of all steps, else - size of each step
4921
4922         Returns:
4923             the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4924         """
4925
4926         return self.RotationSweepObjects( [], theObject, theObject, Axis,
4927                                           AngleInRadians, NbOfSteps, Tolerance,
4928                                           MakeGroups, TotalAngle )
4929
4930     def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
4931                               MakeGroups=False, TotalAngle=False):
4932         """
4933         Generate new elements by rotation of the elements of object around the axis
4934             theObject object which elements should be sweeped.
4935             It can be a mesh, a sub mesh or a group.
4936
4937         Parameters:
4938             Axis: the axis of rotation, AxisStruct or line(geom object)
4939             AngleInRadians: the angle of Rotation
4940             NbOfSteps: number of steps
4941             Tolerance: tolerance
4942             MakeGroups: forces the generation of new groups from existing ones
4943             TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
4944                 of all steps, else - size of each step
4945
4946         Returns:
4947             the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4948         """
4949
4950         return self.RotationSweepObjects([],theObject,[], Axis,
4951                                          AngleInRadians, NbOfSteps, Tolerance,
4952                                          MakeGroups, TotalAngle)
4953
4954     def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
4955                               MakeGroups=False, TotalAngle=False):
4956         """
4957         Generate new elements by rotation of the elements of object around the axis
4958             theObject object which elements should be sweeped.
4959             It can be a mesh, a sub mesh or a group.
4960
4961         Parameters:
4962             Axis: the axis of rotation, AxisStruct or line(geom object)
4963             AngleInRadians: the angle of Rotation
4964             NbOfSteps: number of steps
4965             Tolerance: tolerance
4966             MakeGroups: forces the generation of new groups from existing ones
4967             TotalAngle: gives meaning of AngleInRadians: if True then it is an angular size
4968                 of all steps, else - size of each step
4969
4970         Returns:
4971             the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4972         """
4973
4974         return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
4975                                          NbOfSteps, Tolerance, MakeGroups, TotalAngle)
4976
4977     def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False,
4978                               scaleFactors=[], linearVariation=False, basePoint=[] ):
4979         """
4980         Generate new elements by extrusion of the given elements and nodes
4981
4982         Parameters:
4983             nodes: nodes to extrude: a list including ids, groups, sub-meshes or a mesh
4984             edges: edges to extrude: a list including ids, groups, sub-meshes or a mesh
4985             faces: faces to extrude: a list including ids, groups, sub-meshes or a mesh
4986             StepVector: vector or DirStruct or 3 vector components, defining
4987                 the direction and value of extrusion for one step (the total extrusion
4988                 length will be NbOfSteps * ||StepVector||)
4989             NbOfSteps: the number of steps
4990             MakeGroups: forces the generation of new groups from existing ones
4991             scaleFactors: optional scale factors to apply during extrusion
4992             linearVariation: if *True*, scaleFactors are spread over all *scaleFactors*,
4993                 else scaleFactors[i] is applied to nodes at the i-th extrusion step
4994             basePoint: optional scaling center; if not provided, a gravity center of
4995                 nodes and elements being extruded is used as the scaling center.
4996                 It can be either
4997
4998                         - a list of tree components of the point or
4999                         - a node ID or
5000                         - a GEOM point
5001
5002         Returns:
5003             the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5004
5005         :ref:`tui_extrusion` example
5006         """
5007         unRegister = genObjUnRegister()
5008         nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
5009         edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
5010         faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
5011
5012         if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
5013             StepVector = self.smeshpyD.GetDirStruct(StepVector)
5014         if isinstance( StepVector, list ):
5015             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
5016
5017         if isinstance( basePoint, int):
5018             xyz = self.GetNodeXYZ( basePoint )
5019             if not xyz:
5020                 raise RuntimeError, "Invalid node ID: %s" % basePoint
5021             basePoint = xyz
5022         if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
5023             basePoint = self.geompyD.PointCoordinates( basePoint )
5024
5025         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
5026         Parameters = StepVector.PS.parameters + var_separator + Parameters
5027         self.mesh.SetParameters(Parameters)
5028
5029         return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
5030                                                   StepVector, NbOfSteps,
5031                                                   scaleFactors, linearVariation, basePoint,
5032                                                   MakeGroups)
5033
5034
5035     def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
5036         """
5037         Generate new elements by extrusion of the elements with given ids
5038
5039         Parameters:
5040             IDsOfElements: the list of ids of elements or nodes for extrusion
5041             StepVector: vector or DirStruct or 3 vector components, defining
5042                 the direction and value of extrusion for one step (the total extrusion
5043                 length will be NbOfSteps * ||StepVector||)
5044             NbOfSteps: the number of steps
5045             MakeGroups: forces the generation of new groups from existing ones
5046             IsNodes: is True if elements with given ids are nodes
5047
5048         Returns:
5049             the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5050
5051         :ref:`tui_extrusion` example
5052         """
5053         n,e,f = [],[],[]
5054         if IsNodes: n = IDsOfElements
5055         else      : e,f, = IDsOfElements,IDsOfElements
5056         return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
5057
5058     def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
5059                           ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
5060         """
5061         Generate new elements by extrusion along the normal to a discretized surface or wire
5062
5063         Parameters:
5064             Elements: elements to extrude - a list including ids, groups, sub-meshes or a mesh.
5065                 Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
5066             StepSize: length of one extrusion step (the total extrusion
5067                 length will be *NbOfSteps* *StepSize*).
5068             NbOfSteps: number of extrusion steps.
5069             ByAverageNormal: if True each node is translated by *StepSize*
5070                 along the average of the normal vectors to the faces sharing the node;
5071                 else each node is translated along the same average normal till
5072                 intersection with the plane got by translation of the face sharing
5073                 the node along its own normal by *StepSize*.
5074             UseInputElemsOnly: to use only *Elements* when computing extrusion direction
5075                 for every node of *Elements*.
5076             MakeGroups: forces generation of new groups from existing ones.
5077             Dim: dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
5078                 is not yet implemented. This parameter is used if *Elements* contains
5079                 both faces and edges, i.e. *Elements* is a Mesh.
5080
5081         Returns:
5082             the list of created groups (SMESH_GroupBase) if *MakeGroups=True*,
5083                 empty list otherwise.
5084         :ref:`tui_extrusion` example
5085         """
5086
5087         unRegister = genObjUnRegister()
5088         if isinstance( Elements, Mesh ):
5089             Elements = [ Elements.GetMesh() ]
5090         if isinstance( Elements, list ):
5091             if not Elements:
5092                 raise RuntimeError, "Elements empty!"
5093             if isinstance( Elements[0], int ):
5094                 Elements = self.GetIDSource( Elements, SMESH.ALL )
5095                 unRegister.set( Elements )
5096         if not isinstance( Elements, list ):
5097             Elements = [ Elements ]
5098         StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
5099         self.mesh.SetParameters(Parameters)
5100         return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
5101                                              ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
5102
5103     def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
5104         """
5105         Generate new elements by extrusion of the elements or nodes which belong to the object
5106
5107         Parameters:
5108             theObject: the object whose elements or nodes should be processed.
5109                 It can be a mesh, a sub-mesh or a group.
5110             StepVector: vector or DirStruct or 3 vector components, defining
5111                 the direction and value of extrusion for one step (the total extrusion
5112                 length will be NbOfSteps * ||StepVector||)
5113             NbOfSteps: the number of steps
5114             MakeGroups: forces the generation of new groups from existing ones
5115             IsNodes: is True if elements to extrude are nodes
5116
5117         Returns:
5118             list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5119         :ref:`tui_extrusion` example
5120         """
5121
5122         n,e,f = [],[],[]
5123         if IsNodes: n    = theObject
5124         else      : e,f, = theObject,theObject
5125         return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
5126
5127     def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
5128         """
5129         Generate new elements by extrusion of edges which belong to the object
5130
5131         Parameters:
5132             theObject: object whose 1D elements should be processed.
5133                 It can be a mesh, a sub-mesh or a group.
5134             StepVector: vector or DirStruct or 3 vector components, defining
5135                 the direction and value of extrusion for one step (the total extrusion
5136                 length will be NbOfSteps * ||StepVector||)
5137             NbOfSteps: the number of steps
5138             MakeGroups: to generate new groups from existing ones
5139
5140         Returns:
5141             list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5142         :ref:`tui_extrusion` example
5143         """
5144
5145         return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
5146
5147     def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
5148         """
5149         Generate new elements by extrusion of faces which belong to the object
5150
5151         Parameters:
5152             theObject: object whose 2D elements should be processed.
5153                 It can be a mesh, a sub-mesh or a group.
5154             StepVector: vector or DirStruct or 3 vector components, defining
5155                 the direction and value of extrusion for one step (the total extrusion
5156                 length will be NbOfSteps * ||StepVector||)
5157             NbOfSteps: the number of steps
5158             MakeGroups: forces the generation of new groups from existing ones
5159
5160         Returns:
5161             list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5162         :ref:`tui_extrusion` example
5163         """
5164
5165         return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
5166
5167     def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
5168                           ExtrFlags, SewTolerance, MakeGroups=False):
5169         """
5170         Generate new elements by extrusion of the elements with given ids
5171
5172         Parameters:
5173             IDsOfElements: is ids of elements
5174             StepVector: vector or DirStruct or 3 vector components, defining
5175                 the direction and value of extrusion for one step (the total extrusion
5176                 length will be NbOfSteps * ||StepVector||)
5177             NbOfSteps: the number of steps
5178             ExtrFlags: sets flags for extrusion
5179             SewTolerance: uses for comparing locations of nodes if flag
5180                 EXTRUSION_FLAG_SEW is set
5181             MakeGroups: forces the generation of new groups from existing ones
5182
5183         Returns:
5184             list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5185         """
5186
5187         if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
5188             StepVector = self.smeshpyD.GetDirStruct(StepVector)
5189         if isinstance( StepVector, list ):
5190             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
5191         return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
5192                                              ExtrFlags, SewTolerance, MakeGroups)
5193
5194     def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
5195                                   NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
5196                                   HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
5197         """
5198         Generate new elements by extrusion of the given elements and nodes along the path.
5199         The path of extrusion must be a meshed edge.
5200
5201         Parameters:
5202             Nodes: nodes to extrude: a list including ids, groups, sub-meshes or a mesh
5203             Edges: edges to extrude: a list including ids, groups, sub-meshes or a mesh
5204             Faces: faces to extrude: a list including ids, groups, sub-meshes or a mesh
5205             PathMesh: 1D mesh or 1D sub-mesh, along which proceeds the extrusion
5206             PathShape: shape (edge) defines the sub-mesh of PathMesh if PathMesh
5207                 contains not only path segments, else it can be None
5208             NodeStart: the first or the last node on the path. Defines the direction of extrusion
5209             HasAngles: allows the shape to be rotated around the path
5210                 to get the resulting mesh in a helical fashion
5211             Angles: list of angles
5212             LinearVariation: forces the computation of rotation angles as linear
5213                 variation of the given Angles along path steps
5214             HasRefPoint: allows using the reference point
5215             RefPoint: the point around which the shape is rotated (the mass center of the
5216                 shape by default). The User can specify any point as the Reference Point.
5217             MakeGroups: forces the generation of new groups from existing ones
5218
5219         Returns:
5220             list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
5221         :ref:`tui_extrusion_along_path` example
5222         """
5223
5224         unRegister = genObjUnRegister()
5225         Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
5226         Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
5227         Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
5228
5229         if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
5230             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
5231         if isinstance( RefPoint, list ):
5232             if not RefPoint: RefPoint = [0,0,0]
5233             RefPoint = SMESH.PointStruct( *RefPoint )
5234         if isinstance( PathMesh, Mesh ):
5235             PathMesh = PathMesh.GetMesh()
5236         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
5237         Parameters = AnglesParameters + var_separator + RefPoint.parameters
5238         self.mesh.SetParameters(Parameters)
5239         return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
5240                                                      PathMesh, PathShape, NodeStart,
5241                                                      HasAngles, Angles, LinearVariation,
5242                                                      HasRefPoint, RefPoint, MakeGroups)
5243
5244     def ExtrusionAlongPathX(self, Base, Path, NodeStart,
5245                             HasAngles=False, Angles=[], LinearVariation=False,
5246                             HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
5247                             ElemType=SMESH.FACE):
5248         """
5249         Generate new elements by extrusion of the given elements
5250         The path of extrusion must be a meshed edge.
5251
5252         Parameters:
5253             Base: mesh or group, or sub-mesh, or list of ids of elements for extrusion
5254             Path: 1D mesh or 1D sub-mesh, along which proceeds the extrusion
5255             NodeStart: the start node from Path. Defines the direction of extrusion
5256             HasAngles: allows the shape to be rotated around the path
5257                 to get the resulting mesh in a helical fashion
5258             Angles: list of angles in radians
5259             LinearVariation: forces the computation of rotation angles as linear
5260                 variation of the given Angles along path steps
5261             HasRefPoint: allows using the reference point
5262             RefPoint: the point around which the elements are rotated (the mass
5263                 center of the elements by default).
5264                 The User can specify any point as the Reference Point.
5265                 RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
5266             MakeGroups: forces the generation of new groups from existing ones
5267             ElemType: type of elements for extrusion (if param Base is a mesh)
5268
5269         Returns:
5270             list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
5271                 only SMESH::Extrusion_Error otherwise
5272         :ref:`tui_extrusion_along_path` example
5273         """
5274
5275         n,e,f = [],[],[]
5276         if ElemType == SMESH.NODE: n = Base
5277         if ElemType == SMESH.EDGE: e = Base
5278         if ElemType == SMESH.FACE: f = Base
5279         gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
5280                                                HasAngles, Angles, LinearVariation,
5281                                                HasRefPoint, RefPoint, MakeGroups)
5282         if MakeGroups: return gr,er
5283         return er
5284
5285     def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
5286                            HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5287                            MakeGroups=False, LinearVariation=False):
5288         """
5289         Generate new elements by extrusion of the given elements
5290         The path of extrusion must be a meshed edge.
5291
5292         Parameters:
5293             IDsOfElements: ids of elements
5294             PathMesh: mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
5295             PathShape: shape(edge) defines the sub-mesh for the path
5296             NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5297             HasAngles: allows the shape to be rotated around the path
5298                 to get the resulting mesh in a helical fashion
5299             Angles: list of angles in radians
5300             HasRefPoint: allows using the reference point
5301             RefPoint: the point around which the shape is rotated (the mass center of the shape by default).
5302                 The User can specify any point as the Reference Point.
5303             MakeGroups: forces the generation of new groups from existing ones
5304             LinearVariation: forces the computation of rotation angles as linear
5305                 variation of the given Angles along path steps
5306
5307         Returns:
5308             list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
5309                 only SMESH::Extrusion_Error otherwise
5310         :ref:`tui_extrusion_along_path` example
5311         """
5312
5313         n,e,f = [],IDsOfElements,IDsOfElements
5314         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
5315                                                NodeStart, HasAngles, Angles,
5316                                                LinearVariation,
5317                                                HasRefPoint, RefPoint, MakeGroups)
5318         if MakeGroups: return gr,er
5319         return er
5320
5321     def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
5322                                  HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5323                                  MakeGroups=False, LinearVariation=False):
5324         """
5325         Generate new elements by extrusion of the elements which belong to the object
5326         The path of extrusion must be a meshed edge.
5327
5328         Parameters:
5329             theObject: the object whose elements should be processed.
5330                 It can be a mesh, a sub-mesh or a group.
5331             PathMesh: mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
5332             PathShape: shape(edge) defines the sub-mesh for the path
5333             NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5334             HasAngles: allows the shape to be rotated around the path
5335                 to get the resulting mesh in a helical fashion
5336             Angles: list of angles
5337             HasRefPoint: allows using the reference point
5338             RefPoint: the point around which the shape is rotated (the mass center of the shape by default).
5339                 The User can specify any point as the Reference Point.
5340             MakeGroups: forces the generation of new groups from existing ones
5341             LinearVariation: forces the computation of rotation angles as linear
5342                 variation of the given Angles along path steps
5343
5344         Returns:
5345             list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
5346                 only SMESH::Extrusion_Error otherwise
5347         :ref:`tui_extrusion_along_path` example
5348         """
5349
5350         n,e,f = [],theObject,theObject
5351         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
5352                                                HasAngles, Angles, LinearVariation,
5353                                                HasRefPoint, RefPoint, MakeGroups)
5354         if MakeGroups: return gr,er
5355         return er
5356
5357     def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
5358                                    HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5359                                    MakeGroups=False, LinearVariation=False):
5360         """
5361         Generate new elements by extrusion of mesh segments which belong to the object
5362         The path of extrusion must be a meshed edge.
5363
5364         Parameters:
5365             theObject: the object whose 1D elements should be processed.
5366                 It can be a mesh, a sub-mesh or a group.
5367             PathMesh: mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
5368             PathShape: shape(edge) defines the sub-mesh for the path
5369             NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5370             HasAngles: allows the shape to be rotated around the path
5371                 to get the resulting mesh in a helical fashion
5372             Angles: list of angles
5373             HasRefPoint: allows using the reference point
5374             RefPoint the point: around which the shape is rotated (the mass center of the shape by default).
5375                 The User can specify any point as the Reference Point.
5376             MakeGroups: forces the generation of new groups from existing ones
5377             LinearVariation: forces the computation of rotation angles as linear
5378                 variation of the given Angles along path steps
5379
5380         Returns:
5381             list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
5382                 only SMESH::Extrusion_Error otherwise
5383         :ref:`tui_extrusion_along_path` example
5384         """
5385
5386         n,e,f = [],theObject,[]
5387         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
5388                                                HasAngles, Angles, LinearVariation,
5389                                                HasRefPoint, RefPoint, MakeGroups)
5390         if MakeGroups: return gr,er
5391         return er
5392
5393     def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
5394                                    HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
5395                                    MakeGroups=False, LinearVariation=False):
5396         """
5397         Generate new elements by extrusion of faces which belong to the object
5398         The path of extrusion must be a meshed edge.
5399
5400         Parameters:
5401             theObject: the object whose 2D elements should be processed.
5402                 It can be a mesh, a sub-mesh or a group.
5403             PathMesh: mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
5404             PathShape: shape(edge) defines the sub-mesh for the path
5405             NodeStart: the first or the last node on the edge. Defines the direction of extrusion
5406             HasAngles: allows the shape to be rotated around the path
5407                 to get the resulting mesh in a helical fashion
5408             Angles: list of angles
5409             HasRefPoint: allows using the reference point
5410             RefPoint: the point around which the shape is rotated (the mass center of the shape by default).
5411                 The User can specify any point as the Reference Point.
5412             MakeGroups: forces the generation of new groups from existing ones
5413             LinearVariation: forces the computation of rotation angles as linear
5414                 variation of the given Angles along path steps
5415
5416         Returns:
5417             list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
5418                 only SMESH::Extrusion_Error otherwise
5419         :ref:`tui_extrusion_along_path` example
5420         """
5421
5422         n,e,f = [],[],theObject
5423         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
5424                                                HasAngles, Angles, LinearVariation,
5425                                                HasRefPoint, RefPoint, MakeGroups)
5426         if MakeGroups: return gr,er
5427         return er
5428
5429     def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
5430         """
5431         Create a symmetrical copy of mesh elements
5432
5433         Parameters:
5434             IDsOfElements: list of elements ids
5435             Mirror: is AxisStruct or geom object(point, line, plane)
5436             theMirrorType: smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
5437                 If the Mirror is a geom object this parameter is unnecessary
5438             Copy: allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
5439             MakeGroups: forces the generation of new groups from existing ones (if Copy)
5440
5441         Returns:
5442             list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5443         """
5444
5445         if IDsOfElements == []:
5446             IDsOfElements = self.GetElementsId()
5447         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5448             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
5449             theMirrorType = Mirror._mirrorType
5450         else:
5451             self.mesh.SetParameters(Mirror.parameters)
5452         if Copy and MakeGroups:
5453             return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
5454         self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
5455         return []
5456
5457     def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
5458         """
5459         Create a new mesh by a symmetrical copy of mesh elements
5460
5461         Parameters:
5462             IDsOfElements: the list of elements ids
5463             Mirror: is AxisStruct or geom object (point, line, plane)
5464             theMirrorType: smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
5465                 If the Mirror is a geom object this parameter is unnecessary
5466             MakeGroups: to generate new groups from existing ones
5467             NewMeshName: a name of the new mesh to create
5468
5469         Returns:
5470             instance of Mesh class
5471         """
5472
5473         if IDsOfElements == []:
5474             IDsOfElements = self.GetElementsId()
5475         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5476             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
5477             theMirrorType = Mirror._mirrorType
5478         else:
5479             self.mesh.SetParameters(Mirror.parameters)
5480         mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
5481                                           MakeGroups, NewMeshName)
5482         return Mesh(self.smeshpyD,self.geompyD,mesh)
5483
5484     def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
5485         """
5486         Create a symmetrical copy of the object
5487
5488         Parameters:
5489             theObject: mesh, submesh or group
5490             Mirror: AxisStruct or geom object (point, line, plane)
5491             theMirrorType: smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
5492                 If the Mirror is a geom object this parameter is unnecessary
5493             Copy: allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
5494             MakeGroups: forces the generation of new groups from existing ones (if Copy)
5495
5496         Returns:
5497             list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5498         """
5499
5500         if ( isinstance( theObject, Mesh )):
5501             theObject = theObject.GetMesh()
5502         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5503             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
5504             theMirrorType = Mirror._mirrorType
5505         else:
5506             self.mesh.SetParameters(Mirror.parameters)
5507         if Copy and MakeGroups:
5508             return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
5509         self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
5510         return []
5511
5512     def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
5513         """
5514         Create a new mesh by a symmetrical copy of the object
5515
5516         Parameters:
5517             theObject: mesh, submesh or group
5518             Mirror: AxisStruct or geom object (point, line, plane)
5519             theMirrorType: smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
5520                 If the Mirror is a geom object this parameter is unnecessary
5521             MakeGroups: forces the generation of new groups from existing ones
5522             NewMeshName: the name of the new mesh to create
5523
5524         Returns:
5525             instance of Mesh class
5526         """
5527
5528         if ( isinstance( theObject, Mesh )):
5529             theObject = theObject.GetMesh()
5530         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
5531             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
5532             theMirrorType = Mirror._mirrorType
5533         else:
5534             self.mesh.SetParameters(Mirror.parameters)
5535         mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
5536                                                 MakeGroups, NewMeshName)
5537         return Mesh( self.smeshpyD,self.geompyD,mesh )
5538
5539     def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
5540         """
5541         Translate the elements
5542
5543         Parameters:
5544             IDsOfElements: list of elements ids
5545             Vector: the direction of translation (DirStruct or vector or 3 vector components)
5546             Copy: allows copying the translated elements
5547             MakeGroups: forces the generation of new groups from existing ones (if Copy)
5548
5549         Returns:
5550             list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5551         """
5552
5553         if IDsOfElements == []:
5554             IDsOfElements = self.GetElementsId()
5555         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
5556             Vector = self.smeshpyD.GetDirStruct(Vector)
5557         if isinstance( Vector, list ):
5558             Vector = self.smeshpyD.MakeDirStruct(*Vector)
5559         self.mesh.SetParameters(Vector.PS.parameters)
5560         if Copy and MakeGroups:
5561             return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
5562         self.editor.Translate(IDsOfElements, Vector, Copy)
5563         return []
5564
5565     def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
5566         """
5567         Create a new mesh of translated elements
5568
5569         Parameters:
5570             IDsOfElements: list of elements ids
5571             Vector: the direction of translation (DirStruct or vector or 3 vector components)
5572             MakeGroups: forces the generation of new groups from existing ones
5573             NewMeshName: the name of the newly created mesh
5574
5575         Returns:
5576             instance of Mesh class
5577         """
5578
5579         if IDsOfElements == []:
5580             IDsOfElements = self.GetElementsId()
5581         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
5582             Vector = self.smeshpyD.GetDirStruct(Vector)
5583         if isinstance( Vector, list ):
5584             Vector = self.smeshpyD.MakeDirStruct(*Vector)
5585         self.mesh.SetParameters(Vector.PS.parameters)
5586         mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
5587         return Mesh ( self.smeshpyD, self.geompyD, mesh )
5588
5589     def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
5590         """
5591         Translate the object
5592
5593         Parameters:
5594             theObject: the object to translate (mesh, submesh, or group)
5595             Vector: direction of translation (DirStruct or geom vector or 3 vector components)
5596             Copy: allows copying the translated elements
5597             MakeGroups: forces the generation of new groups from existing ones (if Copy)
5598
5599         Returns:
5600             list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5601         """
5602
5603         if ( isinstance( theObject, Mesh )):
5604             theObject = theObject.GetMesh()
5605         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
5606             Vector = self.smeshpyD.GetDirStruct(Vector)
5607         if isinstance( Vector, list ):
5608             Vector = self.smeshpyD.MakeDirStruct(*Vector)
5609         self.mesh.SetParameters(Vector.PS.parameters)
5610         if Copy and MakeGroups:
5611             return self.editor.TranslateObjectMakeGroups(theObject, Vector)
5612         self.editor.TranslateObject(theObject, Vector, Copy)
5613         return []
5614
5615     def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
5616         """
5617         Create a new mesh from the translated object
5618
5619         Parameters:
5620             theObject: the object to translate (mesh, submesh, or group)
5621             Vector: the direction of translation (DirStruct or geom vector or 3 vector components)
5622             MakeGroups: forces the generation of new groups from existing ones
5623             NewMeshName: the name of the newly created mesh
5624
5625         Returns:
5626             instance of Mesh class
5627         """
5628
5629         if isinstance( theObject, Mesh ):
5630             theObject = theObject.GetMesh()
5631         if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
5632             Vector = self.smeshpyD.GetDirStruct(Vector)
5633         if isinstance( Vector, list ):
5634             Vector = self.smeshpyD.MakeDirStruct(*Vector)
5635         self.mesh.SetParameters(Vector.PS.parameters)
5636         mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
5637         return Mesh( self.smeshpyD, self.geompyD, mesh )
5638
5639
5640
5641     def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
5642         """
5643         Scale the object
5644
5645         Parameters:
5646             theObject: the object to translate (mesh, submesh, or group)
5647             thePoint: base point for scale (SMESH.PointStruct or list of 3 coordinates)
5648             theScaleFact: list of 1-3 scale factors for axises
5649             Copy: allows copying the translated elements
5650             MakeGroups: forces the generation of new groups from existing
5651                 ones (if Copy)
5652
5653         Returns:
5654             list of created groups (SMESH_GroupBase) if MakeGroups=True,
5655                 empty list otherwise
5656         """
5657         unRegister = genObjUnRegister()
5658         if ( isinstance( theObject, Mesh )):
5659             theObject = theObject.GetMesh()
5660         if ( isinstance( theObject, list )):
5661             theObject = self.GetIDSource(theObject, SMESH.ALL)
5662             unRegister.set( theObject )
5663         if ( isinstance( thePoint, list )):
5664             thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
5665         if ( isinstance( theScaleFact, float )):
5666              theScaleFact = [theScaleFact]
5667         if ( isinstance( theScaleFact, int )):
5668              theScaleFact = [ float(theScaleFact)]
5669
5670         self.mesh.SetParameters(thePoint.parameters)
5671
5672         if Copy and MakeGroups:
5673             return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
5674         self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
5675         return []
5676
5677     def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
5678         """
5679         Create a new mesh from the translated object
5680
5681         Parameters:
5682             theObject: the object to translate (mesh, submesh, or group)
5683             thePoint: base point for scale (SMESH.PointStruct or list of 3 coordinates)
5684             theScaleFact: list of 1-3 scale factors for axises
5685             MakeGroups: forces the generation of new groups from existing ones
5686             NewMeshName: the name of the newly created mesh
5687
5688         Returns:
5689             instance of Mesh class
5690         """
5691         unRegister = genObjUnRegister()
5692         if (isinstance(theObject, Mesh)):
5693             theObject = theObject.GetMesh()
5694         if ( isinstance( theObject, list )):
5695             theObject = self.GetIDSource(theObject,SMESH.ALL)
5696             unRegister.set( theObject )
5697         if ( isinstance( thePoint, list )):
5698             thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
5699         if ( isinstance( theScaleFact, float )):
5700              theScaleFact = [theScaleFact]
5701         if ( isinstance( theScaleFact, int )):
5702              theScaleFact = [ float(theScaleFact)]
5703
5704         self.mesh.SetParameters(thePoint.parameters)
5705         mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
5706                                          MakeGroups, NewMeshName)
5707         return Mesh( self.smeshpyD, self.geompyD, mesh )
5708
5709
5710
5711     def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
5712         """
5713         Rotate the elements
5714
5715         Parameters:
5716             IDsOfElements: list of elements ids
5717             Axis: the axis of rotation (AxisStruct or geom line)
5718             AngleInRadians: the angle of rotation (in radians) or a name of variable which defines angle in degrees
5719             Copy: allows copying the rotated elements
5720             MakeGroups: forces the generation of new groups from existing ones (if Copy)
5721
5722         Returns:
5723             list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5724         """
5725
5726
5727         if IDsOfElements == []:
5728             IDsOfElements = self.GetElementsId()
5729         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
5730             Axis = self.smeshpyD.GetAxisStruct(Axis)
5731         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
5732         Parameters = Axis.parameters + var_separator + Parameters
5733         self.mesh.SetParameters(Parameters)
5734         if Copy and MakeGroups:
5735             return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
5736         self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
5737         return []
5738
5739     def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
5740         """
5741         Create a new mesh of rotated elements
5742
5743         Parameters:
5744             IDsOfElements: list of element ids
5745             Axis: the axis of rotation (AxisStruct or geom line)
5746             AngleInRadians: the angle of rotation (in radians) or a name of variable which defines angle in degrees
5747             MakeGroups: forces the generation of new groups from existing ones
5748             NewMeshName: the name of the newly created mesh
5749
5750         Returns:
5751             instance of Mesh class
5752         """
5753
5754         if IDsOfElements == []:
5755             IDsOfElements = self.GetElementsId()
5756         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
5757             Axis = self.smeshpyD.GetAxisStruct(Axis)
5758         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
5759         Parameters = Axis.parameters + var_separator + Parameters
5760         self.mesh.SetParameters(Parameters)
5761         mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
5762                                           MakeGroups, NewMeshName)
5763         return Mesh( self.smeshpyD, self.geompyD, mesh )
5764
5765     def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
5766         """
5767         Rotate the object
5768
5769         Parameters:
5770             theObject: the object to rotate( mesh, submesh, or group)
5771             Axis: the axis of rotation (AxisStruct or geom line)
5772             AngleInRadians: the angle of rotation (in radians) or a name of variable which defines angle in degrees
5773             Copy: allows copying the rotated elements
5774             MakeGroups: forces the generation of new groups from existing ones (if Copy)
5775
5776         Returns:
5777             list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
5778         """
5779
5780         if (isinstance(theObject, Mesh)):
5781             theObject = theObject.GetMesh()
5782         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
5783             Axis = self.smeshpyD.GetAxisStruct(Axis)
5784         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
5785         Parameters = Axis.parameters + ":" + Parameters
5786         self.mesh.SetParameters(Parameters)
5787         if Copy and MakeGroups:
5788             return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
5789         self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
5790         return []
5791
5792     def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
5793         """
5794         Create a new mesh from the rotated object
5795
5796         Parameters:
5797             theObject: the object to rotate (mesh, submesh, or group)
5798             Axis: the axis of rotation (AxisStruct or geom line)
5799             AngleInRadians: the angle of rotation (in radians)  or a name of variable which defines angle in degrees
5800             MakeGroups: forces the generation of new groups from existing ones
5801             NewMeshName: the name of the newly created mesh
5802
5803         Returns:
5804             instance of Mesh class
5805         """
5806
5807         if (isinstance( theObject, Mesh )):
5808             theObject = theObject.GetMesh()
5809         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
5810             Axis = self.smeshpyD.GetAxisStruct(Axis)
5811         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
5812         Parameters = Axis.parameters + ":" + Parameters
5813         mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
5814                                                        MakeGroups, NewMeshName)
5815         self.mesh.SetParameters(Parameters)
5816         return Mesh( self.smeshpyD, self.geompyD, mesh )
5817
5818     def Offset(self, theObject, theValue, MakeGroups=False, NewMeshName=''):
5819         """
5820         Create an offset mesh from the given 2D object
5821
5822         Parameters:
5823             theObject: the source object (mesh, submesh, group or filter)
5824             theValue: signed offset size
5825             MakeGroups: forces the generation of new groups from existing ones
5826             NewMeshName: the name of a mesh to create. If empty, offset elements are added to this mesh
5827
5828         Returns:
5829             A tuple (mesh, list_of_groups)
5830         """
5831
5832         if isinstance( theObject, Mesh ):
5833             theObject = theObject.GetMesh()
5834         theValue,Parameters,hasVars = ParseParameters(theValue)
5835         mesh_groups = self.editor.Offset(theObject, theValue, MakeGroups, NewMeshName )
5836         self.mesh.SetParameters(Parameters)
5837         # if mesh_groups[0]:
5838         #     return Mesh( self.smeshpyD, self.geompyD, mesh_groups[0] ), mesh_groups[1]
5839         return mesh_groups
5840
5841     def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
5842         """
5843         Find groups of adjacent nodes within Tolerance.
5844
5845         Parameters:
5846             Tolerance: the value of tolerance
5847             SeparateCornerAndMediumNodes: if *True*, in quadratic mesh puts
5848                 corner and medium nodes in separate groups thus preventing
5849                 their further merge.
5850
5851         Returns:
5852             the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
5853         """
5854
5855         return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
5856
5857     def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
5858                                    exceptNodes=[], SeparateCornerAndMediumNodes=False):
5859         """
5860         Find groups of ajacent nodes within Tolerance.
5861
5862         Parameters:
5863             Tolerance: the value of tolerance
5864             SubMeshOrGroup: SubMesh, Group or Filter
5865             exceptNodes: list of either SubMeshes, Groups or node IDs to exclude from search
5866             SeparateCornerAndMediumNodes: if *True*, in quadratic mesh puts
5867                 corner and medium nodes in separate groups thus preventing
5868                 their further merge.
5869
5870         Returns:
5871             the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
5872         """
5873
5874         unRegister = genObjUnRegister()
5875         if (isinstance( SubMeshOrGroup, Mesh )):
5876             SubMeshOrGroup = SubMeshOrGroup.GetMesh()
5877         if not isinstance( exceptNodes, list ):
5878             exceptNodes = [ exceptNodes ]
5879         if exceptNodes and isinstance( exceptNodes[0], int ):
5880             exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
5881             unRegister.set( exceptNodes )
5882         return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
5883                                                         exceptNodes, SeparateCornerAndMediumNodes)
5884
5885     def MergeNodes (self, GroupsOfNodes, NodesToKeep=[], AvoidMakingHoles=False):
5886         """
5887         Merge nodes
5888
5889         Parameters:
5890             GroupsOfNodes: a list of groups of nodes IDs for merging
5891                 (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
5892                 by nodes 1 and 25 correspondingly in all elements and groups
5893             NodesToKeep: nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
5894                 If *NodesToKeep* does not include a node to keep for some group to merge,
5895                 then the first node in the group is kept.
5896             AvoidMakingHoles: prevent merging nodes which cause removal of elements becoming
5897                 invalid
5898         """
5899
5900
5901         # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
5902         self.editor.MergeNodes( GroupsOfNodes, NodesToKeep, AvoidMakingHoles )
5903
5904     def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
5905         """
5906         Find the elements built on the same nodes.
5907
5908         Parameters:
5909             MeshOrSubMeshOrGroup: Mesh or SubMesh, or Group of elements for searching
5910
5911         Returns:
5912             the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
5913         """
5914
5915         if not MeshOrSubMeshOrGroup:
5916             MeshOrSubMeshOrGroup=self.mesh
5917         elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
5918             MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
5919         return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
5920
5921     def MergeElements(self, GroupsOfElementsID):
5922         """
5923         Merge elements in each given group.
5924
5925         Parameters:
5926             GroupsOfElementsID: a list of groups of elements IDs for merging
5927                 (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
5928                 replaced by elements 1 and 25 in all groups)
5929         """
5930
5931         self.editor.MergeElements(GroupsOfElementsID)
5932
5933     def MergeEqualElements(self):
5934         """
5935         Leave one element and remove all other elements built on the same nodes.
5936         """
5937
5938         self.editor.MergeEqualElements()
5939
5940     def FindFreeBorders(self, ClosedOnly=True):
5941         """
5942         Returns all or only closed free borders
5943
5944         Returns:
5945             list of SMESH.FreeBorder's
5946         """
5947
5948         return self.editor.FindFreeBorders( ClosedOnly )
5949
5950     def FillHole(self, holeNodes):
5951         """
5952         Fill with 2D elements a hole defined by a SMESH.FreeBorder.
5953
5954         Parameters:
5955             FreeBorder: either a SMESH.FreeBorder or a list on node IDs. These nodes
5956                 must describe all sequential nodes of the hole border. The first and the last
5957                 nodes must be the same. Use FindFreeBorders() to get nodes of holes.
5958         """
5959
5960
5961         if holeNodes and isinstance( holeNodes, list ) and isinstance( holeNodes[0], int ):
5962             holeNodes = SMESH.FreeBorder(nodeIDs=holeNodes)
5963         if not isinstance( holeNodes, SMESH.FreeBorder ):
5964             raise TypeError, "holeNodes must be either SMESH.FreeBorder or list of integer and not %s" % holeNodes
5965         self.editor.FillHole( holeNodes )
5966
5967     def FindCoincidentFreeBorders (self, tolerance=0.):
5968         """
5969         Return groups of FreeBorder's coincident within the given tolerance.
5970
5971         Parameters:
5972             tolerance: the tolerance. If the tolerance <= 0.0 then one tenth of an average
5973                 size of elements adjacent to free borders being compared is used.
5974
5975         Returns:
5976             SMESH.CoincidentFreeBorders structure
5977         """
5978
5979         return self.editor.FindCoincidentFreeBorders( tolerance )
5980
5981     def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
5982         """
5983         Sew FreeBorder's of each group
5984
5985         Parameters:
5986             freeBorders: either a SMESH.CoincidentFreeBorders structure or a list of lists
5987                 where each enclosed list contains node IDs of a group of coincident free
5988                 borders such that each consequent triple of IDs within a group describes
5989                 a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
5990                 last node of a border.
5991                 For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
5992                 groups of coincident free borders, each group including two borders.
5993             createPolygons: if :code:`True` faces adjacent to free borders are converted to
5994                 polygons if a node of opposite border falls on a face edge, else such
5995                 faces are split into several ones.
5996             createPolyhedra: if :code:`True` volumes adjacent to free borders are converted to
5997                 polyhedra if a node of opposite border falls on a volume edge, else such
5998                 volumes, if any, remain intact and the mesh becomes non-conformal.
5999
6000         Returns:
6001             a number of successfully sewed groups
6002         """
6003
6004         if freeBorders and isinstance( freeBorders, list ):
6005             # construct SMESH.CoincidentFreeBorders
6006             if isinstance( freeBorders[0], int ):
6007                 freeBorders = [freeBorders]
6008             borders = []
6009             coincidentGroups = []
6010             for nodeList in freeBorders:
6011                 if not nodeList or len( nodeList ) % 3:
6012                     raise ValueError, "Wrong number of nodes in this group: %s" % nodeList
6013                 group = []
6014                 while nodeList:
6015                     group.append  ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
6016                     borders.append( SMESH.FreeBorder( nodeList[:3] ))
6017                     nodeList = nodeList[3:]
6018                     pass
6019                 coincidentGroups.append( group )
6020                 pass
6021             freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
6022
6023         return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
6024
6025     def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
6026                         FirstNodeID2, SecondNodeID2, LastNodeID2,
6027                         CreatePolygons, CreatePolyedrs):
6028         """
6029         Sew free borders
6030
6031         Returns:
6032             SMESH::Sew_Error
6033         """
6034
6035         return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
6036                                           FirstNodeID2, SecondNodeID2, LastNodeID2,
6037                                           CreatePolygons, CreatePolyedrs)
6038
6039     def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
6040                                FirstNodeID2, SecondNodeID2):
6041         """
6042         Sew conform free borders
6043
6044         Returns:
6045             SMESH::Sew_Error
6046         """
6047
6048         return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
6049                                                  FirstNodeID2, SecondNodeID2)
6050
6051     def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
6052                          FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
6053         """
6054         Sew border to side
6055
6056         Returns:
6057             SMESH::Sew_Error
6058         """
6059
6060         return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
6061                                            FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
6062
6063     def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
6064                          NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
6065                          NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
6066         """
6067         Sew two sides of a mesh. The nodes belonging to Side1 are
6068                 merged with the nodes of elements of Side2.
6069                 The number of elements in theSide1 and in theSide2 must be
6070                 equal and they should have similar nodal connectivity.
6071                 The nodes to merge should belong to side borders and
6072                 the first node should be linked to the second.
6073
6074         Returns:
6075             SMESH::Sew_Error
6076         """
6077
6078         return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
6079                                            NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
6080                                            NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
6081
6082     def ChangeElemNodes(self, ide, newIDs):
6083         """
6084         Set new nodes for the given element.
6085
6086         Parameters:
6087             ide: the element id
6088             newIDs: nodes ids
6089
6090         Returns:
6091             If the number of nodes does not correspond to the type of element - return false
6092         """
6093
6094         return self.editor.ChangeElemNodes(ide, newIDs)
6095
6096     def GetLastCreatedNodes(self):
6097         """
6098         If during the last operation of MeshEditor some nodes were
6099                 created, this method return the list of their IDs, \n
6100                 if new nodes were not created - return empty list
6101
6102         Returns:
6103             the list of integer values (can be empty)
6104         """
6105
6106         return self.editor.GetLastCreatedNodes()
6107
6108     def GetLastCreatedElems(self):
6109         """
6110         If during the last operation of MeshEditor some elements were
6111                 created this method return the list of their IDs, \n
6112                 if new elements were not created - return empty list
6113
6114         Returns:
6115             the list of integer values (can be empty)
6116         """
6117
6118         return self.editor.GetLastCreatedElems()
6119
6120     def ClearLastCreated(self):
6121         """
6122         Forget what nodes and elements were created by the last mesh edition operation
6123         """
6124
6125         self.editor.ClearLastCreated()
6126
6127     def DoubleElements(self, theElements, theGroupName=""):
6128         """
6129         Create duplicates of given elements, i.e. create new elements based on the
6130                 same nodes as the given ones.
6131
6132         Parameters:
6133             theElements: container of elements to duplicate. It can be a Mesh,
6134                 sub-mesh, group, filter or a list of element IDs. If *theElements* is
6135                 a Mesh, elements of highest dimension are duplicated
6136             theGroupName: a name of group to contain the generated elements.
6137                 If a group with such a name already exists, the new elements
6138                 are added to the existng group, else a new group is created.
6139                 If *theGroupName* is empty, new elements are not added
6140                 in any group.
6141
6142         Returns:
6143                 a group where the new elements are added. None if theGroupName == "".
6144         """
6145
6146         unRegister = genObjUnRegister()
6147         if isinstance( theElements, Mesh ):
6148             theElements = theElements.mesh
6149         elif isinstance( theElements, list ):
6150             theElements = self.GetIDSource( theElements, SMESH.ALL )
6151             unRegister.set( theElements )
6152         return self.editor.DoubleElements(theElements, theGroupName)
6153
6154     def DoubleNodes(self, theNodes, theModifiedElems):
6155         """
6156         Create a hole in a mesh by doubling the nodes of some particular elements
6157
6158         Parameters:
6159             theNodes: identifiers of nodes to be doubled
6160             theModifiedElems: identifiers of elements to be updated by the new (doubled)
6161                 nodes. If list of element identifiers is empty then nodes are doubled but
6162                 they not assigned to elements
6163
6164         Returns:
6165             TRUE if operation has been completed successfully, FALSE otherwise
6166         """
6167
6168         return self.editor.DoubleNodes(theNodes, theModifiedElems)
6169
6170     def DoubleNode(self, theNodeId, theModifiedElems):
6171         """
6172         Create a hole in a mesh by doubling the nodes of some particular elements
6173         This method provided for convenience works as DoubleNodes() described above.
6174
6175         Parameters:
6176             theNodeId: identifiers of node to be doubled
6177             theModifiedElems: identifiers of elements to be updated
6178
6179         Returns:
6180             TRUE if operation has been completed successfully, FALSE otherwise
6181         """
6182
6183         return self.editor.DoubleNode(theNodeId, theModifiedElems)
6184
6185     def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
6186         """
6187         Create a hole in a mesh by doubling the nodes of some particular elements
6188         This method provided for convenience works as DoubleNodes() described above.
6189
6190         Parameters:
6191             theNodes: group of nodes to be doubled
6192             theModifiedElems: group of elements to be updated.
6193             theMakeGroup: forces the generation of a group containing new nodes.
6194
6195         Returns:
6196             TRUE or a created group if operation has been completed successfully,
6197                 FALSE or None otherwise
6198         """
6199
6200         if theMakeGroup:
6201             return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
6202         return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
6203
6204     def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
6205         """
6206         Create a hole in a mesh by doubling the nodes of some particular elements
6207         This method provided for convenience works as DoubleNodes() described above.
6208
6209         Parameters:
6210             theNodes: list of groups of nodes to be doubled
6211             theModifiedElems: list of groups of elements to be updated.
6212             theMakeGroup: forces the generation of a group containing new nodes.
6213
6214         Returns:
6215             TRUE if operation has been completed successfully, FALSE otherwise
6216         """
6217
6218         if theMakeGroup:
6219             return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
6220         return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
6221
6222     def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
6223         """
6224         Create a hole in a mesh by doubling the nodes of some particular elements
6225
6226         Parameters:
6227             theElems: the list of elements (edges or faces) to be replicated
6228                 The nodes for duplication could be found from these elements
6229             theNodesNot: list of nodes to NOT replicate
6230             theAffectedElems: the list of elements (cells and edges) to which the
6231                 replicated nodes should be associated to.
6232
6233         Returns:
6234             TRUE if operation has been completed successfully, FALSE otherwise
6235         """
6236
6237         return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
6238
6239     def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
6240         """
6241         Create a hole in a mesh by doubling the nodes of some particular elements
6242
6243         Parameters:
6244             theElems: the list of elements (edges or faces) to be replicated
6245                 The nodes for duplication could be found from these elements
6246             theNodesNot: list of nodes to NOT replicate
6247             theShape: shape to detect affected elements (element which geometric center
6248                 located on or inside shape).
6249                 The replicated nodes should be associated to affected elements.
6250
6251         Returns:
6252             TRUE if operation has been completed successfully, FALSE otherwise
6253         """
6254
6255         return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
6256
6257     def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
6258                              theMakeGroup=False, theMakeNodeGroup=False):
6259         """
6260         Create a hole in a mesh by doubling the nodes of some particular elements
6261         This method provided for convenience works as DoubleNodes() described above.
6262
6263         Parameters:
6264             theElems: group of of elements (edges or faces) to be replicated
6265             theNodesNot: group of nodes not to replicated
6266             theAffectedElems: group of elements to which the replicated nodes
6267                 should be associated to.
6268             theMakeGroup: forces the generation of a group containing new elements.
6269             theMakeNodeGroup: forces the generation of a group containing new nodes.
6270
6271         Returns:
6272             TRUE or created groups (one or two) if operation has been completed successfully,
6273                 FALSE or None otherwise
6274         """
6275
6276         if theMakeGroup or theMakeNodeGroup:
6277             twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
6278                                                             theAffectedElems,
6279                                                             theMakeGroup, theMakeNodeGroup)
6280             if theMakeGroup and theMakeNodeGroup:
6281                 return twoGroups
6282             else:
6283                 return twoGroups[ int(theMakeNodeGroup) ]
6284         return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
6285
6286     def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
6287         """
6288         Create a hole in a mesh by doubling the nodes of some particular elements
6289         This method provided for convenience works as DoubleNodes() described above.
6290
6291         Parameters:
6292             theElems: group of of elements (edges or faces) to be replicated
6293             theNodesNot: group of nodes not to replicated
6294             theShape: shape to detect affected elements (element which geometric center
6295                 located on or inside shape).
6296                 The replicated nodes should be associated to affected elements.
6297         """
6298
6299         return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
6300
6301     def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
6302                              theMakeGroup=False, theMakeNodeGroup=False):
6303         """
6304         Create a hole in a mesh by doubling the nodes of some particular elements
6305         This method provided for convenience works as DoubleNodes() described above.
6306
6307         Parameters:
6308             theElems: list of groups of elements (edges or faces) to be replicated
6309             theNodesNot: list of groups of nodes not to replicated
6310             theAffectedElems: group of elements to which the replicated nodes
6311                 should be associated to.
6312             theMakeGroup: forces the generation of a group containing new elements.
6313             theMakeNodeGroup: forces the generation of a group containing new nodes.
6314
6315         Returns:
6316             TRUE or created groups (one or two) if operation has been completed successfully,
6317                 FALSE or None otherwise
6318         """
6319
6320         if theMakeGroup or theMakeNodeGroup:
6321             twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
6322                                                              theAffectedElems,
6323                                                              theMakeGroup, theMakeNodeGroup)
6324             if theMakeGroup and theMakeNodeGroup:
6325                 return twoGroups
6326             else:
6327                 return twoGroups[ int(theMakeNodeGroup) ]
6328         return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
6329
6330     def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
6331         """
6332         Create a hole in a mesh by doubling the nodes of some particular elements
6333         This method provided for convenience works as DoubleNodes() described above.
6334
6335         Parameters:
6336             theElems: list of groups of elements (edges or faces) to be replicated
6337             theNodesNot: list of groups of nodes not to replicated
6338             theShape: shape to detect affected elements (element which geometric center
6339                 located on or inside shape).
6340                 The replicated nodes should be associated to affected elements.
6341
6342         Returns:
6343             TRUE if operation has been completed successfully, FALSE otherwise
6344         """
6345
6346         return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
6347
6348     def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
6349         """
6350         Identify the elements that will be affected by node duplication (actual duplication is not performed.
6351         This method is the first step of DoubleNodeElemGroupsInRegion.
6352
6353         Parameters:
6354             theElems: list of groups of nodes or elements (edges or faces) to be replicated
6355             theNodesNot: list of groups of nodes not to replicated
6356             theShape: shape to detect affected elements (element which geometric center
6357                 located on or inside shape).
6358                 The replicated nodes should be associated to affected elements.
6359
6360         Returns:
6361             groups of affected elements in order:: volumes, faces, edges
6362         """
6363
6364         return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
6365
6366     def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
6367         """
6368         Double nodes on shared faces between groups of volumes and create flat elements on demand.
6369         The list of groups must describe a partition of the mesh volumes.
6370         The nodes of the internal faces at the boundaries of the groups are doubled.
6371         In option, the internal faces are replaced by flat elements.
6372         Triangles are transformed in prisms, and quadrangles in hexahedrons.
6373
6374         Parameters:
6375             theDomains: list of groups of volumes
6376             createJointElems: if TRUE, create the elements
6377             onAllBoundaries: if TRUE, the nodes and elements are also created on
6378                 the boundary between *theDomains* and the rest mesh
6379
6380         Returns:
6381             TRUE if operation has been completed successfully, FALSE otherwise
6382         """
6383
6384         return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
6385
6386     def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
6387         """
6388         Double nodes on some external faces and create flat elements.
6389         Flat elements are mainly used by some types of mechanic calculations.
6390
6391         Each group of the list must be constituted of faces.
6392         Triangles are transformed in prisms, and quadrangles in hexahedrons.
6393
6394         Parameters:
6395             theGroupsOfFaces: list of groups of faces
6396
6397         Returns:
6398             TRUE if operation has been completed successfully, FALSE otherwise
6399         """
6400
6401         return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
6402
6403     def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
6404         """
6405         identify all the elements around a geom shape, get the faces delimiting the hole
6406         """
6407         return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
6408
6409     def MakePolyLine(self, segments, groupName='', isPreview=False ):
6410         """    
6411         Create a polyline consisting of 1D mesh elements each lying on a 2D element of
6412         the initial mesh. Positions of new nodes are found by cutting the mesh by the
6413         plane passing through pairs of points specified by each PolySegment structure.
6414         If there are several paths connecting a pair of points, the shortest path is
6415         selected by the module. Position of the cutting plane is defined by the two
6416         points and an optional vector lying on the plane specified by a PolySegment.
6417         By default the vector is defined by Mesh module as following. A middle point
6418         of the two given points is computed. The middle point is projected to the mesh.
6419         The vector goes from the middle point to the projection point. In case of planar
6420         mesh, the vector is normal to the mesh.
6421
6422         Parameters:        
6423             segments - PolySegment's defining positions of cutting planes.
6424             groupName - optional name of a group where created mesh segments will
6425             be added.
6426             
6427         Returns:    
6428             The used vector which goes from the middle point to its projection.
6429         """    
6430         editor = self.editor
6431         if isPreview:
6432             editor = self.mesh.GetMeshEditPreviewer()
6433         segmentsRes = editor.MakePolyLine( segments, groupName )
6434         for i, seg in enumerate( segmentsRes ):
6435             segments[i].vector = seg.vector
6436         if isPreview:
6437             return editor.GetPreviewData()
6438         return None        
6439
6440     def GetFunctor(self, funcType ):
6441         """
6442         Return a cached numerical functor by its type.
6443
6444         Parameters:
6445             theCriterion functor type: an item of SMESH.FunctorType enumeration.
6446                 Type SMESH.FunctorType._items in the Python Console to see all items.
6447                 Note that not all items correspond to numerical functors.
6448
6449         Returns:
6450             SMESH_NumericalFunctor. The functor is already initialized
6451                 with a mesh
6452         """
6453
6454         fn = self.functors[ funcType._v ]
6455         if not fn:
6456             fn = self.smeshpyD.GetFunctor(funcType)
6457             fn.SetMesh(self.mesh)
6458             self.functors[ funcType._v ] = fn
6459         return fn
6460
6461     def FunctorValue(self, funcType, elemId, isElem=True):
6462         """
6463         Return value of a functor for a given element
6464
6465         Parameters:
6466             funcType: an item of SMESH.FunctorType enum
6467                 Type "SMESH.FunctorType._items" in the Python Console to see all items.
6468             elemId: element or node ID
6469             isElem: *elemId* is ID of element or node
6470
6471         Returns:
6472             the functor value or zero in case of invalid arguments
6473         """
6474
6475         fn = self.GetFunctor( funcType )
6476         if fn.GetElementType() == self.GetElementType(elemId, isElem):
6477             val = fn.GetValue(elemId)
6478         else:
6479             val = 0
6480         return val
6481
6482     def GetLength(self, elemId=None):
6483         """
6484         Get length of 1D element or sum of lengths of all 1D mesh elements
6485
6486         Parameters:
6487             elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
6488
6489         Returns:
6490             element's length value if *elemId* is specified or sum of all 1D mesh elements' lengths otherwise
6491         """
6492
6493         length = 0
6494         if elemId == None:
6495             length = self.smeshpyD.GetLength(self)
6496         else:
6497             length = self.FunctorValue(SMESH.FT_Length, elemId)
6498         return length
6499
6500     def GetArea(self, elemId=None):
6501         """
6502         Get area of 2D element or sum of areas of all 2D mesh elements
6503             elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
6504
6505         Returns:
6506             element's area value if *elemId* is specified or sum of all 2D mesh elements' areas otherwise
6507         """
6508
6509         area = 0
6510         if elemId == None:
6511             area = self.smeshpyD.GetArea(self)
6512         else:
6513             area = self.FunctorValue(SMESH.FT_Area, elemId)
6514         return area
6515
6516     def GetVolume(self, elemId=None):
6517         """
6518         Get volume of 3D element or sum of volumes of all 3D mesh elements
6519             elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
6520
6521         Returns:
6522             element's volume value if *elemId* is specified or sum of all 3D mesh elements' volumes otherwise
6523         """
6524
6525         volume = 0
6526         if elemId == None:
6527             volume = self.smeshpyD.GetVolume(self)
6528         else:
6529             volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
6530         return volume
6531
6532     def GetMaxElementLength(self, elemId):
6533         """
6534         Get maximum element length.
6535
6536         Parameters:
6537             elemId mesh element ID
6538
6539         Returns:
6540             element's maximum length value
6541         """
6542
6543         if self.GetElementType(elemId, True) == SMESH.VOLUME:
6544             ftype = SMESH.FT_MaxElementLength3D
6545         else:
6546             ftype = SMESH.FT_MaxElementLength2D
6547         return self.FunctorValue(ftype, elemId)
6548
6549     def GetAspectRatio(self, elemId):
6550         """
6551         Get aspect ratio of 2D or 3D element.
6552
6553         Parameters:
6554             elemId mesh element ID
6555
6556         Returns:
6557             element's aspect ratio value
6558         """
6559
6560         if self.GetElementType(elemId, True) == SMESH.VOLUME:
6561             ftype = SMESH.FT_AspectRatio3D
6562         else:
6563             ftype = SMESH.FT_AspectRatio
6564         return self.FunctorValue(ftype, elemId)
6565
6566     def GetWarping(self, elemId):
6567         """
6568         Get warping angle of 2D element.
6569
6570         Parameters:
6571             elemId mesh element ID
6572
6573         Returns:
6574             element's warping angle value
6575         """
6576
6577         return self.FunctorValue(SMESH.FT_Warping, elemId)
6578
6579     def GetMinimumAngle(self, elemId):
6580         """
6581         Get minimum angle of 2D element.
6582
6583         Parameters:
6584             elemId mesh element ID
6585
6586         Returns:
6587             element's minimum angle value
6588         """
6589
6590         return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
6591
6592     def GetTaper(self, elemId):
6593         """
6594         Get taper of 2D element.
6595
6596         Parameters:
6597             elemId mesh element ID
6598
6599         Returns:
6600             element's taper value
6601         """
6602
6603         return self.FunctorValue(SMESH.FT_Taper, elemId)
6604
6605     def GetSkew(self, elemId):
6606         """
6607         Get skew of 2D element.
6608
6609         Parameters:
6610             elemId mesh element ID
6611
6612         Returns:
6613             element's skew value
6614         """
6615
6616         return self.FunctorValue(SMESH.FT_Skew, elemId)
6617
6618     def GetMinMax(self, funType, meshPart=None):
6619         """
6620         Return minimal and maximal value of a given functor.
6621
6622         Parameters:
6623             funType a functor type, an item of SMESH.FunctorType enum
6624                 (one of SMESH.FunctorType._items)
6625             meshPart a part of mesh (group, sub-mesh) to treat
6626
6627         Returns:
6628             tuple (min,max)
6629         """
6630
6631         unRegister = genObjUnRegister()
6632         if isinstance( meshPart, list ):
6633             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
6634             unRegister.set( meshPart )
6635         if isinstance( meshPart, Mesh ):
6636             meshPart = meshPart.mesh
6637         fun = self.GetFunctor( funType )
6638         if fun:
6639             if meshPart:
6640                 if hasattr( meshPart, "SetMesh" ):
6641                     meshPart.SetMesh( self.mesh ) # set mesh to filter
6642                 hist = fun.GetLocalHistogram( 1, False, meshPart )
6643             else:
6644                 hist = fun.GetHistogram( 1, False )
6645             if hist:
6646                 return hist[0].min, hist[0].max
6647         return None
6648
6649     pass # end of Mesh class
6650
6651
6652 class meshProxy(SMESH._objref_SMESH_Mesh):
6653     """
6654     Private class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
6655     with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
6656     """
6657     def __init__(self):
6658         SMESH._objref_SMESH_Mesh.__init__(self)
6659     def __deepcopy__(self, memo=None):
6660         new = self.__class__()
6661         return new
6662     def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
6663         if len( args ) == 3:
6664             args += SMESH.ALL_NODES, True
6665         return SMESH._objref_SMESH_Mesh.CreateDimGroup( self, *args )
6666     pass
6667 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
6668
6669
6670 class submeshProxy(SMESH._objref_SMESH_subMesh):
6671     """
6672     Private class wrapping SMESH.SMESH_SubMesh in order to add Compute()
6673     """
6674     def __init__(self):
6675         SMESH._objref_SMESH_subMesh.__init__(self)
6676         self.mesh = None
6677     def __deepcopy__(self, memo=None):
6678         new = self.__class__()
6679         return new
6680
6681     def Compute(self,refresh=False):
6682         """
6683         Compute the sub-mesh and return the status of the computation
6684             refresh if *True*, Object browser is automatically updated (when running in GUI)
6685
6686         Returns:
6687             True or False
6688         This is a method of SMESH.SMESH_submesh that can be obtained via Mesh.GetSubMesh() or
6689         :meth:`smeshBuilder.Mesh.GetSubMesh`.
6690         """
6691
6692         if not self.mesh:
6693             self.mesh = Mesh( smeshBuilder(), None, self.GetMesh())
6694
6695         ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
6696
6697         if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
6698             smeshgui = salome.ImportComponentGUI("SMESH")
6699             smeshgui.Init(self.mesh.GetStudyId())
6700             smeshgui.SetMeshIcon( salome.ObjectToID( self ), ok, (self.GetNumberOfElements()==0) )
6701             if refresh: salome.sg.updateObjBrowser(True)
6702             pass
6703
6704         return ok
6705     pass
6706 omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy)
6707
6708
6709 class meshEditor(SMESH._objref_SMESH_MeshEditor):
6710     """
6711     Private class used to compensate change of CORBA API of SMESH_MeshEditor for backward
6712     compatibility with old dump scripts which call SMESH_MeshEditor directly and not via
6713     smeshBuilder.Mesh
6714     """
6715     def __init__(self):
6716         SMESH._objref_SMESH_MeshEditor.__init__(self)
6717         self.mesh = None
6718     def __getattr__(self, name ): # method called if an attribute not found
6719         if not self.mesh:         # look for name() method in Mesh class
6720             self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
6721         if hasattr( self.mesh, name ):
6722             return getattr( self.mesh, name )
6723         if name == "ExtrusionAlongPathObjX":
6724             return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
6725         print "meshEditor: attribute '%s' NOT FOUND" % name
6726         return None
6727     def __deepcopy__(self, memo=None):
6728         new = self.__class__()
6729         return new
6730     def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
6731         if len( args ) == 1: args += False,
6732         return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
6733     def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
6734         if len( args ) == 2: args += False,
6735         return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
6736     def MergeNodes(self,*args): # 2 args added (NodesToKeep,AvoidMakingHoles)
6737         if len( args ) == 1:
6738             return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [], False )
6739         NodesToKeep = args[1]
6740         AvoidMakingHoles = args[2] if len( args ) == 3 else False
6741         unRegister  = genObjUnRegister()
6742         if NodesToKeep:
6743             if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
6744                 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
6745             if not isinstance( NodesToKeep, list ):
6746                 NodesToKeep = [ NodesToKeep ]
6747         return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep, AvoidMakingHoles )
6748     pass
6749 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
6750
6751 class Pattern(SMESH._objref_SMESH_Pattern):
6752     """
6753     Private class wrapping SMESH.SMESH_Pattern CORBA class in order to treat Notebook
6754     variables in some methods
6755     """
6756
6757     def LoadFromFile(self, patternTextOrFile ):
6758         text = patternTextOrFile
6759         if os.path.exists( text ):
6760             text = open( patternTextOrFile ).read()
6761             pass
6762         return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
6763
6764     def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
6765         decrFun = lambda i: i-1
6766         theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
6767         theMesh.SetParameters(Parameters)
6768         return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
6769
6770     def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
6771         decrFun = lambda i: i-1
6772         theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
6773         theMesh.SetParameters(Parameters)
6774         return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
6775
6776     def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
6777         if isinstance( mesh, Mesh ):
6778             mesh = mesh.GetMesh()
6779         return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
6780
6781 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
6782 """
6783 Registering the new proxy for Pattern
6784 """
6785
6786 class algoCreator:
6787     """
6788     Private class used to bind methods creating algorithms to the class Mesh
6789     """
6790
6791     def __init__(self, method):
6792         self.mesh = None
6793         self.defaultAlgoType = ""
6794         self.algoTypeToClass = {}
6795         self.method = method
6796
6797     def add(self, algoClass):
6798         """
6799         Store a python class of algorithm
6800         """
6801         if type( algoClass ).__name__ == 'classobj' and \
6802            hasattr( algoClass, "algoType"):
6803             self.algoTypeToClass[ algoClass.algoType ] = algoClass
6804             if not self.defaultAlgoType and \
6805                hasattr( algoClass, "isDefault") and algoClass.isDefault:
6806                 self.defaultAlgoType = algoClass.algoType
6807             #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
6808
6809     def copy(self, mesh):
6810         """
6811         Create a copy of self and assign mesh to the copy
6812         """
6813
6814         other = algoCreator( self.method )
6815         other.defaultAlgoType = self.defaultAlgoType
6816         other.algoTypeToClass = self.algoTypeToClass
6817         other.mesh = mesh
6818         return other
6819
6820     def __call__(self,algo="",geom=0,*args):
6821         """
6822         Create an instance of algorithm
6823         """
6824         algoType = ""
6825         shape = 0
6826         if isinstance( algo, str ):
6827             algoType = algo
6828         elif ( isinstance( algo, geomBuilder.GEOM._objref_GEOM_Object ) and \
6829                not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object )):
6830             shape = algo
6831         elif algo:
6832             args += (algo,)
6833
6834         if isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
6835             shape = geom
6836         elif not algoType and isinstance( geom, str ):
6837             algoType = geom
6838         elif geom:
6839             args += (geom,)
6840         for arg in args:
6841             if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ) and not shape:
6842                 shape = arg
6843             elif isinstance( arg, str ) and not algoType:
6844                 algoType = arg
6845             else:
6846                 import traceback, sys
6847                 msg = "Warning. Unexpected argument in mesh.%s() --->  %s" % ( self.method, arg )
6848                 sys.stderr.write( msg + '\n' )
6849                 tb = traceback.extract_stack(None,2)
6850                 traceback.print_list( [tb[0]] )
6851         if not algoType:
6852             algoType = self.defaultAlgoType
6853         if not algoType and self.algoTypeToClass:
6854             algoType = sorted( self.algoTypeToClass.keys() )[0]
6855         if self.algoTypeToClass.has_key( algoType ):
6856             #print "Create algo",algoType
6857             return self.algoTypeToClass[ algoType ]( self.mesh, shape )
6858         raise RuntimeError, "No class found for algo type %s" % algoType
6859         return None
6860
6861 class hypMethodWrapper:
6862     """
6863     Private class used to substitute and store variable parameters of hypotheses.
6864     """
6865
6866     def __init__(self, hyp, method):
6867         self.hyp    = hyp
6868         self.method = method
6869         #print "REBIND:", method.__name__
6870         return
6871
6872     def __call__(self,*args):
6873         """
6874         call a method of hypothesis with calling SetVarParameter() before
6875         """
6876
6877         if not args:
6878             return self.method( self.hyp, *args ) # hypothesis method with no args
6879
6880         #print "MethWrapper.__call__",self.method.__name__, args
6881         try:
6882             parsed = ParseParameters(*args)     # replace variables with their values
6883             self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
6884             result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
6885         except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
6886             # maybe there is a replaced string arg which is not variable
6887             result = self.method( self.hyp, *args )
6888         except ValueError, detail: # raised by ParseParameters()
6889             try:
6890                 result = self.method( self.hyp, *args )
6891             except omniORB.CORBA.BAD_PARAM:
6892                 raise ValueError, detail # wrong variable name
6893
6894         return result
6895     pass
6896
6897 class genObjUnRegister:
6898     """
6899     A helper class that calls UnRegister() of SALOME.GenericObj'es stored in it
6900     """
6901
6902     def __init__(self, genObj=None):
6903         self.genObjList = []
6904         self.set( genObj )
6905         return
6906
6907     def set(self, genObj):
6908         "Store one or a list of of SALOME.GenericObj'es"
6909         if isinstance( genObj, list ):
6910             self.genObjList.extend( genObj )
6911         else:
6912             self.genObjList.append( genObj )
6913         return
6914
6915     def __del__(self):
6916         for genObj in self.genObjList:
6917             if genObj and hasattr( genObj, "UnRegister" ):
6918                 genObj.UnRegister()
6919
6920 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
6921     """
6922     Bind methods creating mesher plug-ins to the Mesh class
6923     """
6924
6925     # print "pluginName: ", pluginName
6926     pluginBuilderName = pluginName + "Builder"
6927     try:
6928         exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
6929     except Exception, e:
6930         from salome_utils import verbose
6931         if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
6932         continue
6933     exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
6934     plugin = eval( pluginBuilderName )
6935     # print "  plugin:" , str(plugin)
6936
6937     # add methods creating algorithms to Mesh
6938     for k in dir( plugin ):
6939         if k[0] == '_': continue
6940         algo = getattr( plugin, k )
6941         # print "             algo:", str(algo)
6942         if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
6943             # print "                     meshMethod:" , str(algo.meshMethod)
6944             if not hasattr( Mesh, algo.meshMethod ):
6945                 setattr( Mesh, algo.meshMethod, algoCreator( algo.meshMethod ))
6946                 pass
6947             _mmethod = getattr( Mesh, algo.meshMethod )
6948             if hasattr(  _mmethod, "add" ):
6949                 _mmethod.add(algo)
6950             pass
6951         pass
6952     pass
6953 del pluginName