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