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