Salome HOME
53076: OCC exception in Netgen algorithm (regression of StdMeshers_QuadToTriaAdaptor...
[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             for err in computeErrors:
1428                 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1429                 errText = ""
1430                 stdErrors = ["OK",                   #COMPERR_OK
1431                              "Invalid input mesh",   #COMPERR_BAD_INPUT_MESH
1432                              "std::exception",       #COMPERR_STD_EXCEPTION
1433                              "OCC exception",        #COMPERR_OCC_EXCEPTION
1434                              "..",                   #COMPERR_SLM_EXCEPTION
1435                              "Unknown exception",    #COMPERR_EXCEPTION
1436                              "Memory allocation problem", #COMPERR_MEMORY_PB
1437                              "Algorithm failed",     #COMPERR_ALGO_FAILED
1438                              "Unexpected geometry",  #COMPERR_BAD_SHAPE
1439                              "Warning",              #COMPERR_WARNING
1440                              "Computation cancelled",#COMPERR_CANCELED
1441                              "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1442                 if err.code > 0:
1443                     if err.code < len(stdErrors): errText = stdErrors[err.code]
1444                 else:
1445                     errText = "code %s" % -err.code
1446                 if errText: errText += ". "
1447                 errText += err.comment
1448                 if allReasons != "":allReasons += "\n"
1449                 if ok:
1450                     allReasons += '-  "%s"%s - %s' %(err.algoName, shapeText, errText)
1451                 else:
1452                     allReasons += '-  "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1453                 pass
1454
1455             # Treat hyp errors
1456             errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1457             for err in errors:
1458                 if err.isGlobalAlgo:
1459                     glob = "global"
1460                 else:
1461                     glob = "local"
1462                     pass
1463                 dim = err.algoDim
1464                 name = err.algoName
1465                 if len(name) == 0:
1466                     reason = '%s %sD algorithm is missing' % (glob, dim)
1467                 elif err.state == HYP_MISSING:
1468                     reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1469                               % (glob, dim, name, dim))
1470                 elif err.state == HYP_NOTCONFORM:
1471                     reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1472                 elif err.state == HYP_BAD_PARAMETER:
1473                     reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1474                               % ( glob, dim, name ))
1475                 elif err.state == HYP_BAD_GEOMETRY:
1476                     reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1477                               'geometry' % ( glob, dim, name ))
1478                 elif err.state == HYP_HIDDEN_ALGO:
1479                     reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1480                               'algorithm of upper dimension generating %sD mesh'
1481                               % ( glob, dim, name, glob, dim ))
1482                 else:
1483                     reason = ("For unknown reason. "
1484                               "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1485                     pass
1486                 if allReasons != "":allReasons += "\n"
1487                 allReasons += "-  " + reason
1488                 pass
1489             if not ok or allReasons != "":
1490                 msg = '"' + GetName(self.mesh) + '"'
1491                 if ok: msg += " has been computed with warnings"
1492                 else:  msg += " has not been computed"
1493                 if allReasons != "": msg += ":"
1494                 else:                msg += "."
1495                 print msg
1496                 print allReasons
1497             pass
1498         if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1499             smeshgui = salome.ImportComponentGUI("SMESH")
1500             smeshgui.Init(self.mesh.GetStudyId())
1501             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1502             if refresh: salome.sg.updateObjBrowser(1)
1503             pass
1504         return ok
1505
1506     ## Return a name of a sub-shape by its ID
1507     #  @param subShapeID a unique ID of a sub-shape
1508     #  @return a string describing the sub-shape; possible variants:
1509     #  - "Face_12"    (published sub-shape)
1510     #  - FACE #3      (not published sub-shape)
1511     #  - sub-shape #3 (invalid sub-shape ID)
1512     #  - #3           (error in this function)
1513     def GetSubShapeName(self, subShapeID ):
1514         if not self.mesh.HasShapeToMesh():
1515             return ""
1516         try:
1517             shapeText = ""
1518             mainIOR  = salome.orb.object_to_string( self.GetShape() )
1519             for sname in salome.myStudyManager.GetOpenStudies():
1520                 s = salome.myStudyManager.GetStudyByName(sname)
1521                 if not s: continue
1522                 mainSO = s.FindObjectIOR(mainIOR)
1523                 if not mainSO: continue
1524                 if subShapeID == 1:
1525                     shapeText = '"%s"' % mainSO.GetName()
1526                 subIt = s.NewChildIterator(mainSO)
1527                 while subIt.More():
1528                     subSO = subIt.Value()
1529                     subIt.Next()
1530                     obj = subSO.GetObject()
1531                     if not obj: continue
1532                     go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1533                     if not go: continue
1534                     try:
1535                         ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1536                     except:
1537                         continue
1538                     if ids == subShapeID:
1539                         shapeText = '"%s"' % subSO.GetName()
1540                         break
1541             if not shapeText:
1542                 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1543                 if shape:
1544                     shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1545                 else:
1546                     shapeText = 'sub-shape #%s' % (subShapeID)
1547         except:
1548             shapeText = "#%s" % (subShapeID)
1549         return shapeText
1550
1551     ## Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1552     #  error of an algorithm
1553     #  @param publish if @c True, the returned groups will be published in the study
1554     #  @return a list of GEOM groups each named after a failed algorithm
1555     def GetFailedShapes(self, publish=False):
1556
1557         algo2shapes = {}
1558         computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1559         for err in computeErrors:
1560             shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1561             if not shape: continue
1562             if err.algoName in algo2shapes:
1563                 algo2shapes[ err.algoName ].append( shape )
1564             else:
1565                 algo2shapes[ err.algoName ] = [ shape ]
1566             pass
1567
1568         groups = []
1569         for algoName, shapes in algo2shapes.items():
1570             while shapes:
1571                 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1572                 otherTypeShapes = []
1573                 sameTypeShapes  = []
1574                 group = self.geompyD.CreateGroup( self.geom, groupType )
1575                 for shape in shapes:
1576                     if shape.GetShapeType() == shapes[0].GetShapeType():
1577                         sameTypeShapes.append( shape )
1578                     else:
1579                         otherTypeShapes.append( shape )
1580                 self.geompyD.UnionList( group, sameTypeShapes )
1581                 if otherTypeShapes:
1582                     group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1583                 else:
1584                     group.SetName( algoName )
1585                 groups.append( group )
1586                 shapes = otherTypeShapes
1587             pass
1588         if publish:
1589             for group in groups:
1590                 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1591         return groups
1592
1593     ## Return sub-mesh objects list in meshing order
1594     #  @return list of list of sub-meshes
1595     #  @ingroup l2_construct
1596     def GetMeshOrder(self):
1597         return self.mesh.GetMeshOrder()
1598
1599     ## Set order in which concurrent sub-meshes sould be meshed
1600     #  @param submeshes list of sub-meshes
1601     #  @ingroup l2_construct
1602     def SetMeshOrder(self, submeshes):
1603         return self.mesh.SetMeshOrder(submeshes)
1604
1605     ## Removes all nodes and elements
1606     #  @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1607     #  @ingroup l2_construct
1608     def Clear(self, refresh=False):
1609         self.mesh.Clear()
1610         if ( salome.sg.hasDesktop() and 
1611              salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1612             smeshgui = salome.ImportComponentGUI("SMESH")
1613             smeshgui.Init(self.mesh.GetStudyId())
1614             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1615             if refresh: salome.sg.updateObjBrowser(1)
1616
1617     ## Removes all nodes and elements of indicated shape
1618     #  @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1619     #  @param geomId the ID of a sub-shape to remove elements on
1620     #  @ingroup l2_construct
1621     def ClearSubMesh(self, geomId, refresh=False):
1622         self.mesh.ClearSubMesh(geomId)
1623         if salome.sg.hasDesktop():
1624             smeshgui = salome.ImportComponentGUI("SMESH")
1625             smeshgui.Init(self.mesh.GetStudyId())
1626             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1627             if refresh: salome.sg.updateObjBrowser(1)
1628
1629     ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1630     #  @param fineness [0.0,1.0] defines mesh fineness
1631     #  @return True or False
1632     #  @ingroup l3_algos_basic
1633     def AutomaticTetrahedralization(self, fineness=0):
1634         dim = self.MeshDimension()
1635         # assign hypotheses
1636         self.RemoveGlobalHypotheses()
1637         self.Segment().AutomaticLength(fineness)
1638         if dim > 1 :
1639             self.Triangle().LengthFromEdges()
1640             pass
1641         if dim > 2 :
1642             self.Tetrahedron()
1643             pass
1644         return self.Compute()
1645
1646     ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1647     #  @param fineness [0.0, 1.0] defines mesh fineness
1648     #  @return True or False
1649     #  @ingroup l3_algos_basic
1650     def AutomaticHexahedralization(self, fineness=0):
1651         dim = self.MeshDimension()
1652         # assign the hypotheses
1653         self.RemoveGlobalHypotheses()
1654         self.Segment().AutomaticLength(fineness)
1655         if dim > 1 :
1656             self.Quadrangle()
1657             pass
1658         if dim > 2 :
1659             self.Hexahedron()
1660             pass
1661         return self.Compute()
1662
1663     ## Assigns a hypothesis
1664     #  @param hyp a hypothesis to assign
1665     #  @param geom a subhape of mesh geometry
1666     #  @return SMESH.Hypothesis_Status
1667     #  @ingroup l2_hypotheses
1668     def AddHypothesis(self, hyp, geom=0):
1669         if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1670             hyp, geom = geom, hyp
1671         if isinstance( hyp, Mesh_Algorithm ):
1672             hyp = hyp.GetAlgorithm()
1673             pass
1674         if not geom:
1675             geom = self.geom
1676             if not geom:
1677                 geom = self.mesh.GetShapeToMesh()
1678             pass
1679         isApplicable = True
1680         if self.mesh.HasShapeToMesh():
1681             hyp_type     = hyp.GetName()
1682             lib_name     = hyp.GetLibName()
1683             # checkAll    = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1684             # if checkAll and geom:
1685             #     checkAll = geom.GetType() == 37
1686             checkAll     = False
1687             isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1688         if isApplicable:
1689             AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1690             status = self.mesh.AddHypothesis(geom, hyp)
1691         else:
1692             status = HYP_BAD_GEOMETRY,""
1693         hyp_name = GetName( hyp )
1694         geom_name = ""
1695         if geom:
1696             geom_name = geom.GetName()
1697         isAlgo = hyp._narrow( SMESH_Algo )
1698         TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1699         return status
1700
1701     ## Return True if an algorithm of hypothesis is assigned to a given shape
1702     #  @param hyp a hypothesis to check
1703     #  @param geom a subhape of mesh geometry
1704     #  @return True of False
1705     #  @ingroup l2_hypotheses
1706     def IsUsedHypothesis(self, hyp, geom):
1707         if not hyp: # or not geom
1708             return False
1709         if isinstance( hyp, Mesh_Algorithm ):
1710             hyp = hyp.GetAlgorithm()
1711             pass
1712         hyps = self.GetHypothesisList(geom)
1713         for h in hyps:
1714             if h.GetId() == hyp.GetId():
1715                 return True
1716         return False
1717
1718     ## Unassigns a hypothesis
1719     #  @param hyp a hypothesis to unassign
1720     #  @param geom a sub-shape of mesh geometry
1721     #  @return SMESH.Hypothesis_Status
1722     #  @ingroup l2_hypotheses
1723     def RemoveHypothesis(self, hyp, geom=0):
1724         if not hyp:
1725             return None
1726         if isinstance( hyp, Mesh_Algorithm ):
1727             hyp = hyp.GetAlgorithm()
1728             pass
1729         shape = geom
1730         if not shape:
1731             shape = self.geom
1732             pass
1733         if self.IsUsedHypothesis( hyp, shape ):
1734             return self.mesh.RemoveHypothesis( shape, hyp )
1735         hypName = GetName( hyp )
1736         geoName = GetName( shape )
1737         print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1738         return None
1739
1740     ## Gets the list of hypotheses added on a geometry
1741     #  @param geom a sub-shape of mesh geometry
1742     #  @return the sequence of SMESH_Hypothesis
1743     #  @ingroup l2_hypotheses
1744     def GetHypothesisList(self, geom):
1745         return self.mesh.GetHypothesisList( geom )
1746
1747     ## Removes all global hypotheses
1748     #  @ingroup l2_hypotheses
1749     def RemoveGlobalHypotheses(self):
1750         current_hyps = self.mesh.GetHypothesisList( self.geom )
1751         for hyp in current_hyps:
1752             self.mesh.RemoveHypothesis( self.geom, hyp )
1753             pass
1754         pass
1755
1756    ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1757     ## allowing to overwrite the file if it exists or add the exported data to its contents
1758     #  @param f is the file name
1759     #  @param auto_groups boolean parameter for creating/not creating
1760     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1761     #  the typical use is auto_groups=false.
1762     #  @param version MED format version(MED_V2_1 or MED_V2_2)
1763     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1764     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1765     #  @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1766     #         - 1D if all mesh nodes lie on OX coordinate axis, or
1767     #         - 2D if all mesh nodes lie on XOY coordinate plane, or
1768     #         - 3D in the rest cases.
1769     #         If @a autoDimension is @c False, the space dimension is always 3.
1770     #  @param fields : list of GEOM fields defined on the shape to mesh.
1771     #  @param geomAssocFields : each character of this string means a need to export a 
1772     #         corresponding field; correspondence between fields and characters is following:
1773     #         - 'v' stands for _vertices_ field;
1774     #         - 'e' stands for _edges_ field;
1775     #         - 'f' stands for _faces_ field;
1776     #         - 's' stands for _solids_ field.
1777     #  @ingroup l2_impexp
1778     def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1779                   overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1780         if meshPart or fields or geomAssocFields:
1781             unRegister = genObjUnRegister()
1782             if isinstance( meshPart, list ):
1783                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1784                 unRegister.set( meshPart )
1785             self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1786                                        fields, geomAssocFields)
1787         else:
1788             self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1789
1790     ## Exports the mesh in a file in SAUV format
1791     #  @param f is the file name
1792     #  @param auto_groups boolean parameter for creating/not creating
1793     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1794     #  the typical use is auto_groups=false.
1795     #  @ingroup l2_impexp
1796     def ExportSAUV(self, f, auto_groups=0):
1797         self.mesh.ExportSAUV(f, auto_groups)
1798
1799     ## Exports the mesh in a file in DAT format
1800     #  @param f the file name
1801     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1802     #  @ingroup l2_impexp
1803     def ExportDAT(self, f, meshPart=None):
1804         if meshPart:
1805             unRegister = genObjUnRegister()
1806             if isinstance( meshPart, list ):
1807                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1808                 unRegister.set( meshPart )
1809             self.mesh.ExportPartToDAT( meshPart, f )
1810         else:
1811             self.mesh.ExportDAT(f)
1812
1813     ## Exports the mesh in a file in UNV format
1814     #  @param f the file name
1815     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1816     #  @ingroup l2_impexp
1817     def ExportUNV(self, f, meshPart=None):
1818         if meshPart:
1819             unRegister = genObjUnRegister()
1820             if isinstance( meshPart, list ):
1821                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1822                 unRegister.set( meshPart )
1823             self.mesh.ExportPartToUNV( meshPart, f )
1824         else:
1825             self.mesh.ExportUNV(f)
1826
1827     ## Export the mesh in a file in STL format
1828     #  @param f the file name
1829     #  @param ascii defines the file encoding
1830     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1831     #  @ingroup l2_impexp
1832     def ExportSTL(self, f, ascii=1, meshPart=None):
1833         if meshPart:
1834             unRegister = genObjUnRegister()
1835             if isinstance( meshPart, list ):
1836                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1837                 unRegister.set( meshPart )
1838             self.mesh.ExportPartToSTL( meshPart, f, ascii )
1839         else:
1840             self.mesh.ExportSTL(f, ascii)
1841
1842     ## Exports the mesh in a file in CGNS format
1843     #  @param f is the file name
1844     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1845     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1846     #  @ingroup l2_impexp
1847     def ExportCGNS(self, f, overwrite=1, meshPart=None):
1848         unRegister = genObjUnRegister()
1849         if isinstance( meshPart, list ):
1850             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1851             unRegister.set( meshPart )
1852         if isinstance( meshPart, Mesh ):
1853             meshPart = meshPart.mesh
1854         elif not meshPart:
1855             meshPart = self.mesh
1856         self.mesh.ExportCGNS(meshPart, f, overwrite)
1857
1858     ## Exports the mesh in a file in GMF format.
1859     #  GMF files must have .mesh extension for the ASCII format and .meshb for
1860     #  the bynary format. Other extensions are not allowed.
1861     #  @param f is the file name
1862     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1863     #  @ingroup l2_impexp
1864     def ExportGMF(self, f, meshPart=None):
1865         unRegister = genObjUnRegister()
1866         if isinstance( meshPart, list ):
1867             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1868             unRegister.set( meshPart )
1869         if isinstance( meshPart, Mesh ):
1870             meshPart = meshPart.mesh
1871         elif not meshPart:
1872             meshPart = self.mesh
1873         self.mesh.ExportGMF(meshPart, f, True)
1874
1875     ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1876     #  Exports the mesh in a file in MED format and chooses the \a version of MED format
1877     ## allowing to overwrite the file if it exists or add the exported data to its contents
1878     #  @param f the file name
1879     #  @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1880     #  @param opt boolean parameter for creating/not creating
1881     #         the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1882     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1883     #  @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1884     #         - 1D if all mesh nodes lie on OX coordinate axis, or
1885     #         - 2D if all mesh nodes lie on XOY coordinate plane, or
1886     #         - 3D in the rest cases.
1887     #
1888     #         If @a autoDimension is @c False, the space dimension is always 3.
1889     #  @ingroup l2_impexp
1890     def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1891         self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1892
1893     # Operations with groups:
1894     # ----------------------
1895
1896     ## Creates an empty mesh group
1897     #  @param elementType the type of elements in the group; either of 
1898     #         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1899     #  @param name the name of the mesh group
1900     #  @return SMESH_Group
1901     #  @ingroup l2_grps_create
1902     def CreateEmptyGroup(self, elementType, name):
1903         return self.mesh.CreateGroup(elementType, name)
1904
1905     ## Creates a mesh group based on the geometric object \a grp
1906     #  and gives a \a name, \n if this parameter is not defined
1907     #  the name is the same as the geometric group name \n
1908     #  Note: Works like GroupOnGeom().
1909     #  @param grp  a geometric group, a vertex, an edge, a face or a solid
1910     #  @param name the name of the mesh group
1911     #  @return SMESH_GroupOnGeom
1912     #  @ingroup l2_grps_create
1913     def Group(self, grp, name=""):
1914         return self.GroupOnGeom(grp, name)
1915
1916     ## Creates a mesh group based on the geometrical object \a grp
1917     #  and gives a \a name, \n if this parameter is not defined
1918     #  the name is the same as the geometrical group name
1919     #  @param grp  a geometrical group, a vertex, an edge, a face or a solid
1920     #  @param name the name of the mesh group
1921     #  @param typ  the type of elements in the group; either of 
1922     #         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
1923     #         automatically detected by the type of the geometry
1924     #  @return SMESH_GroupOnGeom
1925     #  @ingroup l2_grps_create
1926     def GroupOnGeom(self, grp, name="", typ=None):
1927         AssureGeomPublished( self, grp, name )
1928         if name == "":
1929             name = grp.GetName()
1930         if not typ:
1931             typ = self._groupTypeFromShape( grp )
1932         return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1933
1934     ## Pivate method to get a type of group on geometry
1935     def _groupTypeFromShape( self, shape ):
1936         tgeo = str(shape.GetShapeType())
1937         if tgeo == "VERTEX":
1938             typ = NODE
1939         elif tgeo == "EDGE":
1940             typ = EDGE
1941         elif tgeo == "FACE" or tgeo == "SHELL":
1942             typ = FACE
1943         elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1944             typ = VOLUME
1945         elif tgeo == "COMPOUND":
1946             sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1947             if not sub:
1948                 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1949             return self._groupTypeFromShape( sub[0] )
1950         else:
1951             raise ValueError, \
1952                   "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1953         return typ
1954
1955     ## Creates a mesh group with given \a name based on the \a filter which
1956     ## is a special type of group dynamically updating it's contents during
1957     ## mesh modification
1958     #  @param typ  the type of elements in the group; either of 
1959     #         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1960     #  @param name the name of the mesh group
1961     #  @param filter the filter defining group contents
1962     #  @return SMESH_GroupOnFilter
1963     #  @ingroup l2_grps_create
1964     def GroupOnFilter(self, typ, name, filter):
1965         return self.mesh.CreateGroupFromFilter(typ, name, filter)
1966
1967     ## Creates a mesh group by the given ids of elements
1968     #  @param groupName the name of the mesh group
1969     #  @param elementType the type of elements in the group; either of 
1970     #         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1971     #  @param elemIDs the list of ids
1972     #  @return SMESH_Group
1973     #  @ingroup l2_grps_create
1974     def MakeGroupByIds(self, groupName, elementType, elemIDs):
1975         group = self.mesh.CreateGroup(elementType, groupName)
1976         if hasattr( elemIDs, "GetIDs" ):
1977             if hasattr( elemIDs, "SetMesh" ):
1978                 elemIDs.SetMesh( self.GetMesh() )
1979             group.AddFrom( elemIDs )
1980         else:
1981             group.Add(elemIDs)
1982         return group
1983
1984     ## Creates a mesh group by the given conditions
1985     #  @param groupName the name of the mesh group
1986     #  @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1987     #  @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
1988     #          Type SMESH.FunctorType._items in the Python Console to see all values.
1989     #          Note that the items starting from FT_LessThan are not suitable for CritType.
1990     #  @param Compare  belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
1991     #  @param Threshold the threshold value (range of ids as string, shape, numeric)
1992     #  @param UnaryOp  SMESH.FT_LogicalNOT or SMESH.FT_Undefined
1993     #  @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
1994     #         SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
1995     #  @return SMESH_GroupOnFilter
1996     #  @ingroup l2_grps_create
1997     def MakeGroup(self,
1998                   groupName,
1999                   elementType,
2000                   CritType=FT_Undefined,
2001                   Compare=FT_EqualTo,
2002                   Threshold="",
2003                   UnaryOp=FT_Undefined,
2004                   Tolerance=1e-07):
2005         aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2006         group = self.MakeGroupByCriterion(groupName, aCriterion)
2007         return group
2008
2009     ## Creates a mesh group by the given criterion
2010     #  @param groupName the name of the mesh group
2011     #  @param Criterion the instance of Criterion class
2012     #  @return SMESH_GroupOnFilter
2013     #  @ingroup l2_grps_create
2014     def MakeGroupByCriterion(self, groupName, Criterion):
2015         return self.MakeGroupByCriteria( groupName, [Criterion] )
2016
2017     ## Creates a mesh group by the given criteria (list of criteria)
2018     #  @param groupName the name of the mesh group
2019     #  @param theCriteria the list of criteria
2020     #  @param binOp binary operator used when binary operator of criteria is undefined
2021     #  @return SMESH_GroupOnFilter
2022     #  @ingroup l2_grps_create
2023     def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2024         aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2025         group = self.MakeGroupByFilter(groupName, aFilter)
2026         return group
2027
2028     ## Creates a mesh group by the given filter
2029     #  @param groupName the name of the mesh group
2030     #  @param theFilter the instance of Filter class
2031     #  @return SMESH_GroupOnFilter
2032     #  @ingroup l2_grps_create
2033     def MakeGroupByFilter(self, groupName, theFilter):
2034         #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2035         #theFilter.SetMesh( self.mesh )
2036         #group.AddFrom( theFilter )
2037         group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2038         return group
2039
2040     ## Removes a group
2041     #  @ingroup l2_grps_delete
2042     def RemoveGroup(self, group):
2043         self.mesh.RemoveGroup(group)
2044
2045     ## Removes a group with its contents
2046     #  @ingroup l2_grps_delete
2047     def RemoveGroupWithContents(self, group):
2048         self.mesh.RemoveGroupWithContents(group)
2049
2050     ## Gets the list of groups existing in the mesh in the order
2051     #  of creation (starting from the oldest one)
2052     #  @param elemType type of elements the groups contain; either of 
2053     #         (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2054     #         by default groups of elements of all types are returned
2055     #  @return a sequence of SMESH_GroupBase
2056     #  @ingroup l2_grps_create
2057     def GetGroups(self, elemType = SMESH.ALL):
2058         groups = self.mesh.GetGroups()
2059         if elemType == SMESH.ALL:
2060             return groups
2061         typedGroups = []
2062         for g in groups:
2063             if g.GetType() == elemType:
2064                 typedGroups.append( g )
2065                 pass
2066             pass
2067         return typedGroups
2068
2069     ## Gets the number of groups existing in the mesh
2070     #  @return the quantity of groups as an integer value
2071     #  @ingroup l2_grps_create
2072     def NbGroups(self):
2073         return self.mesh.NbGroups()
2074
2075     ## Gets the list of names of groups existing in the mesh
2076     #  @return list of strings
2077     #  @ingroup l2_grps_create
2078     def GetGroupNames(self):
2079         groups = self.GetGroups()
2080         names = []
2081         for group in groups:
2082             names.append(group.GetName())
2083         return names
2084
2085     ## Finds groups by name and type
2086     #  @param name name of the group of interest
2087     #  @param elemType type of elements the groups contain; either of 
2088     #         (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2089     #         by default one group of any type of elements is returned
2090     #         if elemType == SMESH.ALL then all groups of any type are returned
2091     #  @return a list of SMESH_GroupBase's
2092     #  @ingroup l2_grps_create
2093     def GetGroupByName(self, name, elemType = None):
2094         groups = []
2095         for group in self.GetGroups():
2096             if group.GetName() == name:
2097                 if elemType is None:
2098                     return [group]
2099                 if ( elemType == SMESH.ALL or 
2100                      group.GetType() == elemType ):
2101                     groups.append( group )
2102         return groups
2103
2104     ## Produces a union of two groups.
2105     #  A new group is created. All mesh elements that are
2106     #  present in the initial groups are added to the new one
2107     #  @return an instance of SMESH_Group
2108     #  @ingroup l2_grps_operon
2109     def UnionGroups(self, group1, group2, name):
2110         return self.mesh.UnionGroups(group1, group2, name)
2111
2112     ## Produces a union list of groups.
2113     #  New group is created. All mesh elements that are present in
2114     #  initial groups are added to the new one
2115     #  @return an instance of SMESH_Group
2116     #  @ingroup l2_grps_operon
2117     def UnionListOfGroups(self, groups, name):
2118       return self.mesh.UnionListOfGroups(groups, name)
2119
2120     ## Prodices an intersection of two groups.
2121     #  A new group is created. All mesh elements that are common
2122     #  for the two initial groups are added to the new one.
2123     #  @return an instance of SMESH_Group
2124     #  @ingroup l2_grps_operon
2125     def IntersectGroups(self, group1, group2, name):
2126         return self.mesh.IntersectGroups(group1, group2, name)
2127
2128     ## Produces an intersection of groups.
2129     #  New group is created. All mesh elements that are present in all
2130     #  initial groups simultaneously are added to the new one
2131     #  @return an instance of SMESH_Group
2132     #  @ingroup l2_grps_operon
2133     def IntersectListOfGroups(self, groups, name):
2134       return self.mesh.IntersectListOfGroups(groups, name)
2135
2136     ## Produces a cut of two groups.
2137     #  A new group is created. All mesh elements that are present in
2138     #  the main group but are not present in the tool group are added to the new one
2139     #  @return an instance of SMESH_Group
2140     #  @ingroup l2_grps_operon
2141     def CutGroups(self, main_group, tool_group, name):
2142         return self.mesh.CutGroups(main_group, tool_group, name)
2143
2144     ## Produces a cut of groups.
2145     #  A new group is created. All mesh elements that are present in main groups
2146     #  but do not present in tool groups are added to the new one
2147     #  @return an instance of SMESH_Group
2148     #  @ingroup l2_grps_operon
2149     def CutListOfGroups(self, main_groups, tool_groups, name):
2150         return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2151
2152     ##
2153     #  Create a standalone group of entities basing on nodes of other groups.
2154     #  \param groups - list of groups, sub-meshes or filters, of any type.
2155     #  \param elemType - a type of elements to include to the new group; either of 
2156     #         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2157     #  \param name - a name of the new group.
2158     #  \param nbCommonNodes - a criterion of inclusion of an element to the new group
2159     #         basing on number of element nodes common with reference \a groups.
2160     #         Meaning of possible values are:
2161     #         - SMESH.ALL_NODES - include if all nodes are common,
2162     #         - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2163     #         - SMESH.AT_LEAST_ONE - include if one or more node is common,
2164     #         - SMEHS.MAJORITY - include if half of nodes or more are common.
2165     #  \param underlyingOnly - if \c True (default), an element is included to the
2166     #         new group provided that it is based on nodes of one element of \a groups.
2167     #  @return an instance of SMESH_Group
2168     #  @ingroup l2_grps_operon
2169     def CreateDimGroup(self, groups, elemType, name,
2170                        nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2171         if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2172             groups = [groups]
2173         return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2174
2175
2176     ## Convert group on geom into standalone group
2177     #  @ingroup l2_grps_delete
2178     def ConvertToStandalone(self, group):
2179         return self.mesh.ConvertToStandalone(group)
2180
2181     # Get some info about mesh:
2182     # ------------------------
2183
2184     ## Returns the log of nodes and elements added or removed
2185     #  since the previous clear of the log.
2186     #  @param clearAfterGet log is emptied after Get (safe if concurrents access)
2187     #  @return list of log_block structures:
2188     #                                        commandType
2189     #                                        number
2190     #                                        coords
2191     #                                        indexes
2192     #  @ingroup l1_auxiliary
2193     def GetLog(self, clearAfterGet):
2194         return self.mesh.GetLog(clearAfterGet)
2195
2196     ## Clears the log of nodes and elements added or removed since the previous
2197     #  clear. Must be used immediately after GetLog if clearAfterGet is false.
2198     #  @ingroup l1_auxiliary
2199     def ClearLog(self):
2200         self.mesh.ClearLog()
2201
2202     ## Toggles auto color mode on the object.
2203     #  @param theAutoColor the flag which toggles auto color mode.
2204     #  @ingroup l1_auxiliary
2205     def SetAutoColor(self, theAutoColor):
2206         self.mesh.SetAutoColor(theAutoColor)
2207
2208     ## Gets flag of object auto color mode.
2209     #  @return True or False
2210     #  @ingroup l1_auxiliary
2211     def GetAutoColor(self):
2212         return self.mesh.GetAutoColor()
2213
2214     ## Gets the internal ID
2215     #  @return integer value, which is the internal Id of the mesh
2216     #  @ingroup l1_auxiliary
2217     def GetId(self):
2218         return self.mesh.GetId()
2219
2220     ## Get the study Id
2221     #  @return integer value, which is the study Id of the mesh
2222     #  @ingroup l1_auxiliary
2223     def GetStudyId(self):
2224         return self.mesh.GetStudyId()
2225
2226     ## Checks the group names for duplications.
2227     #  Consider the maximum group name length stored in MED file.
2228     #  @return True or False
2229     #  @ingroup l1_auxiliary
2230     def HasDuplicatedGroupNamesMED(self):
2231         return self.mesh.HasDuplicatedGroupNamesMED()
2232
2233     ## Obtains the mesh editor tool
2234     #  @return an instance of SMESH_MeshEditor
2235     #  @ingroup l1_modifying
2236     def GetMeshEditor(self):
2237         return self.editor
2238
2239     ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2240     #  can be passed as argument to a method accepting mesh, group or sub-mesh
2241     #  @param ids list of IDs
2242     #  @param elemType type of elements; this parameter is used to distinguish
2243     #         IDs of nodes from IDs of elements; by default ids are treated as
2244     #         IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2245     #  @return an instance of SMESH_IDSource
2246     #  @warning call UnRegister() for the returned object as soon as it is no more useful:
2247     #          idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2248     #          mesh.DoSomething( idSrc )
2249     #          idSrc.UnRegister()
2250     #  @ingroup l1_auxiliary
2251     def GetIDSource(self, ids, elemType = SMESH.ALL):
2252         return self.editor.MakeIDSource(ids, elemType)
2253
2254
2255     # Get informations about mesh contents:
2256     # ------------------------------------
2257
2258     ## Gets the mesh stattistic
2259     #  @return dictionary type element - count of elements
2260     #  @ingroup l1_meshinfo
2261     def GetMeshInfo(self, obj = None):
2262         if not obj: obj = self.mesh
2263         return self.smeshpyD.GetMeshInfo(obj)
2264
2265     ## Returns the number of nodes in the mesh
2266     #  @return an integer value
2267     #  @ingroup l1_meshinfo
2268     def NbNodes(self):
2269         return self.mesh.NbNodes()
2270
2271     ## Returns the number of elements in the mesh
2272     #  @return an integer value
2273     #  @ingroup l1_meshinfo
2274     def NbElements(self):
2275         return self.mesh.NbElements()
2276
2277     ## Returns the number of 0d elements in the mesh
2278     #  @return an integer value
2279     #  @ingroup l1_meshinfo
2280     def Nb0DElements(self):
2281         return self.mesh.Nb0DElements()
2282
2283     ## Returns the number of ball discrete elements in the mesh
2284     #  @return an integer value
2285     #  @ingroup l1_meshinfo
2286     def NbBalls(self):
2287         return self.mesh.NbBalls()
2288
2289     ## Returns the number of edges in the mesh
2290     #  @return an integer value
2291     #  @ingroup l1_meshinfo
2292     def NbEdges(self):
2293         return self.mesh.NbEdges()
2294
2295     ## Returns the number of edges with the given order in the mesh
2296     #  @param elementOrder the order of elements:
2297     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2298     #  @return an integer value
2299     #  @ingroup l1_meshinfo
2300     def NbEdgesOfOrder(self, elementOrder):
2301         return self.mesh.NbEdgesOfOrder(elementOrder)
2302
2303     ## Returns the number of faces in the mesh
2304     #  @return an integer value
2305     #  @ingroup l1_meshinfo
2306     def NbFaces(self):
2307         return self.mesh.NbFaces()
2308
2309     ## Returns the number of faces with the given order in the mesh
2310     #  @param elementOrder the order of elements:
2311     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2312     #  @return an integer value
2313     #  @ingroup l1_meshinfo
2314     def NbFacesOfOrder(self, elementOrder):
2315         return self.mesh.NbFacesOfOrder(elementOrder)
2316
2317     ## Returns the number of triangles in the mesh
2318     #  @return an integer value
2319     #  @ingroup l1_meshinfo
2320     def NbTriangles(self):
2321         return self.mesh.NbTriangles()
2322
2323     ## Returns the number of triangles with the given order in the mesh
2324     #  @param elementOrder is the order of elements:
2325     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2326     #  @return an integer value
2327     #  @ingroup l1_meshinfo
2328     def NbTrianglesOfOrder(self, elementOrder):
2329         return self.mesh.NbTrianglesOfOrder(elementOrder)
2330
2331     ## Returns the number of biquadratic triangles in the mesh
2332     #  @return an integer value
2333     #  @ingroup l1_meshinfo
2334     def NbBiQuadTriangles(self):
2335         return self.mesh.NbBiQuadTriangles()
2336
2337     ## Returns the number of quadrangles in the mesh
2338     #  @return an integer value
2339     #  @ingroup l1_meshinfo
2340     def NbQuadrangles(self):
2341         return self.mesh.NbQuadrangles()
2342
2343     ## Returns the number of quadrangles with the given order in the mesh
2344     #  @param elementOrder the order of elements:
2345     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2346     #  @return an integer value
2347     #  @ingroup l1_meshinfo
2348     def NbQuadranglesOfOrder(self, elementOrder):
2349         return self.mesh.NbQuadranglesOfOrder(elementOrder)
2350
2351     ## Returns the number of biquadratic quadrangles in the mesh
2352     #  @return an integer value
2353     #  @ingroup l1_meshinfo
2354     def NbBiQuadQuadrangles(self):
2355         return self.mesh.NbBiQuadQuadrangles()
2356
2357     ## Returns the number of polygons of given order in the mesh
2358     #  @param elementOrder the order of elements:
2359     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2360     #  @return an integer value
2361     #  @ingroup l1_meshinfo
2362     def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2363         return self.mesh.NbPolygonsOfOrder(elementOrder)
2364
2365     ## Returns the number of volumes in the mesh
2366     #  @return an integer value
2367     #  @ingroup l1_meshinfo
2368     def NbVolumes(self):
2369         return self.mesh.NbVolumes()
2370
2371     ## Returns the number of volumes with the given order in the mesh
2372     #  @param elementOrder  the order of elements:
2373     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2374     #  @return an integer value
2375     #  @ingroup l1_meshinfo
2376     def NbVolumesOfOrder(self, elementOrder):
2377         return self.mesh.NbVolumesOfOrder(elementOrder)
2378
2379     ## Returns the number of tetrahedrons in the mesh
2380     #  @return an integer value
2381     #  @ingroup l1_meshinfo
2382     def NbTetras(self):
2383         return self.mesh.NbTetras()
2384
2385     ## Returns the number of tetrahedrons with the given order in the mesh
2386     #  @param elementOrder  the order of elements:
2387     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2388     #  @return an integer value
2389     #  @ingroup l1_meshinfo
2390     def NbTetrasOfOrder(self, elementOrder):
2391         return self.mesh.NbTetrasOfOrder(elementOrder)
2392
2393     ## Returns the number of hexahedrons in the mesh
2394     #  @return an integer value
2395     #  @ingroup l1_meshinfo
2396     def NbHexas(self):
2397         return self.mesh.NbHexas()
2398
2399     ## Returns the number of hexahedrons with the given order in the mesh
2400     #  @param elementOrder  the order of elements:
2401     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2402     #  @return an integer value
2403     #  @ingroup l1_meshinfo
2404     def NbHexasOfOrder(self, elementOrder):
2405         return self.mesh.NbHexasOfOrder(elementOrder)
2406
2407     ## Returns the number of triquadratic hexahedrons in the mesh
2408     #  @return an integer value
2409     #  @ingroup l1_meshinfo
2410     def NbTriQuadraticHexas(self):
2411         return self.mesh.NbTriQuadraticHexas()
2412
2413     ## Returns the number of pyramids in the mesh
2414     #  @return an integer value
2415     #  @ingroup l1_meshinfo
2416     def NbPyramids(self):
2417         return self.mesh.NbPyramids()
2418
2419     ## Returns the number of pyramids with the given order in the mesh
2420     #  @param elementOrder  the order of elements:
2421     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2422     #  @return an integer value
2423     #  @ingroup l1_meshinfo
2424     def NbPyramidsOfOrder(self, elementOrder):
2425         return self.mesh.NbPyramidsOfOrder(elementOrder)
2426
2427     ## Returns the number of prisms in the mesh
2428     #  @return an integer value
2429     #  @ingroup l1_meshinfo
2430     def NbPrisms(self):
2431         return self.mesh.NbPrisms()
2432
2433     ## Returns the number of prisms with the given order in the mesh
2434     #  @param elementOrder  the order of elements:
2435     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2436     #  @return an integer value
2437     #  @ingroup l1_meshinfo
2438     def NbPrismsOfOrder(self, elementOrder):
2439         return self.mesh.NbPrismsOfOrder(elementOrder)
2440
2441     ## Returns the number of hexagonal prisms in the mesh
2442     #  @return an integer value
2443     #  @ingroup l1_meshinfo
2444     def NbHexagonalPrisms(self):
2445         return self.mesh.NbHexagonalPrisms()
2446
2447     ## Returns the number of polyhedrons in the mesh
2448     #  @return an integer value
2449     #  @ingroup l1_meshinfo
2450     def NbPolyhedrons(self):
2451         return self.mesh.NbPolyhedrons()
2452
2453     ## Returns the number of submeshes in the mesh
2454     #  @return an integer value
2455     #  @ingroup l1_meshinfo
2456     def NbSubMesh(self):
2457         return self.mesh.NbSubMesh()
2458
2459     ## Returns the list of mesh elements IDs
2460     #  @return the list of integer values
2461     #  @ingroup l1_meshinfo
2462     def GetElementsId(self):
2463         return self.mesh.GetElementsId()
2464
2465     ## Returns the list of IDs of mesh elements with the given type
2466     #  @param elementType  the required type of elements, either of
2467     #         (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2468     #  @return list of integer values
2469     #  @ingroup l1_meshinfo
2470     def GetElementsByType(self, elementType):
2471         return self.mesh.GetElementsByType(elementType)
2472
2473     ## Returns the list of mesh nodes IDs
2474     #  @return the list of integer values
2475     #  @ingroup l1_meshinfo
2476     def GetNodesId(self):
2477         return self.mesh.GetNodesId()
2478
2479     # Get the information about mesh elements:
2480     # ------------------------------------
2481
2482     ## Returns the type of mesh element
2483     #  @return the value from SMESH::ElementType enumeration
2484     #          Type SMESH.ElementType._items in the Python Console to see all possible values.
2485     #  @ingroup l1_meshinfo
2486     def GetElementType(self, id, iselem=True):
2487         return self.mesh.GetElementType(id, iselem)
2488
2489     ## Returns the geometric type of mesh element
2490     #  @return the value from SMESH::EntityType enumeration
2491     #          Type SMESH.EntityType._items in the Python Console to see all possible values.
2492     #  @ingroup l1_meshinfo
2493     def GetElementGeomType(self, id):
2494         return self.mesh.GetElementGeomType(id)
2495
2496     ## Returns the shape type of mesh element
2497     #  @return the value from SMESH::GeometryType enumeration.
2498     #          Type SMESH.GeometryType._items in the Python Console to see all possible values.
2499     #  @ingroup l1_meshinfo
2500     def GetElementShape(self, id):
2501         return self.mesh.GetElementShape(id)
2502
2503     ## Returns the list of submesh elements IDs
2504     #  @param Shape a geom object(sub-shape) IOR
2505     #         Shape must be the sub-shape of a ShapeToMesh()
2506     #  @return the list of integer values
2507     #  @ingroup l1_meshinfo
2508     def GetSubMeshElementsId(self, Shape):
2509         if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2510             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2511         else:
2512             ShapeID = Shape
2513         return self.mesh.GetSubMeshElementsId(ShapeID)
2514
2515     ## Returns the list of submesh nodes IDs
2516     #  @param Shape a geom object(sub-shape) IOR
2517     #         Shape must be the sub-shape of a ShapeToMesh()
2518     #  @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2519     #  @return the list of integer values
2520     #  @ingroup l1_meshinfo
2521     def GetSubMeshNodesId(self, Shape, all):
2522         if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2523             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2524         else:
2525             ShapeID = Shape
2526         return self.mesh.GetSubMeshNodesId(ShapeID, all)
2527
2528     ## Returns type of elements on given shape
2529     #  @param Shape a geom object(sub-shape) IOR
2530     #         Shape must be a sub-shape of a ShapeToMesh()
2531     #  @return element type
2532     #  @ingroup l1_meshinfo
2533     def GetSubMeshElementType(self, Shape):
2534         if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2535             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2536         else:
2537             ShapeID = Shape
2538         return self.mesh.GetSubMeshElementType(ShapeID)
2539
2540     ## Gets the mesh description
2541     #  @return string value
2542     #  @ingroup l1_meshinfo
2543     def Dump(self):
2544         return self.mesh.Dump()
2545
2546
2547     # Get the information about nodes and elements of a mesh by its IDs:
2548     # -----------------------------------------------------------
2549
2550     ## Gets XYZ coordinates of a node
2551     #  \n If there is no nodes for the given ID - returns an empty list
2552     #  @return a list of double precision values
2553     #  @ingroup l1_meshinfo
2554     def GetNodeXYZ(self, id):
2555         return self.mesh.GetNodeXYZ(id)
2556
2557     ## Returns list of IDs of inverse elements for the given node
2558     #  \n If there is no node for the given ID - returns an empty list
2559     #  @return a list of integer values
2560     #  @ingroup l1_meshinfo
2561     def GetNodeInverseElements(self, id):
2562         return self.mesh.GetNodeInverseElements(id)
2563
2564     ## @brief Returns the position of a node on the shape
2565     #  @return SMESH::NodePosition
2566     #  @ingroup l1_meshinfo
2567     def GetNodePosition(self,NodeID):
2568         return self.mesh.GetNodePosition(NodeID)
2569
2570     ## @brief Returns the position of an element on the shape
2571     #  @return SMESH::ElementPosition
2572     #  @ingroup l1_meshinfo
2573     def GetElementPosition(self,ElemID):
2574         return self.mesh.GetElementPosition(ElemID)
2575
2576     ## Returns the ID of the shape, on which the given node was generated.
2577     #  @return an integer value > 0 or -1 if there is no node for the given
2578     #          ID or the node is not assigned to any geometry
2579     #  @ingroup l1_meshinfo
2580     def GetShapeID(self, id):
2581         return self.mesh.GetShapeID(id)
2582
2583     ## Returns the ID of the shape, on which the given element was generated.
2584     #  @return an integer value > 0 or -1 if there is no element for the given
2585     #          ID or the element is not assigned to any geometry
2586     #  @ingroup l1_meshinfo
2587     def GetShapeIDForElem(self,id):
2588         return self.mesh.GetShapeIDForElem(id)
2589
2590     ## Returns the number of nodes of the given element
2591     #  @return an integer value > 0 or -1 if there is no element for the given ID
2592     #  @ingroup l1_meshinfo
2593     def GetElemNbNodes(self, id):
2594         return self.mesh.GetElemNbNodes(id)
2595
2596     ## Returns the node ID the given (zero based) index for the given element
2597     #  \n If there is no element for the given ID - returns -1
2598     #  \n If there is no node for the given index - returns -2
2599     #  @return an integer value
2600     #  @ingroup l1_meshinfo
2601     def GetElemNode(self, id, index):
2602         return self.mesh.GetElemNode(id, index)
2603
2604     ## Returns the IDs of nodes of the given element
2605     #  @return a list of integer values
2606     #  @ingroup l1_meshinfo
2607     def GetElemNodes(self, id):
2608         return self.mesh.GetElemNodes(id)
2609
2610     ## Returns true if the given node is the medium node in the given quadratic element
2611     #  @ingroup l1_meshinfo
2612     def IsMediumNode(self, elementID, nodeID):
2613         return self.mesh.IsMediumNode(elementID, nodeID)
2614
2615     ## Returns true if the given node is the medium node in one of quadratic elements
2616     #  @param nodeID ID of the node
2617     #  @param elementType  the type of elements to check a state of the node, either of
2618     #         (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2619     #  @ingroup l1_meshinfo
2620     def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2621         return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2622
2623     ## Returns the number of edges for the given element
2624     #  @ingroup l1_meshinfo
2625     def ElemNbEdges(self, id):
2626         return self.mesh.ElemNbEdges(id)
2627
2628     ## Returns the number of faces for the given element
2629     #  @ingroup l1_meshinfo
2630     def ElemNbFaces(self, id):
2631         return self.mesh.ElemNbFaces(id)
2632
2633     ## Returns nodes of given face (counted from zero) for given volumic element.
2634     #  @ingroup l1_meshinfo
2635     def GetElemFaceNodes(self,elemId, faceIndex):
2636         return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2637
2638     ## Returns three components of normal of given mesh face
2639     #  (or an empty array in KO case)
2640     #  @ingroup l1_meshinfo
2641     def GetFaceNormal(self, faceId, normalized=False):
2642         return self.mesh.GetFaceNormal(faceId,normalized)
2643
2644     ## Returns an element based on all given nodes.
2645     #  @ingroup l1_meshinfo
2646     def FindElementByNodes(self,nodes):
2647         return self.mesh.FindElementByNodes(nodes)
2648
2649     ## Returns true if the given element is a polygon
2650     #  @ingroup l1_meshinfo
2651     def IsPoly(self, id):
2652         return self.mesh.IsPoly(id)
2653
2654     ## Returns true if the given element is quadratic
2655     #  @ingroup l1_meshinfo
2656     def IsQuadratic(self, id):
2657         return self.mesh.IsQuadratic(id)
2658
2659     ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2660     #  @ingroup l1_meshinfo
2661     def GetBallDiameter(self, id):
2662         return self.mesh.GetBallDiameter(id)
2663
2664     ## Returns XYZ coordinates of the barycenter of the given element
2665     #  \n If there is no element for the given ID - returns an empty list
2666     #  @return a list of three double values
2667     #  @ingroup l1_meshinfo
2668     def BaryCenter(self, id):
2669         return self.mesh.BaryCenter(id)
2670
2671     ## Passes mesh elements through the given filter and return IDs of fitting elements
2672     #  @param theFilter SMESH_Filter
2673     #  @return a list of ids
2674     #  @ingroup l1_controls
2675     def GetIdsFromFilter(self, theFilter):
2676         theFilter.SetMesh( self.mesh )
2677         return theFilter.GetIDs()
2678
2679     ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2680     #  Returns a list of special structures (borders).
2681     #  @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2682     #  @ingroup l1_controls
2683     def GetFreeBorders(self):
2684         aFilterMgr = self.smeshpyD.CreateFilterManager()
2685         aPredicate = aFilterMgr.CreateFreeEdges()
2686         aPredicate.SetMesh(self.mesh)
2687         aBorders = aPredicate.GetBorders()
2688         aFilterMgr.UnRegister()
2689         return aBorders
2690
2691
2692     # Get mesh measurements information:
2693     # ------------------------------------
2694
2695     ## Get minimum distance between two nodes, elements or distance to the origin
2696     #  @param id1 first node/element id
2697     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2698     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2699     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2700     #  @return minimum distance value
2701     #  @sa GetMinDistance()
2702     def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2703         aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2704         return aMeasure.value
2705
2706     ## Get measure structure specifying minimum distance data between two objects
2707     #  @param id1 first node/element id
2708     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2709     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2710     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2711     #  @return Measure structure
2712     #  @sa MinDistance()
2713     def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2714         if isElem1:
2715             id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2716         else:
2717             id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2718         if id2 != 0:
2719             if isElem2:
2720                 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2721             else:
2722                 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2723             pass
2724         else:
2725             id2 = None
2726
2727         aMeasurements = self.smeshpyD.CreateMeasurements()
2728         aMeasure = aMeasurements.MinDistance(id1, id2)
2729         genObjUnRegister([aMeasurements,id1, id2])
2730         return aMeasure
2731
2732     ## Get bounding box of the specified object(s)
2733     #  @param objects single source object or list of source objects or list of nodes/elements IDs
2734     #  @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2735     #  @c False specifies that @a objects are nodes
2736     #  @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2737     #  @sa GetBoundingBox()
2738     def BoundingBox(self, objects=None, isElem=False):
2739         result = self.GetBoundingBox(objects, isElem)
2740         if result is None:
2741             result = (0.0,)*6
2742         else:
2743             result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2744         return result
2745
2746     ## Get measure structure specifying bounding box data of the specified object(s)
2747     #  @param IDs single source object or list of source objects or list of nodes/elements IDs
2748     #  @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2749     #  @c False specifies that @a objects are nodes
2750     #  @return Measure structure
2751     #  @sa BoundingBox()
2752     def GetBoundingBox(self, IDs=None, isElem=False):
2753         if IDs is None:
2754             IDs = [self.mesh]
2755         elif isinstance(IDs, tuple):
2756             IDs = list(IDs)
2757         if not isinstance(IDs, list):
2758             IDs = [IDs]
2759         if len(IDs) > 0 and isinstance(IDs[0], int):
2760             IDs = [IDs]
2761         srclist = []
2762         unRegister = genObjUnRegister()
2763         for o in IDs:
2764             if isinstance(o, Mesh):
2765                 srclist.append(o.mesh)
2766             elif hasattr(o, "_narrow"):
2767                 src = o._narrow(SMESH.SMESH_IDSource)
2768                 if src: srclist.append(src)
2769                 pass
2770             elif isinstance(o, list):
2771                 if isElem:
2772                     srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2773                 else:
2774                     srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2775                 unRegister.set( srclist[-1] )
2776                 pass
2777             pass
2778         aMeasurements = self.smeshpyD.CreateMeasurements()
2779         unRegister.set( aMeasurements )
2780         aMeasure = aMeasurements.BoundingBox(srclist)
2781         return aMeasure
2782
2783     # Mesh edition (SMESH_MeshEditor functionality):
2784     # ---------------------------------------------
2785
2786     ## Removes the elements from the mesh by ids
2787     #  @param IDsOfElements is a list of ids of elements to remove
2788     #  @return True or False
2789     #  @ingroup l2_modif_del
2790     def RemoveElements(self, IDsOfElements):
2791         return self.editor.RemoveElements(IDsOfElements)
2792
2793     ## Removes nodes from mesh by ids
2794     #  @param IDsOfNodes is a list of ids of nodes to remove
2795     #  @return True or False
2796     #  @ingroup l2_modif_del
2797     def RemoveNodes(self, IDsOfNodes):
2798         return self.editor.RemoveNodes(IDsOfNodes)
2799
2800     ## Removes all orphan (free) nodes from mesh
2801     #  @return number of the removed nodes
2802     #  @ingroup l2_modif_del
2803     def RemoveOrphanNodes(self):
2804         return self.editor.RemoveOrphanNodes()
2805
2806     ## Add a node to the mesh by coordinates
2807     #  @return Id of the new node
2808     #  @ingroup l2_modif_add
2809     def AddNode(self, x, y, z):
2810         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2811         if hasVars: self.mesh.SetParameters(Parameters)
2812         return self.editor.AddNode( x, y, z)
2813
2814     ## Creates a 0D element on a node with given number.
2815     #  @param IDOfNode the ID of node for creation of the element.
2816     #  @return the Id of the new 0D element
2817     #  @ingroup l2_modif_add
2818     def Add0DElement(self, IDOfNode):
2819         return self.editor.Add0DElement(IDOfNode)
2820
2821     ## Create 0D elements on all nodes of the given elements except those 
2822     #  nodes on which a 0D element already exists.
2823     #  @param theObject an object on whose nodes 0D elements will be created.
2824     #         It can be mesh, sub-mesh, group, list of element IDs or a holder
2825     #         of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2826     #  @param theGroupName optional name of a group to add 0D elements created
2827     #         and/or found on nodes of \a theObject.
2828     #  @return an object (a new group or a temporary SMESH_IDSource) holding
2829     #          IDs of new and/or found 0D elements. IDs of 0D elements 
2830     #          can be retrieved from the returned object by calling GetIDs()
2831     #  @ingroup l2_modif_add
2832     def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2833         unRegister = genObjUnRegister()
2834         if isinstance( theObject, Mesh ):
2835             theObject = theObject.GetMesh()
2836         if isinstance( theObject, list ):
2837             theObject = self.GetIDSource( theObject, SMESH.ALL )
2838             unRegister.set( theObject )
2839         return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2840
2841     ## Creates a ball element on a node with given ID.
2842     #  @param IDOfNode the ID of node for creation of the element.
2843     #  @param diameter the bal diameter.
2844     #  @return the Id of the new ball element
2845     #  @ingroup l2_modif_add
2846     def AddBall(self, IDOfNode, diameter):
2847         return self.editor.AddBall( IDOfNode, diameter )
2848
2849     ## Creates a linear or quadratic edge (this is determined
2850     #  by the number of given nodes).
2851     #  @param IDsOfNodes the list of node IDs for creation of the element.
2852     #  The order of nodes in this list should correspond to the description
2853     #  of MED. \n This description is located by the following link:
2854     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2855     #  @return the Id of the new edge
2856     #  @ingroup l2_modif_add
2857     def AddEdge(self, IDsOfNodes):
2858         return self.editor.AddEdge(IDsOfNodes)
2859
2860     ## Creates a linear or quadratic face (this is determined
2861     #  by the number of given nodes).
2862     #  @param IDsOfNodes the list of node IDs for creation of the element.
2863     #  The order of nodes in this list should correspond to the description
2864     #  of MED. \n This description is located by the following link:
2865     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2866     #  @return the Id of the new face
2867     #  @ingroup l2_modif_add
2868     def AddFace(self, IDsOfNodes):
2869         return self.editor.AddFace(IDsOfNodes)
2870
2871     ## Adds a polygonal face to the mesh by the list of node IDs
2872     #  @param IdsOfNodes the list of node IDs for creation of the element.
2873     #  @return the Id of the new face
2874     #  @ingroup l2_modif_add
2875     def AddPolygonalFace(self, IdsOfNodes):
2876         return self.editor.AddPolygonalFace(IdsOfNodes)
2877
2878     ## Adds a quadratic polygonal face to the mesh by the list of node IDs
2879     #  @param IdsOfNodes the list of node IDs for creation of the element;
2880     #         corner nodes follow first.
2881     #  @return the Id of the new face
2882     #  @ingroup l2_modif_add
2883     def AddQuadPolygonalFace(self, IdsOfNodes):
2884         return self.editor.AddQuadPolygonalFace(IdsOfNodes)
2885
2886     ## Creates both simple and quadratic volume (this is determined
2887     #  by the number of given nodes).
2888     #  @param IDsOfNodes the list of node IDs for creation of the element.
2889     #  The order of nodes in this list should correspond to the description
2890     #  of MED. \n This description is located by the following link:
2891     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2892     #  @return the Id of the new volumic element
2893     #  @ingroup l2_modif_add
2894     def AddVolume(self, IDsOfNodes):
2895         return self.editor.AddVolume(IDsOfNodes)
2896
2897     ## Creates a volume of many faces, giving nodes for each face.
2898     #  @param IdsOfNodes the list of node IDs for volume creation face by face.
2899     #  @param Quantities the list of integer values, Quantities[i]
2900     #         gives the quantity of nodes in face number i.
2901     #  @return the Id of the new volumic element
2902     #  @ingroup l2_modif_add
2903     def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2904         return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2905
2906     ## Creates a volume of many faces, giving the IDs of the existing faces.
2907     #  @param IdsOfFaces the list of face IDs for volume creation.
2908     #
2909     #  Note:  The created volume will refer only to the nodes
2910     #         of the given faces, not to the faces themselves.
2911     #  @return the Id of the new volumic element
2912     #  @ingroup l2_modif_add
2913     def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2914         return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2915
2916
2917     ## @brief Binds a node to a vertex
2918     #  @param NodeID a node ID
2919     #  @param Vertex a vertex or vertex ID
2920     #  @return True if succeed else raises an exception
2921     #  @ingroup l2_modif_add
2922     def SetNodeOnVertex(self, NodeID, Vertex):
2923         if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2924             VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
2925         else:
2926             VertexID = Vertex
2927         try:
2928             self.editor.SetNodeOnVertex(NodeID, VertexID)
2929         except SALOME.SALOME_Exception, inst:
2930             raise ValueError, inst.details.text
2931         return True
2932
2933
2934     ## @brief Stores the node position on an edge
2935     #  @param NodeID a node ID
2936     #  @param Edge an edge or edge ID
2937     #  @param paramOnEdge a parameter on the edge where the node is located
2938     #  @return True if succeed else raises an exception
2939     #  @ingroup l2_modif_add
2940     def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2941         if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2942             EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
2943         else:
2944             EdgeID = Edge
2945         try:
2946             self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2947         except SALOME.SALOME_Exception, inst:
2948             raise ValueError, inst.details.text
2949         return True
2950
2951     ## @brief Stores node position on a face
2952     #  @param NodeID a node ID
2953     #  @param Face a face or face ID
2954     #  @param u U parameter on the face where the node is located
2955     #  @param v V parameter on the face where the node is located
2956     #  @return True if succeed else raises an exception
2957     #  @ingroup l2_modif_add
2958     def SetNodeOnFace(self, NodeID, Face, u, v):
2959         if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2960             FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
2961         else:
2962             FaceID = Face
2963         try:
2964             self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2965         except SALOME.SALOME_Exception, inst:
2966             raise ValueError, inst.details.text
2967         return True
2968
2969     ## @brief Binds a node to a solid
2970     #  @param NodeID a node ID
2971     #  @param Solid  a solid or solid ID
2972     #  @return True if succeed else raises an exception
2973     #  @ingroup l2_modif_add
2974     def SetNodeInVolume(self, NodeID, Solid):
2975         if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2976             SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
2977         else:
2978             SolidID = Solid
2979         try:
2980             self.editor.SetNodeInVolume(NodeID, SolidID)
2981         except SALOME.SALOME_Exception, inst:
2982             raise ValueError, inst.details.text
2983         return True
2984
2985     ## @brief Bind an element to a shape
2986     #  @param ElementID an element ID
2987     #  @param Shape a shape or shape ID
2988     #  @return True if succeed else raises an exception
2989     #  @ingroup l2_modif_add
2990     def SetMeshElementOnShape(self, ElementID, Shape):
2991         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2992             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2993         else:
2994             ShapeID = Shape
2995         try:
2996             self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2997         except SALOME.SALOME_Exception, inst:
2998             raise ValueError, inst.details.text
2999         return True
3000
3001
3002     ## Moves the node with the given id
3003     #  @param NodeID the id of the node
3004     #  @param x  a new X coordinate
3005     #  @param y  a new Y coordinate
3006     #  @param z  a new Z coordinate
3007     #  @return True if succeed else False
3008     #  @ingroup l2_modif_movenode
3009     def MoveNode(self, NodeID, x, y, z):
3010         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3011         if hasVars: self.mesh.SetParameters(Parameters)
3012         return self.editor.MoveNode(NodeID, x, y, z)
3013
3014     ## Finds the node closest to a point and moves it to a point location
3015     #  @param x  the X coordinate of a point
3016     #  @param y  the Y coordinate of a point
3017     #  @param z  the Z coordinate of a point
3018     #  @param NodeID if specified (>0), the node with this ID is moved,
3019     #  otherwise, the node closest to point (@a x,@a y,@a z) is moved
3020     #  @return the ID of a node
3021     #  @ingroup l2_modif_throughp
3022     def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3023         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3024         if hasVars: self.mesh.SetParameters(Parameters)
3025         return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3026
3027     ## Finds the node closest to a point
3028     #  @param x  the X coordinate of a point
3029     #  @param y  the Y coordinate of a point
3030     #  @param z  the Z coordinate of a point
3031     #  @return the ID of a node
3032     #  @ingroup l2_modif_throughp
3033     def FindNodeClosestTo(self, x, y, z):
3034         #preview = self.mesh.GetMeshEditPreviewer()
3035         #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3036         return self.editor.FindNodeClosestTo(x, y, z)
3037
3038     ## Finds the elements where a point lays IN or ON
3039     #  @param x  the X coordinate of a point
3040     #  @param y  the Y coordinate of a point
3041     #  @param z  the Z coordinate of a point
3042     #  @param elementType type of elements to find; either of 
3043     #         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3044     #         means elements of any type excluding nodes, discrete and 0D elements.
3045     #  @param meshPart a part of mesh (group, sub-mesh) to search within
3046     #  @return list of IDs of found elements
3047     #  @ingroup l2_modif_throughp
3048     def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3049         if meshPart:
3050             return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
3051         else:
3052             return self.editor.FindElementsByPoint(x, y, z, elementType)
3053
3054     ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
3055     #  0-IN, 1-OUT, 2-ON, 3-UNKNOWN
3056     #  UNKNOWN state means that either mesh is wrong or the analysis fails.
3057     def GetPointState(self, x, y, z):
3058         return self.editor.GetPointState(x, y, z)
3059
3060     ## Finds the node closest to a point and moves it to a point location
3061     #  @param x  the X coordinate of a point
3062     #  @param y  the Y coordinate of a point
3063     #  @param z  the Z coordinate of a point
3064     #  @return the ID of a moved node
3065     #  @ingroup l2_modif_throughp
3066     def MeshToPassThroughAPoint(self, x, y, z):
3067         return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3068
3069     ## Replaces two neighbour triangles sharing Node1-Node2 link
3070     #  with the triangles built on the same 4 nodes but having other common link.
3071     #  @param NodeID1  the ID of the first node
3072     #  @param NodeID2  the ID of the second node
3073     #  @return false if proper faces were not found
3074     #  @ingroup l2_modif_invdiag
3075     def InverseDiag(self, NodeID1, NodeID2):
3076         return self.editor.InverseDiag(NodeID1, NodeID2)
3077
3078     ## Replaces two neighbour triangles sharing Node1-Node2 link
3079     #  with a quadrangle built on the same 4 nodes.
3080     #  @param NodeID1  the ID of the first node
3081     #  @param NodeID2  the ID of the second node
3082     #  @return false if proper faces were not found
3083     #  @ingroup l2_modif_unitetri
3084     def DeleteDiag(self, NodeID1, NodeID2):
3085         return self.editor.DeleteDiag(NodeID1, NodeID2)
3086
3087     ## Reorients elements by ids
3088     #  @param IDsOfElements if undefined reorients all mesh elements
3089     #  @return True if succeed else False
3090     #  @ingroup l2_modif_changori
3091     def Reorient(self, IDsOfElements=None):
3092         if IDsOfElements == None:
3093             IDsOfElements = self.GetElementsId()
3094         return self.editor.Reorient(IDsOfElements)
3095
3096     ## Reorients all elements of the object
3097     #  @param theObject mesh, submesh or group
3098     #  @return True if succeed else False
3099     #  @ingroup l2_modif_changori
3100     def ReorientObject(self, theObject):
3101         if ( isinstance( theObject, Mesh )):
3102             theObject = theObject.GetMesh()
3103         return self.editor.ReorientObject(theObject)
3104
3105     ## Reorient faces contained in \a the2DObject.
3106     #  @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3107     #  @param theDirection is a desired direction of normal of \a theFace.
3108     #         It can be either a GEOM vector or a list of coordinates [x,y,z].
3109     #  @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3110     #         compared with theDirection. It can be either ID of face or a point
3111     #         by which the face will be found. The point can be given as either
3112     #         a GEOM vertex or a list of point coordinates.
3113     #  @return number of reoriented faces
3114     #  @ingroup l2_modif_changori
3115     def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3116         unRegister = genObjUnRegister()
3117         # check the2DObject
3118         if isinstance( the2DObject, Mesh ):
3119             the2DObject = the2DObject.GetMesh()
3120         if isinstance( the2DObject, list ):
3121             the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3122             unRegister.set( the2DObject )
3123         # check theDirection
3124         if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3125             theDirection = self.smeshpyD.GetDirStruct( theDirection )
3126         if isinstance( theDirection, list ):
3127             theDirection = self.smeshpyD.MakeDirStruct( *theDirection  )
3128         # prepare theFace and thePoint
3129         theFace = theFaceOrPoint
3130         thePoint = PointStruct(0,0,0)
3131         if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3132             thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3133             theFace = -1
3134         if isinstance( theFaceOrPoint, list ):
3135             thePoint = PointStruct( *theFaceOrPoint )
3136             theFace = -1
3137         if isinstance( theFaceOrPoint, PointStruct ):
3138             thePoint = theFaceOrPoint
3139             theFace = -1
3140         return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3141
3142     ## Reorient faces according to adjacent volumes.
3143     #  @param the2DObject is a mesh, sub-mesh, group or list of
3144     #         either IDs of faces or face groups.
3145     #  @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3146     #  @param theOutsideNormal to orient faces to have their normals
3147     #         pointing either \a outside or \a inside the adjacent volumes.
3148     #  @return number of reoriented faces.
3149     #  @ingroup l2_modif_changori
3150     def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3151         unRegister = genObjUnRegister()
3152         # check the2DObject
3153         if not isinstance( the2DObject, list ):
3154             the2DObject = [ the2DObject ]
3155         elif the2DObject and isinstance( the2DObject[0], int ):
3156             the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3157             unRegister.set( the2DObject )
3158             the2DObject = [ the2DObject ]
3159         for i,obj2D in enumerate( the2DObject ):
3160             if isinstance( obj2D, Mesh ):
3161                 the2DObject[i] = obj2D.GetMesh()
3162             if isinstance( obj2D, list ):
3163                 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3164                 unRegister.set( the2DObject[i] )
3165         # check the3DObject
3166         if isinstance( the3DObject, Mesh ):
3167             the3DObject = the3DObject.GetMesh()
3168         if isinstance( the3DObject, list ):
3169             the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3170             unRegister.set( the3DObject )
3171         return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3172
3173     ## Fuses the neighbouring triangles into quadrangles.
3174     #  @param IDsOfElements The triangles to be fused.
3175     #  @param theCriterion  a numerical functor, in terms of enum SMESH.FunctorType, used to
3176     #          applied to possible quadrangles to choose a neighbour to fuse with.
3177     #          Type SMESH.FunctorType._items in the Python Console to see all items.
3178     #          Note that not all items correspond to numerical functors.
3179     #  @param MaxAngle      is the maximum angle between element normals at which the fusion
3180     #          is still performed; theMaxAngle is mesured in radians.
3181     #          Also it could be a name of variable which defines angle in degrees.
3182     #  @return TRUE in case of success, FALSE otherwise.
3183     #  @ingroup l2_modif_unitetri
3184     def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3185         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3186         self.mesh.SetParameters(Parameters)
3187         if not IDsOfElements:
3188             IDsOfElements = self.GetElementsId()
3189         Functor = self.smeshpyD.GetFunctor(theCriterion)
3190         return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3191
3192     ## Fuses the neighbouring triangles of the object into quadrangles
3193     #  @param theObject is mesh, submesh or group
3194     #  @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType,
3195     #          applied to possible quadrangles to choose a neighbour to fuse with.
3196     #          Type SMESH.FunctorType._items in the Python Console to see all items.
3197     #          Note that not all items correspond to numerical functors.
3198     #  @param MaxAngle   a max angle between element normals at which the fusion
3199     #          is still performed; theMaxAngle is mesured in radians.
3200     #  @return TRUE in case of success, FALSE otherwise.
3201     #  @ingroup l2_modif_unitetri
3202     def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3203         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3204         self.mesh.SetParameters(Parameters)
3205         if isinstance( theObject, Mesh ):
3206             theObject = theObject.GetMesh()
3207         Functor = self.smeshpyD.GetFunctor(theCriterion)
3208         return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3209
3210     ## Splits quadrangles into triangles.
3211     #  @param IDsOfElements the faces to be splitted.
3212     #  @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3213     #         choose a diagonal for splitting. If @a theCriterion is None, which is a default
3214     #         value, then quadrangles will be split by the smallest diagonal.
3215     #         Type SMESH.FunctorType._items in the Python Console to see all items.
3216     #         Note that not all items correspond to numerical functors.
3217     #  @return TRUE in case of success, FALSE otherwise.
3218     #  @ingroup l2_modif_cutquadr
3219     def QuadToTri (self, IDsOfElements, theCriterion = None):
3220         if IDsOfElements == []:
3221             IDsOfElements = self.GetElementsId()
3222         if theCriterion is None:
3223             theCriterion = FT_MaxElementLength2D
3224         Functor = self.smeshpyD.GetFunctor(theCriterion)
3225         return self.editor.QuadToTri(IDsOfElements, Functor)
3226
3227     ## Splits quadrangles into triangles.
3228     #  @param theObject the object from which the list of elements is taken,
3229     #         this is mesh, submesh or group
3230     #  @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3231     #         choose a diagonal for splitting. If @a theCriterion is None, which is a default
3232     #         value, then quadrangles will be split by the smallest diagonal.
3233     #         Type SMESH.FunctorType._items in the Python Console to see all items.
3234     #         Note that not all items correspond to numerical functors.
3235     #  @return TRUE in case of success, FALSE otherwise.
3236     #  @ingroup l2_modif_cutquadr
3237     def QuadToTriObject (self, theObject, theCriterion = None):
3238         if ( isinstance( theObject, Mesh )):
3239             theObject = theObject.GetMesh()
3240         if theCriterion is None:
3241             theCriterion = FT_MaxElementLength2D
3242         Functor = self.smeshpyD.GetFunctor(theCriterion)
3243         return self.editor.QuadToTriObject(theObject, Functor)
3244
3245     ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3246     #  a quadrangle.
3247     #  @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3248     #         group or a list of face IDs. By default all quadrangles are split
3249     #  @ingroup l2_modif_cutquadr
3250     def QuadTo4Tri (self, theElements=[]):
3251         unRegister = genObjUnRegister()
3252         if isinstance( theElements, Mesh ):
3253             theElements = theElements.mesh
3254         elif not theElements:
3255             theElements = self.mesh
3256         elif isinstance( theElements, list ):
3257             theElements = self.GetIDSource( theElements, SMESH.FACE )
3258             unRegister.set( theElements )
3259         return self.editor.QuadTo4Tri( theElements )
3260
3261     ## Splits quadrangles into triangles.
3262     #  @param IDsOfElements the faces to be splitted
3263     #  @param Diag13        is used to choose a diagonal for splitting.
3264     #  @return TRUE in case of success, FALSE otherwise.
3265     #  @ingroup l2_modif_cutquadr
3266     def SplitQuad (self, IDsOfElements, Diag13):
3267         if IDsOfElements == []:
3268             IDsOfElements = self.GetElementsId()
3269         return self.editor.SplitQuad(IDsOfElements, Diag13)
3270
3271     ## Splits quadrangles into triangles.
3272     #  @param theObject the object from which the list of elements is taken,
3273     #         this is mesh, submesh or group
3274     #  @param Diag13    is used to choose a diagonal for splitting.
3275     #  @return TRUE in case of success, FALSE otherwise.
3276     #  @ingroup l2_modif_cutquadr
3277     def SplitQuadObject (self, theObject, Diag13):
3278         if ( isinstance( theObject, Mesh )):
3279             theObject = theObject.GetMesh()
3280         return self.editor.SplitQuadObject(theObject, Diag13)
3281
3282     ## Finds a better splitting of the given quadrangle.
3283     #  @param IDOfQuad   the ID of the quadrangle to be splitted.
3284     #  @param theCriterion  is a numerical functor, in terms of enum SMESH.FunctorType, used to
3285     #         choose a diagonal for splitting.
3286     #         Type SMESH.FunctorType._items in the Python Console to see all items.
3287     #         Note that not all items correspond to numerical functors.
3288     #  @return 1 if 1-3 diagonal is better, 2 if 2-4
3289     #          diagonal is better, 0 if error occurs.
3290     #  @ingroup l2_modif_cutquadr
3291     def BestSplit (self, IDOfQuad, theCriterion):
3292         return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3293
3294     ## Splits volumic elements into tetrahedrons
3295     #  @param elems either a list of elements or a mesh or a group or a submesh or a filter
3296     #  @param method  flags passing splitting method:
3297     #         smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3298     #         smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3299     #  @ingroup l2_modif_cutquadr
3300     def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3301         unRegister = genObjUnRegister()
3302         if isinstance( elems, Mesh ):
3303             elems = elems.GetMesh()
3304         if ( isinstance( elems, list )):
3305             elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3306             unRegister.set( elems )
3307         self.editor.SplitVolumesIntoTetra(elems, method)
3308         return
3309
3310     ## Split bi-quadratic elements into linear ones without creation of additional nodes:
3311     #   - bi-quadratic triangle will be split into 3 linear quadrangles;
3312     #   - bi-quadratic quadrangle will be split into 4 linear quadrangles;
3313     #   - tri-quadratic hexahedron will be split into 8 linear hexahedra.
3314     #   Quadratic elements of lower dimension  adjacent to the split bi-quadratic element
3315     #   will be split in order to keep the mesh conformal.
3316     #  @param elems - elements to split: sub-meshes, groups, filters or element IDs;
3317     #         if None (default), all bi-quadratic elements will be split
3318     #  @ingroup l2_modif_cutquadr
3319     def SplitBiQuadraticIntoLinear(self, elems=None):
3320         unRegister = genObjUnRegister()
3321         if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
3322             elems = self.editor.MakeIDSource(elems, SMESH.ALL)
3323             unRegister.set( elems )
3324         if elems is None:
3325             elems = [ self.GetMesh() ]
3326         if isinstance( elems, Mesh ):
3327             elems = [ elems.GetMesh() ]
3328         if not isinstance( elems, list ):
3329             elems = [elems]
3330         self.editor.SplitBiQuadraticIntoLinear( elems )
3331
3332     ## Splits hexahedra into prisms
3333     #  @param elems either a list of elements or a mesh or a group or a submesh or a filter
3334     #  @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3335     #         gives a normal vector defining facets to split into triangles.
3336     #         @a startHexPoint can be either a triple of coordinates or a vertex.
3337     #  @param facetNormal a normal to a facet to split into triangles of a
3338     #         hexahedron found by @a startHexPoint.
3339     #         @a facetNormal can be either a triple of coordinates or an edge.
3340     #  @param method  flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3341     #         smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3342     #  @param allDomains if @c False, only hexahedra adjacent to one closest
3343     #         to @a startHexPoint are split, else @a startHexPoint
3344     #         is used to find the facet to split in all domains present in @a elems.
3345     #  @ingroup l2_modif_cutquadr
3346     def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3347                                  method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3348         # IDSource
3349         unRegister = genObjUnRegister()
3350         if isinstance( elems, Mesh ):
3351             elems = elems.GetMesh()
3352         if ( isinstance( elems, list )):
3353             elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3354             unRegister.set( elems )
3355             pass
3356         # axis
3357         if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3358             startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3359         elif isinstance( startHexPoint, list ):
3360             startHexPoint = SMESH.PointStruct( startHexPoint[0],
3361                                                startHexPoint[1],
3362                                                startHexPoint[2])
3363         if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3364             facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3365         elif isinstance( facetNormal, list ):
3366             facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3367                                                        facetNormal[1],
3368                                                        facetNormal[2])
3369         self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3370
3371         self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3372
3373     ## Splits quadrangle faces near triangular facets of volumes
3374     #
3375     #  @ingroup l1_auxiliary
3376     def SplitQuadsNearTriangularFacets(self):
3377         faces_array = self.GetElementsByType(SMESH.FACE)
3378         for face_id in faces_array:
3379             if self.GetElemNbNodes(face_id) == 4: # quadrangle
3380                 quad_nodes = self.mesh.GetElemNodes(face_id)
3381                 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3382                 isVolumeFound = False
3383                 for node1_elem in node1_elems:
3384                     if not isVolumeFound:
3385                         if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3386                             nb_nodes = self.GetElemNbNodes(node1_elem)
3387                             if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3388                                 volume_elem = node1_elem
3389                                 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3390                                 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3391                                     if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3392                                         isVolumeFound = True
3393                                         if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3394                                             self.SplitQuad([face_id], False) # diagonal 2-4
3395                                     elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3396                                         isVolumeFound = True
3397                                         self.SplitQuad([face_id], True) # diagonal 1-3
3398                                 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3399                                     if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3400                                         isVolumeFound = True
3401                                         self.SplitQuad([face_id], True) # diagonal 1-3
3402
3403     ## @brief Splits hexahedrons into tetrahedrons.
3404     #
3405     #  This operation uses pattern mapping functionality for splitting.
3406     #  @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3407     #  @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3408     #         pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3409     #         will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3410     #         key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3411     #         The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3412     #  @return TRUE in case of success, FALSE otherwise.
3413     #  @ingroup l1_auxiliary
3414     def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3415         # Pattern:     5.---------.6
3416         #              /|#*      /|
3417         #             / | #*    / |
3418         #            /  |  # * /  |
3419         #           /   |   # /*  |
3420         # (0,0,1) 4.---------.7 * |
3421         #          |#*  |1   | # *|
3422         #          | # *.----|---#.2
3423         #          |  #/ *   |   /
3424         #          |  /#  *  |  /
3425         #          | /   # * | /
3426         #          |/      #*|/
3427         # (0,0,0) 0.---------.3
3428         pattern_tetra = "!!! Nb of points: \n 8 \n\
3429         !!! Points: \n\
3430         0 0 0  !- 0 \n\
3431         0 1 0  !- 1 \n\
3432         1 1 0  !- 2 \n\
3433         1 0 0  !- 3 \n\
3434         0 0 1  !- 4 \n\
3435         0 1 1  !- 5 \n\
3436         1 1 1  !- 6 \n\
3437         1 0 1  !- 7 \n\
3438         !!! Indices of points of 6 tetras: \n\
3439         0 3 4 1 \n\
3440         7 4 3 1 \n\
3441         4 7 5 1 \n\
3442         6 2 5 7 \n\
3443         1 5 2 7 \n\
3444         2 3 1 7 \n"
3445
3446         pattern = self.smeshpyD.GetPattern()
3447         isDone  = pattern.LoadFromFile(pattern_tetra)
3448         if not isDone:
3449             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3450             return isDone
3451
3452         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3453         isDone = pattern.MakeMesh(self.mesh, False, False)
3454         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3455
3456         # split quafrangle faces near triangular facets of volumes
3457         self.SplitQuadsNearTriangularFacets()
3458
3459         return isDone
3460
3461     ## @brief Split hexahedrons into prisms.
3462     #
3463     #  Uses the pattern mapping functionality for splitting.
3464     #  @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3465     #  @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3466     #         pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3467     #         will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3468     #         will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3469     #         Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3470     #  @return TRUE in case of success, FALSE otherwise.
3471     #  @ingroup l1_auxiliary
3472     def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3473         # Pattern:     5.---------.6
3474         #              /|#       /|
3475         #             / | #     / |
3476         #            /  |  #   /  |
3477         #           /   |   # /   |
3478         # (0,0,1) 4.---------.7   |
3479         #          |    |    |    |
3480         #          |   1.----|----.2
3481         #          |   / *   |   /
3482         #          |  /   *  |  /
3483         #          | /     * | /
3484         #          |/       *|/
3485         # (0,0,0) 0.---------.3
3486         pattern_prism = "!!! Nb of points: \n 8 \n\
3487         !!! Points: \n\
3488         0 0 0  !- 0 \n\
3489         0 1 0  !- 1 \n\
3490         1 1 0  !- 2 \n\
3491         1 0 0  !- 3 \n\
3492         0 0 1  !- 4 \n\
3493         0 1 1  !- 5 \n\
3494         1 1 1  !- 6 \n\
3495         1 0 1  !- 7 \n\
3496         !!! Indices of points of 2 prisms: \n\
3497         0 1 3 4 5 7 \n\
3498         2 3 1 6 7 5 \n"
3499
3500         pattern = self.smeshpyD.GetPattern()
3501         isDone  = pattern.LoadFromFile(pattern_prism)
3502         if not isDone:
3503             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3504             return isDone
3505
3506         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3507         isDone = pattern.MakeMesh(self.mesh, False, False)
3508         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3509
3510         # Splits quafrangle faces near triangular facets of volumes
3511         self.SplitQuadsNearTriangularFacets()
3512
3513         return isDone
3514
3515     ## Smoothes elements
3516     #  @param IDsOfElements the list if ids of elements to smooth
3517     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3518     #  Note that nodes built on edges and boundary nodes are always fixed.
3519     #  @param MaxNbOfIterations the maximum number of iterations
3520     #  @param MaxAspectRatio varies in range [1.0, inf]
3521     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3522     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3523     #  @return TRUE in case of success, FALSE otherwise.
3524     #  @ingroup l2_modif_smooth
3525     def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3526                MaxNbOfIterations, MaxAspectRatio, Method):
3527         if IDsOfElements == []:
3528             IDsOfElements = self.GetElementsId()
3529         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3530         self.mesh.SetParameters(Parameters)
3531         return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3532                                   MaxNbOfIterations, MaxAspectRatio, Method)
3533
3534     ## Smoothes elements which belong to the given object
3535     #  @param theObject the object to smooth
3536     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3537     #  Note that nodes built on edges and boundary nodes are always fixed.
3538     #  @param MaxNbOfIterations the maximum number of iterations
3539     #  @param MaxAspectRatio varies in range [1.0, inf]
3540     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3541     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3542     #  @return TRUE in case of success, FALSE otherwise.
3543     #  @ingroup l2_modif_smooth
3544     def SmoothObject(self, theObject, IDsOfFixedNodes,
3545                      MaxNbOfIterations, MaxAspectRatio, Method):
3546         if ( isinstance( theObject, Mesh )):
3547             theObject = theObject.GetMesh()
3548         return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3549                                         MaxNbOfIterations, MaxAspectRatio, Method)
3550
3551     ## Parametrically smoothes the given elements
3552     #  @param IDsOfElements the list if ids of elements to smooth
3553     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3554     #  Note that nodes built on edges and boundary nodes are always fixed.
3555     #  @param MaxNbOfIterations the maximum number of iterations
3556     #  @param MaxAspectRatio varies in range [1.0, inf]
3557     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3558     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3559     #  @return TRUE in case of success, FALSE otherwise.
3560     #  @ingroup l2_modif_smooth
3561     def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3562                          MaxNbOfIterations, MaxAspectRatio, Method):
3563         if IDsOfElements == []:
3564             IDsOfElements = self.GetElementsId()
3565         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3566         self.mesh.SetParameters(Parameters)
3567         return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3568                                             MaxNbOfIterations, MaxAspectRatio, Method)
3569
3570     ## Parametrically smoothes the elements which belong to the given object
3571     #  @param theObject the object to smooth
3572     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3573     #  Note that nodes built on edges and boundary nodes are always fixed.
3574     #  @param MaxNbOfIterations the maximum number of iterations
3575     #  @param MaxAspectRatio varies in range [1.0, inf]
3576     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3577     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3578     #  @return TRUE in case of success, FALSE otherwise.
3579     #  @ingroup l2_modif_smooth
3580     def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3581                                MaxNbOfIterations, MaxAspectRatio, Method):
3582         if ( isinstance( theObject, Mesh )):
3583             theObject = theObject.GetMesh()
3584         return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3585                                                   MaxNbOfIterations, MaxAspectRatio, Method)
3586
3587     ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3588     #  them with quadratic with the same id.
3589     #  @param theForce3d new node creation method:
3590     #         0 - the medium node lies at the geometrical entity from which the mesh element is built
3591     #         1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3592     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3593     #  @param theToBiQuad If True, converts the mesh to bi-quadratic
3594     #  @ingroup l2_modif_tofromqu
3595     def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3596         if isinstance( theSubMesh, Mesh ):
3597             theSubMesh = theSubMesh.mesh
3598         if theToBiQuad:
3599             self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3600         else:
3601             if theSubMesh:
3602                 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3603             else:
3604                 self.editor.ConvertToQuadratic(theForce3d)
3605         error = self.editor.GetLastError()
3606         if error and error.comment:
3607             print error.comment
3608             
3609     ## Converts the mesh from quadratic to ordinary,
3610     #  deletes old quadratic elements, \n replacing
3611     #  them with ordinary mesh elements with the same id.
3612     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3613     #  @ingroup l2_modif_tofromqu
3614     def ConvertFromQuadratic(self, theSubMesh=None):
3615         if theSubMesh:
3616             self.editor.ConvertFromQuadraticObject(theSubMesh)
3617         else:
3618             return self.editor.ConvertFromQuadratic()
3619
3620     ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3621     #  @return TRUE if operation has been completed successfully, FALSE otherwise
3622     #  @ingroup l2_modif_edit
3623     def Make2DMeshFrom3D(self):
3624         return self.editor.Make2DMeshFrom3D()
3625
3626     ## Creates missing boundary elements
3627     #  @param elements - elements whose boundary is to be checked:
3628     #                    mesh, group, sub-mesh or list of elements
3629     #   if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3630     #  @param dimension - defines type of boundary elements to create, either of
3631     #                     { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3632     #    SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3633     #  @param groupName - a name of group to store created boundary elements in,
3634     #                     "" means not to create the group
3635     #  @param meshName - a name of new mesh to store created boundary elements in,
3636     #                     "" means not to create the new mesh
3637     #  @param toCopyElements - if true, the checked elements will be copied into
3638     #     the new mesh else only boundary elements will be copied into the new mesh
3639     #  @param toCopyExistingBondary - if true, not only new but also pre-existing
3640     #     boundary elements will be copied into the new mesh
3641     #  @return tuple (mesh, group) where boundary elements were added to
3642     #  @ingroup l2_modif_edit
3643     def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3644                          toCopyElements=False, toCopyExistingBondary=False):
3645         unRegister = genObjUnRegister()
3646         if isinstance( elements, Mesh ):
3647             elements = elements.GetMesh()
3648         if ( isinstance( elements, list )):
3649             elemType = SMESH.ALL
3650             if elements: elemType = self.GetElementType( elements[0], iselem=True)
3651             elements = self.editor.MakeIDSource(elements, elemType)
3652             unRegister.set( elements )
3653         mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3654                                                    toCopyElements,toCopyExistingBondary)
3655         if mesh: mesh = self.smeshpyD.Mesh(mesh)
3656         return mesh, group
3657
3658     ##
3659     # @brief Creates missing boundary elements around either the whole mesh or 
3660     #    groups of elements
3661     #  @param dimension - defines type of boundary elements to create, either of
3662     #                     { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3663     #  @param groupName - a name of group to store all boundary elements in,
3664     #    "" means not to create the group
3665     #  @param meshName - a name of a new mesh, which is a copy of the initial 
3666     #    mesh + created boundary elements; "" means not to create the new mesh
3667     #  @param toCopyAll - if true, the whole initial mesh will be copied into
3668     #    the new mesh else only boundary elements will be copied into the new mesh
3669     #  @param groups - groups of elements to make boundary around
3670     #  @retval tuple( long, mesh, groups )
3671     #                 long - number of added boundary elements
3672     #                 mesh - the mesh where elements were added to
3673     #                 group - the group of boundary elements or None
3674     #
3675     def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3676                              toCopyAll=False, groups=[]):
3677         nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3678                                                            toCopyAll,groups)
3679         if mesh: mesh = self.smeshpyD.Mesh(mesh)
3680         return nb, mesh, group
3681
3682     ## Renumber mesh nodes (Obsolete, does nothing)
3683     #  @ingroup l2_modif_renumber
3684     def RenumberNodes(self):
3685         self.editor.RenumberNodes()
3686
3687     ## Renumber mesh elements (Obsole, does nothing)
3688     #  @ingroup l2_modif_renumber
3689     def RenumberElements(self):
3690         self.editor.RenumberElements()
3691
3692     ## Private method converting \a arg into a list of SMESH_IdSource's
3693     def _getIdSourceList(self, arg, idType, unRegister):
3694         if arg and isinstance( arg, list ):
3695             if isinstance( arg[0], int ):
3696                 arg = self.GetIDSource( arg, idType )
3697                 unRegister.set( arg )
3698             elif isinstance( arg[0], Mesh ):
3699                 arg[0] = arg[0].GetMesh()
3700         elif isinstance( arg, Mesh ):
3701             arg = arg.GetMesh()
3702         if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3703             arg = [arg]
3704         return arg
3705
3706     ## Generates new elements by rotation of the given elements and nodes around the axis
3707     #  @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3708     #  @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3709     #  @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3710     #  @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3711     #  @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3712     #         which defines angle in degrees
3713     #  @param NbOfSteps the number of steps
3714     #  @param Tolerance tolerance
3715     #  @param MakeGroups forces the generation of new groups from existing ones
3716     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3717     #                    of all steps, else - size of each step
3718     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3719     #  @ingroup l2_modif_extrurev
3720     def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3721                              MakeGroups=False, TotalAngle=False):
3722         unRegister = genObjUnRegister()
3723         nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3724         edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3725         faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3726
3727         if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3728             Axis = self.smeshpyD.GetAxisStruct( Axis )
3729         if isinstance( Axis, list ):
3730             Axis = SMESH.AxisStruct( *Axis )
3731
3732         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3733         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3734         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3735         self.mesh.SetParameters(Parameters)
3736         if TotalAngle and NbOfSteps:
3737             AngleInRadians /= NbOfSteps
3738         return self.editor.RotationSweepObjects( nodes, edges, faces,
3739                                                  Axis, AngleInRadians,
3740                                                  NbOfSteps, Tolerance, MakeGroups)
3741
3742     ## Generates new elements by rotation of the elements around the axis
3743     #  @param IDsOfElements the list of ids of elements to sweep
3744     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3745     #  @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3746     #  @param NbOfSteps the number of steps
3747     #  @param Tolerance tolerance
3748     #  @param MakeGroups forces the generation of new groups from existing ones
3749     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3750     #                    of all steps, else - size of each step
3751     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3752     #  @ingroup l2_modif_extrurev
3753     def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3754                       MakeGroups=False, TotalAngle=False):
3755         return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3756                                          AngleInRadians, NbOfSteps, Tolerance,
3757                                          MakeGroups, TotalAngle)
3758
3759     ## Generates new elements by rotation of the elements of object around the axis
3760     #  @param theObject object which elements should be sweeped.
3761     #                   It can be a mesh, a sub mesh or a group.
3762     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3763     #  @param AngleInRadians the angle of Rotation
3764     #  @param NbOfSteps number of steps
3765     #  @param Tolerance tolerance
3766     #  @param MakeGroups forces the generation of new groups from existing ones
3767     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3768     #                    of all steps, else - size of each step
3769     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3770     #  @ingroup l2_modif_extrurev
3771     def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3772                             MakeGroups=False, TotalAngle=False):
3773         return self.RotationSweepObjects( [], theObject, theObject, Axis,
3774                                           AngleInRadians, NbOfSteps, Tolerance,
3775                                           MakeGroups, TotalAngle )
3776
3777     ## Generates new elements by rotation of the elements of object around the axis
3778     #  @param theObject object which elements should be sweeped.
3779     #                   It can be a mesh, a sub mesh or a group.
3780     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3781     #  @param AngleInRadians the angle of Rotation
3782     #  @param NbOfSteps number of steps
3783     #  @param Tolerance tolerance
3784     #  @param MakeGroups forces the generation of new groups from existing ones
3785     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3786     #                    of all steps, else - size of each step
3787     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3788     #  @ingroup l2_modif_extrurev
3789     def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3790                               MakeGroups=False, TotalAngle=False):
3791         return self.RotationSweepObjects([],theObject,[], Axis,
3792                                          AngleInRadians, NbOfSteps, Tolerance,
3793                                          MakeGroups, TotalAngle)
3794
3795     ## Generates new elements by rotation of the elements of object around the axis
3796     #  @param theObject object which elements should be sweeped.
3797     #                   It can be a mesh, a sub mesh or a group.
3798     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3799     #  @param AngleInRadians the angle of Rotation
3800     #  @param NbOfSteps number of steps
3801     #  @param Tolerance tolerance
3802     #  @param MakeGroups forces the generation of new groups from existing ones
3803     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3804     #                    of all steps, else - size of each step
3805     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3806     #  @ingroup l2_modif_extrurev
3807     def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3808                               MakeGroups=False, TotalAngle=False):
3809         return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3810                                          NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3811
3812     ## Generates new elements by extrusion of the given elements and nodes
3813     #  @param nodes - nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3814     #  @param edges - edges to extrude: a list including ids, groups, sub-meshes or a mesh
3815     #  @param faces - faces to extrude: a list including ids, groups, sub-meshes or a mesh
3816     #  @param StepVector vector or DirStruct or 3 vector components, defining
3817     #         the direction and value of extrusion for one step (the total extrusion
3818     #         length will be NbOfSteps * ||StepVector||)
3819     #  @param NbOfSteps the number of steps
3820     #  @param MakeGroups forces the generation of new groups from existing ones
3821     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3822     #  @ingroup l2_modif_extrurev
3823     def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False):
3824         unRegister = genObjUnRegister()
3825         nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3826         edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3827         faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3828
3829         if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3830             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3831         if isinstance( StepVector, list ):
3832             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3833
3834         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3835         Parameters = StepVector.PS.parameters + var_separator + Parameters
3836         self.mesh.SetParameters(Parameters)
3837
3838         return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
3839                                                   StepVector, NbOfSteps, MakeGroups)
3840
3841
3842     ## Generates new elements by extrusion of the elements with given ids
3843     #  @param IDsOfElements the list of ids of elements or nodes for extrusion
3844     #  @param StepVector vector or DirStruct or 3 vector components, defining
3845     #         the direction and value of extrusion for one step (the total extrusion
3846     #         length will be NbOfSteps * ||StepVector||)
3847     #  @param NbOfSteps the number of steps
3848     #  @param MakeGroups forces the generation of new groups from existing ones
3849     #  @param IsNodes is True if elements with given ids are nodes
3850     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3851     #  @ingroup l2_modif_extrurev
3852     def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3853         n,e,f = [],[],[]
3854         if IsNodes: n = IDsOfElements
3855         else      : e,f, = IDsOfElements,IDsOfElements
3856         return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3857
3858     ## Generates new elements by extrusion along the normal to a discretized surface or wire
3859     #  @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh.
3860     #         Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
3861     #  @param StepSize length of one extrusion step (the total extrusion
3862     #         length will be \a NbOfSteps * \a StepSize ).
3863     #  @param NbOfSteps number of extrusion steps.
3864     #  @param ByAverageNormal if True each node is translated by \a StepSize
3865     #         along the average of the normal vectors to the faces sharing the node;
3866     #         else each node is translated along the same average normal till
3867     #         intersection with the plane got by translation of the face sharing
3868     #         the node along its own normal by \a StepSize.
3869     #  @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3870     #         for every node of \a Elements.
3871     #  @param MakeGroups forces generation of new groups from existing ones.
3872     #  @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
3873     #         is not yet implemented. This parameter is used if \a Elements contains
3874     #         both faces and edges, i.e. \a Elements is a Mesh.
3875     #  @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
3876     #          empty list otherwise.
3877     #  @ingroup l2_modif_extrurev
3878     def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
3879                           ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
3880         unRegister = genObjUnRegister()
3881         if isinstance( Elements, Mesh ):
3882             Elements = [ Elements.GetMesh() ]
3883         if isinstance( Elements, list ):
3884             if not Elements:
3885                 raise RuntimeError, "Elements empty!"
3886             if isinstance( Elements[0], int ):
3887                 Elements = self.GetIDSource( Elements, SMESH.ALL )
3888                 unRegister.set( Elements )
3889         if not isinstance( Elements, list ):
3890             Elements = [ Elements ]
3891         StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
3892         self.mesh.SetParameters(Parameters)
3893         return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
3894                                              ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
3895
3896     ## Generates new elements by extrusion of the elements or nodes which belong to the object
3897     #  @param theObject the object whose elements or nodes should be processed.
3898     #                   It can be a mesh, a sub-mesh or a group.
3899     #  @param StepVector vector or DirStruct or 3 vector components, defining
3900     #         the direction and value of extrusion for one step (the total extrusion
3901     #         length will be NbOfSteps * ||StepVector||)
3902     #  @param NbOfSteps the number of steps
3903     #  @param MakeGroups forces the generation of new groups from existing ones
3904     #  @param IsNodes is True if elements to extrude are nodes
3905     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3906     #  @ingroup l2_modif_extrurev
3907     def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3908         n,e,f = [],[],[]
3909         if IsNodes: n    = theObject
3910         else      : e,f, = theObject,theObject
3911         return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3912
3913     ## Generates new elements by extrusion of edges which belong to the object
3914     #  @param theObject object whose 1D elements should be processed.
3915     #                   It can be a mesh, a sub-mesh or a group.
3916     #  @param StepVector vector or DirStruct or 3 vector components, defining
3917     #         the direction and value of extrusion for one step (the total extrusion
3918     #         length will be NbOfSteps * ||StepVector||)
3919     #  @param NbOfSteps the number of steps
3920     #  @param MakeGroups to generate new groups from existing ones
3921     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3922     #  @ingroup l2_modif_extrurev
3923     def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3924         return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
3925
3926     ## Generates new elements by extrusion of faces which belong to the object
3927     #  @param theObject object whose 2D elements should be processed.
3928     #                   It can be a mesh, a sub-mesh or a group.
3929     #  @param StepVector vector or DirStruct or 3 vector components, defining
3930     #         the direction and value of extrusion for one step (the total extrusion
3931     #         length will be NbOfSteps * ||StepVector||)
3932     #  @param NbOfSteps the number of steps
3933     #  @param MakeGroups forces the generation of new groups from existing ones
3934     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3935     #  @ingroup l2_modif_extrurev
3936     def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3937         return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
3938
3939     ## Generates new elements by extrusion of the elements with given ids
3940     #  @param IDsOfElements is ids of elements
3941     #  @param StepVector vector or DirStruct or 3 vector components, defining
3942     #         the direction and value of extrusion for one step (the total extrusion
3943     #         length will be NbOfSteps * ||StepVector||)
3944     #  @param NbOfSteps the number of steps
3945     #  @param ExtrFlags sets flags for extrusion
3946     #  @param SewTolerance uses for comparing locations of nodes if flag
3947     #         EXTRUSION_FLAG_SEW is set
3948     #  @param MakeGroups forces the generation of new groups from existing ones
3949     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3950     #  @ingroup l2_modif_extrurev
3951     def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3952                           ExtrFlags, SewTolerance, MakeGroups=False):
3953         if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3954             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3955         if isinstance( StepVector, list ):
3956             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3957         return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3958                                              ExtrFlags, SewTolerance, MakeGroups)
3959
3960     ## Generates new elements by extrusion of the given elements and nodes along the path.
3961     #  The path of extrusion must be a meshed edge.
3962     #  @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3963     #  @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3964     #  @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3965     #  @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3966     #  @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
3967     #         contains not only path segments, else it can be None
3968     #  @param NodeStart the first or the last node on the path. Defines the direction of extrusion
3969     #  @param HasAngles allows the shape to be rotated around the path
3970     #                   to get the resulting mesh in a helical fashion
3971     #  @param Angles list of angles
3972     #  @param LinearVariation forces the computation of rotation angles as linear
3973     #                         variation of the given Angles along path steps
3974     #  @param HasRefPoint allows using the reference point
3975     #  @param RefPoint the point around which the shape is rotated (the mass center of the
3976     #         shape by default). The User can specify any point as the Reference Point.
3977     #  @param MakeGroups forces the generation of new groups from existing ones
3978     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
3979     #  @ingroup l2_modif_extrurev
3980     def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
3981                                   NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
3982                                   HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
3983         unRegister = genObjUnRegister()
3984         Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
3985         Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
3986         Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
3987
3988         if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3989             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3990         if isinstance( RefPoint, list ):
3991             if not RefPoint: RefPoint = [0,0,0]
3992             RefPoint = SMESH.PointStruct( *RefPoint )
3993         if isinstance( PathMesh, Mesh ):
3994             PathMesh = PathMesh.GetMesh()
3995         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3996         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3997         self.mesh.SetParameters(Parameters)
3998         return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
3999                                                      PathMesh, PathShape, NodeStart,
4000                                                      HasAngles, Angles, LinearVariation,
4001                                                      HasRefPoint, RefPoint, MakeGroups)
4002
4003     ## Generates new elements by extrusion of the given elements
4004     #  The path of extrusion must be a meshed edge.
4005     #  @param Base mesh or group, or sub-mesh, or list of ids of elements for extrusion
4006     #  @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4007     #  @param NodeStart the start node from Path. Defines the direction of extrusion
4008     #  @param HasAngles allows the shape to be rotated around the path
4009     #                   to get the resulting mesh in a helical fashion
4010     #  @param Angles list of angles in radians
4011     #  @param LinearVariation forces the computation of rotation angles as linear
4012     #                         variation of the given Angles along path steps
4013     #  @param HasRefPoint allows using the reference point
4014     #  @param RefPoint the point around which the elements are rotated (the mass
4015     #         center of the elements by default).
4016     #         The User can specify any point as the Reference Point.
4017     #         RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
4018     #  @param MakeGroups forces the generation of new groups from existing ones
4019     #  @param ElemType type of elements for extrusion (if param Base is a mesh)
4020     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4021     #          only SMESH::Extrusion_Error otherwise
4022     #  @ingroup l2_modif_extrurev
4023     def ExtrusionAlongPathX(self, Base, Path, NodeStart,
4024                             HasAngles=False, Angles=[], LinearVariation=False,
4025                             HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
4026                             ElemType=SMESH.FACE):
4027         n,e,f = [],[],[]
4028         if ElemType == SMESH.NODE: n = Base
4029         if ElemType == SMESH.EDGE: e = Base
4030         if ElemType == SMESH.FACE: f = Base
4031         gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
4032                                                HasAngles, Angles, LinearVariation,
4033                                                HasRefPoint, RefPoint, MakeGroups)
4034         if MakeGroups: return gr,er
4035         return er
4036
4037     ## Generates new elements by extrusion of the given elements
4038     #  The path of extrusion must be a meshed edge.
4039     #  @param IDsOfElements ids of elements
4040     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
4041     #  @param PathShape shape(edge) defines the sub-mesh for the path
4042     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4043     #  @param HasAngles allows the shape to be rotated around the path
4044     #                   to get the resulting mesh in a helical fashion
4045     #  @param Angles list of angles in radians
4046     #  @param HasRefPoint allows using the reference point
4047     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4048     #         The User can specify any point as the Reference Point.
4049     #  @param MakeGroups forces the generation of new groups from existing ones
4050     #  @param LinearVariation forces the computation of rotation angles as linear
4051     #                         variation of the given Angles along path steps
4052     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4053     #          only SMESH::Extrusion_Error otherwise
4054     #  @ingroup l2_modif_extrurev
4055     def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
4056                            HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4057                            MakeGroups=False, LinearVariation=False):
4058         n,e,f = [],IDsOfElements,IDsOfElements
4059         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
4060                                                NodeStart, HasAngles, Angles,
4061                                                LinearVariation,
4062                                                HasRefPoint, RefPoint, MakeGroups)
4063         if MakeGroups: return gr,er
4064         return er
4065
4066     ## Generates new elements by extrusion of the elements which belong to the object
4067     #  The path of extrusion must be a meshed edge.
4068     #  @param theObject the object whose elements should be processed.
4069     #                   It can be a mesh, a sub-mesh or a group.
4070     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4071     #  @param PathShape shape(edge) defines the sub-mesh for the path
4072     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4073     #  @param HasAngles allows the shape to be rotated around the path
4074     #                   to get the resulting mesh in a helical fashion
4075     #  @param Angles list of angles
4076     #  @param HasRefPoint allows using the reference point
4077     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4078     #         The User can specify any point as the Reference Point.
4079     #  @param MakeGroups forces the generation of new groups from existing ones
4080     #  @param LinearVariation forces the computation of rotation angles as linear
4081     #                         variation of the given Angles along path steps
4082     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4083     #          only SMESH::Extrusion_Error otherwise
4084     #  @ingroup l2_modif_extrurev
4085     def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4086                                  HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4087                                  MakeGroups=False, LinearVariation=False):
4088         n,e,f = [],theObject,theObject
4089         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4090                                                HasAngles, Angles, LinearVariation,
4091                                                HasRefPoint, RefPoint, MakeGroups)
4092         if MakeGroups: return gr,er
4093         return er
4094
4095     ## Generates new elements by extrusion of mesh segments which belong to the object
4096     #  The path of extrusion must be a meshed edge.
4097     #  @param theObject the object whose 1D elements should be processed.
4098     #                   It can be a mesh, a sub-mesh or a group.
4099     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4100     #  @param PathShape shape(edge) defines the sub-mesh for the path
4101     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4102     #  @param HasAngles allows the shape to be rotated around the path
4103     #                   to get the resulting mesh in a helical fashion
4104     #  @param Angles list of angles
4105     #  @param HasRefPoint allows using the reference point
4106     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4107     #         The User can specify any point as the Reference Point.
4108     #  @param MakeGroups forces the generation of new groups from existing ones
4109     #  @param LinearVariation forces the computation of rotation angles as linear
4110     #                         variation of the given Angles along path steps
4111     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4112     #          only SMESH::Extrusion_Error otherwise
4113     #  @ingroup l2_modif_extrurev
4114     def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4115                                    HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4116                                    MakeGroups=False, LinearVariation=False):
4117         n,e,f = [],theObject,[]
4118         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4119                                                HasAngles, Angles, LinearVariation,
4120                                                HasRefPoint, RefPoint, MakeGroups)
4121         if MakeGroups: return gr,er
4122         return er
4123
4124     ## Generates new elements by extrusion of faces which belong to the object
4125     #  The path of extrusion must be a meshed edge.
4126     #  @param theObject the object whose 2D elements should be processed.
4127     #                   It can be a mesh, a sub-mesh or a group.
4128     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4129     #  @param PathShape shape(edge) defines the sub-mesh for the path
4130     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4131     #  @param HasAngles allows the shape to be rotated around the path
4132     #                   to get the resulting mesh in a helical fashion
4133     #  @param Angles list of angles
4134     #  @param HasRefPoint allows using the reference point
4135     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4136     #         The User can specify any point as the Reference Point.
4137     #  @param MakeGroups forces the generation of new groups from existing ones
4138     #  @param LinearVariation forces the computation of rotation angles as linear
4139     #                         variation of the given Angles along path steps
4140     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4141     #          only SMESH::Extrusion_Error otherwise
4142     #  @ingroup l2_modif_extrurev
4143     def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4144                                    HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4145                                    MakeGroups=False, LinearVariation=False):
4146         n,e,f = [],[],theObject
4147         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4148                                                HasAngles, Angles, LinearVariation,
4149                                                HasRefPoint, RefPoint, MakeGroups)
4150         if MakeGroups: return gr,er
4151         return er
4152
4153     ## Creates a symmetrical copy of mesh elements
4154     #  @param IDsOfElements list of elements ids
4155     #  @param Mirror is AxisStruct or geom object(point, line, plane)
4156     #  @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4157     #         If the Mirror is a geom object this parameter is unnecessary
4158     #  @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4159     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4160     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4161     #  @ingroup l2_modif_trsf
4162     def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4163         if IDsOfElements == []:
4164             IDsOfElements = self.GetElementsId()
4165         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4166             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
4167             theMirrorType = Mirror._mirrorType
4168         else:
4169             self.mesh.SetParameters(Mirror.parameters)
4170         if Copy and MakeGroups:
4171             return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4172         self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4173         return []
4174
4175     ## Creates a new mesh by a symmetrical copy of mesh elements
4176     #  @param IDsOfElements the list of elements ids
4177     #  @param Mirror is AxisStruct or geom object (point, line, plane)
4178     #  @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4179     #         If the Mirror is a geom object this parameter is unnecessary
4180     #  @param MakeGroups to generate new groups from existing ones
4181     #  @param NewMeshName a name of the new mesh to create
4182     #  @return instance of Mesh class
4183     #  @ingroup l2_modif_trsf
4184     def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4185         if IDsOfElements == []:
4186             IDsOfElements = self.GetElementsId()
4187         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4188             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
4189             theMirrorType = Mirror._mirrorType
4190         else:
4191             self.mesh.SetParameters(Mirror.parameters)
4192         mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4193                                           MakeGroups, NewMeshName)
4194         return Mesh(self.smeshpyD,self.geompyD,mesh)
4195
4196     ## Creates a symmetrical copy of the object
4197     #  @param theObject mesh, submesh or group
4198     #  @param Mirror AxisStruct or geom object (point, line, plane)
4199     #  @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4200     #         If the Mirror is a geom object this parameter is unnecessary
4201     #  @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4202     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4203     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4204     #  @ingroup l2_modif_trsf
4205     def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4206         if ( isinstance( theObject, Mesh )):
4207             theObject = theObject.GetMesh()
4208         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4209             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
4210             theMirrorType = Mirror._mirrorType
4211         else:
4212             self.mesh.SetParameters(Mirror.parameters)
4213         if Copy and MakeGroups:
4214             return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4215         self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4216         return []
4217
4218     ## Creates a new mesh by a symmetrical copy of the object
4219     #  @param theObject mesh, submesh or group
4220     #  @param Mirror AxisStruct or geom object (point, line, plane)
4221     #  @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4222     #         If the Mirror is a geom object this parameter is unnecessary
4223     #  @param MakeGroups forces the generation of new groups from existing ones
4224     #  @param NewMeshName the name of the new mesh to create
4225     #  @return instance of Mesh class
4226     #  @ingroup l2_modif_trsf
4227     def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4228         if ( isinstance( theObject, Mesh )):
4229             theObject = theObject.GetMesh()
4230         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4231             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
4232             theMirrorType = Mirror._mirrorType
4233         else:
4234             self.mesh.SetParameters(Mirror.parameters)
4235         mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4236                                                 MakeGroups, NewMeshName)
4237         return Mesh( self.smeshpyD,self.geompyD,mesh )
4238
4239     ## Translates the elements
4240     #  @param IDsOfElements list of elements ids
4241     #  @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4242     #  @param Copy allows copying the translated elements
4243     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4244     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4245     #  @ingroup l2_modif_trsf
4246     def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4247         if IDsOfElements == []:
4248             IDsOfElements = self.GetElementsId()
4249         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4250             Vector = self.smeshpyD.GetDirStruct(Vector)
4251         if isinstance( Vector, list ):
4252             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4253         self.mesh.SetParameters(Vector.PS.parameters)
4254         if Copy and MakeGroups:
4255             return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4256         self.editor.Translate(IDsOfElements, Vector, Copy)
4257         return []
4258
4259     ## Creates a new mesh of translated elements
4260     #  @param IDsOfElements list of elements ids
4261     #  @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4262     #  @param MakeGroups forces the generation of new groups from existing ones
4263     #  @param NewMeshName the name of the newly created mesh
4264     #  @return instance of Mesh class
4265     #  @ingroup l2_modif_trsf
4266     def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4267         if IDsOfElements == []:
4268             IDsOfElements = self.GetElementsId()
4269         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4270             Vector = self.smeshpyD.GetDirStruct(Vector)
4271         if isinstance( Vector, list ):
4272             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4273         self.mesh.SetParameters(Vector.PS.parameters)
4274         mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4275         return Mesh ( self.smeshpyD, self.geompyD, mesh )
4276
4277     ## Translates the object
4278     #  @param theObject the object to translate (mesh, submesh, or group)
4279     #  @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4280     #  @param Copy allows copying the translated elements
4281     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4282     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4283     #  @ingroup l2_modif_trsf
4284     def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4285         if ( isinstance( theObject, Mesh )):
4286             theObject = theObject.GetMesh()
4287         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4288             Vector = self.smeshpyD.GetDirStruct(Vector)
4289         if isinstance( Vector, list ):
4290             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4291         self.mesh.SetParameters(Vector.PS.parameters)
4292         if Copy and MakeGroups:
4293             return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4294         self.editor.TranslateObject(theObject, Vector, Copy)
4295         return []
4296
4297     ## Creates a new mesh from the translated object
4298     #  @param theObject the object to translate (mesh, submesh, or group)
4299     #  @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4300     #  @param MakeGroups forces the generation of new groups from existing ones
4301     #  @param NewMeshName the name of the newly created mesh
4302     #  @return instance of Mesh class
4303     #  @ingroup l2_modif_trsf
4304     def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4305         if isinstance( theObject, Mesh ):
4306             theObject = theObject.GetMesh()
4307         if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4308             Vector = self.smeshpyD.GetDirStruct(Vector)
4309         if isinstance( Vector, list ):
4310             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4311         self.mesh.SetParameters(Vector.PS.parameters)
4312         mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4313         return Mesh( self.smeshpyD, self.geompyD, mesh )
4314
4315
4316
4317     ## Scales the object
4318     #  @param theObject - the object to translate (mesh, submesh, or group)
4319     #  @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4320     #  @param theScaleFact - list of 1-3 scale factors for axises
4321     #  @param Copy - allows copying the translated elements
4322     #  @param MakeGroups - forces the generation of new groups from existing
4323     #                      ones (if Copy)
4324     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4325     #          empty list otherwise
4326     def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4327         unRegister = genObjUnRegister()
4328         if ( isinstance( theObject, Mesh )):
4329             theObject = theObject.GetMesh()
4330         if ( isinstance( theObject, list )):
4331             theObject = self.GetIDSource(theObject, SMESH.ALL)
4332             unRegister.set( theObject )
4333         if ( isinstance( thePoint, list )):
4334             thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4335         if ( isinstance( theScaleFact, float )):
4336              theScaleFact = [theScaleFact]
4337         if ( isinstance( theScaleFact, int )):
4338              theScaleFact = [ float(theScaleFact)]
4339
4340         self.mesh.SetParameters(thePoint.parameters)
4341
4342         if Copy and MakeGroups:
4343             return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4344         self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4345         return []
4346
4347     ## Creates a new mesh from the translated object
4348     #  @param theObject - the object to translate (mesh, submesh, or group)
4349     #  @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4350     #  @param theScaleFact - list of 1-3 scale factors for axises
4351     #  @param MakeGroups - forces the generation of new groups from existing ones
4352     #  @param NewMeshName - the name of the newly created mesh
4353     #  @return instance of Mesh class
4354     def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4355         unRegister = genObjUnRegister()
4356         if (isinstance(theObject, Mesh)):
4357             theObject = theObject.GetMesh()
4358         if ( isinstance( theObject, list )):
4359             theObject = self.GetIDSource(theObject,SMESH.ALL)
4360             unRegister.set( theObject )
4361         if ( isinstance( thePoint, list )):
4362             thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4363         if ( isinstance( theScaleFact, float )):
4364              theScaleFact = [theScaleFact]
4365         if ( isinstance( theScaleFact, int )):
4366              theScaleFact = [ float(theScaleFact)]
4367
4368         self.mesh.SetParameters(thePoint.parameters)
4369         mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4370                                          MakeGroups, NewMeshName)
4371         return Mesh( self.smeshpyD, self.geompyD, mesh )
4372
4373
4374
4375     ## Rotates the elements
4376     #  @param IDsOfElements list of elements ids
4377     #  @param Axis the axis of rotation (AxisStruct or geom line)
4378     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4379     #  @param Copy allows copying the rotated elements
4380     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4381     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4382     #  @ingroup l2_modif_trsf
4383     def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4384         if IDsOfElements == []:
4385             IDsOfElements = self.GetElementsId()
4386         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4387             Axis = self.smeshpyD.GetAxisStruct(Axis)
4388         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4389         Parameters = Axis.parameters + var_separator + Parameters
4390         self.mesh.SetParameters(Parameters)
4391         if Copy and MakeGroups:
4392             return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4393         self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4394         return []
4395
4396     ## Creates a new mesh of rotated elements
4397     #  @param IDsOfElements list of element ids
4398     #  @param Axis the axis of rotation (AxisStruct or geom line)
4399     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4400     #  @param MakeGroups forces the generation of new groups from existing ones
4401     #  @param NewMeshName the name of the newly created mesh
4402     #  @return instance of Mesh class
4403     #  @ingroup l2_modif_trsf
4404     def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4405         if IDsOfElements == []:
4406             IDsOfElements = self.GetElementsId()
4407         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4408             Axis = self.smeshpyD.GetAxisStruct(Axis)
4409         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4410         Parameters = Axis.parameters + var_separator + Parameters
4411         self.mesh.SetParameters(Parameters)
4412         mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4413                                           MakeGroups, NewMeshName)
4414         return Mesh( self.smeshpyD, self.geompyD, mesh )
4415
4416     ## Rotates the object
4417     #  @param theObject the object to rotate( mesh, submesh, or group)
4418     #  @param Axis the axis of rotation (AxisStruct or geom line)
4419     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4420     #  @param Copy allows copying the rotated elements
4421     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4422     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4423     #  @ingroup l2_modif_trsf
4424     def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4425         if (isinstance(theObject, Mesh)):
4426             theObject = theObject.GetMesh()
4427         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4428             Axis = self.smeshpyD.GetAxisStruct(Axis)
4429         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4430         Parameters = Axis.parameters + ":" + Parameters
4431         self.mesh.SetParameters(Parameters)
4432         if Copy and MakeGroups:
4433             return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4434         self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4435         return []
4436
4437     ## Creates a new mesh from the rotated object
4438     #  @param theObject the object to rotate (mesh, submesh, or group)
4439     #  @param Axis the axis of rotation (AxisStruct or geom line)
4440     #  @param AngleInRadians the angle of rotation (in radians)  or a name of variable which defines angle in degrees
4441     #  @param MakeGroups forces the generation of new groups from existing ones
4442     #  @param NewMeshName the name of the newly created mesh
4443     #  @return instance of Mesh class
4444     #  @ingroup l2_modif_trsf
4445     def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4446         if (isinstance( theObject, Mesh )):
4447             theObject = theObject.GetMesh()
4448         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4449             Axis = self.smeshpyD.GetAxisStruct(Axis)
4450         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4451         Parameters = Axis.parameters + ":" + Parameters
4452         mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4453                                                        MakeGroups, NewMeshName)
4454         self.mesh.SetParameters(Parameters)
4455         return Mesh( self.smeshpyD, self.geompyD, mesh )
4456
4457     ## Finds groups of adjacent nodes within Tolerance.
4458     #  @param Tolerance the value of tolerance
4459     #  @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4460     #         corner and medium nodes in separate groups thus preventing
4461     #         their further merge.
4462     #  @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4463     #  @ingroup l2_modif_trsf
4464     def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
4465         return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
4466
4467     ## Finds groups of ajacent nodes within Tolerance.
4468     #  @param Tolerance the value of tolerance
4469     #  @param SubMeshOrGroup SubMesh or Group
4470     #  @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4471     #  @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4472     #         corner and medium nodes in separate groups thus preventing
4473     #         their further merge.
4474     #  @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4475     #  @ingroup l2_modif_trsf
4476     def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
4477                                    exceptNodes=[], SeparateCornerAndMediumNodes=False):
4478         unRegister = genObjUnRegister()
4479         if (isinstance( SubMeshOrGroup, Mesh )):
4480             SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4481         if not isinstance( exceptNodes, list ):
4482             exceptNodes = [ exceptNodes ]
4483         if exceptNodes and isinstance( exceptNodes[0], int ):
4484             exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
4485             unRegister.set( exceptNodes )
4486         return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
4487                                                         exceptNodes, SeparateCornerAndMediumNodes)
4488
4489     ## Merges nodes
4490     #  @param GroupsOfNodes a list of groups of nodes IDs for merging
4491     #         (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
4492     #         by nodes 1 and 25 correspondingly in all elements and groups
4493     #  @param NodesToKeep nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
4494     #         If @a NodesToKeep does not include a node to keep for some group to merge,
4495     #         then the first node in the group is kept.
4496     #  @ingroup l2_modif_trsf
4497     def MergeNodes (self, GroupsOfNodes, NodesToKeep=[]):
4498         # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
4499         self.editor.MergeNodes(GroupsOfNodes,NodesToKeep)
4500
4501     ## Finds the elements built on the same nodes.
4502     #  @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4503     #  @return the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
4504     #  @ingroup l2_modif_trsf
4505     def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4506         if not MeshOrSubMeshOrGroup:
4507             MeshOrSubMeshOrGroup=self.mesh
4508         elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4509             MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4510         return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4511
4512     ## Merges elements in each given group.
4513     #  @param GroupsOfElementsID a list of groups of elements IDs for merging
4514     #        (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
4515     #        replaced by elements 1 and 25 in all groups)
4516     #  @ingroup l2_modif_trsf
4517     def MergeElements(self, GroupsOfElementsID):
4518         self.editor.MergeElements(GroupsOfElementsID)
4519
4520     ## Leaves one element and removes all other elements built on the same nodes.
4521     #  @ingroup l2_modif_trsf
4522     def MergeEqualElements(self):
4523         self.editor.MergeEqualElements()
4524
4525     ## Returns groups of FreeBorder's coincident within the given tolerance.
4526     #  @param tolerance the tolerance. If the tolerance <= 0.0 then one tenth of an average
4527     #         size of elements adjacent to free borders being compared is used.
4528     #  @return SMESH.CoincidentFreeBorders structure
4529     #  @ingroup l2_modif_trsf
4530     def FindCoincidentFreeBorders (self, tolerance=0.):
4531         return self.editor.FindCoincidentFreeBorders( tolerance )
4532         
4533     ## Sew FreeBorder's of each group
4534     #  @param freeBorders either a SMESH.CoincidentFreeBorders structure or a list of lists
4535     #         where each enclosed list contains node IDs of a group of coincident free
4536     #         borders such that each consequent triple of IDs within a group describes
4537     #         a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
4538     #         last node of a border.
4539     #         For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
4540     #         groups of coincident free borders, each group including two borders.
4541     #  @param createPolygons if @c True faces adjacent to free borders are converted to
4542     #         polygons if a node of opposite border falls on a face edge, else such
4543     #         faces are split into several ones.
4544     #  @param createPolyhedra if @c True volumes adjacent to free borders are converted to
4545     #         polyhedra if a node of opposite border falls on a volume edge, else such
4546     #         volumes, if any, remain intact and the mesh becomes non-conformal.
4547     #  @return a number of successfully sewed groups
4548     #  @ingroup l2_modif_trsf
4549     def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
4550         if freeBorders and isinstance( freeBorders, list ):
4551             # construct SMESH.CoincidentFreeBorders
4552             if isinstance( freeBorders[0], int ):
4553                 freeBorders = [freeBorders]
4554             borders = []
4555             coincidentGroups = []
4556             for nodeList in freeBorders:
4557                 if not nodeList or len( nodeList ) % 3:
4558                     raise ValueError, "Wrong number of nodes in this group: %s" % nodeList
4559                 group = []
4560                 while nodeList:
4561                     group.append  ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
4562                     borders.append( SMESH.FreeBorder( nodeList[:3] ))
4563                     nodeList = nodeList[3:]
4564                     pass
4565                 coincidentGroups.append( group )
4566                 pass
4567             freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
4568
4569         return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
4570
4571     ## Sews free borders
4572     #  @return SMESH::Sew_Error
4573     #  @ingroup l2_modif_trsf
4574     def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4575                         FirstNodeID2, SecondNodeID2, LastNodeID2,
4576                         CreatePolygons, CreatePolyedrs):
4577         return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4578                                           FirstNodeID2, SecondNodeID2, LastNodeID2,
4579                                           CreatePolygons, CreatePolyedrs)
4580
4581     ## Sews conform free borders
4582     #  @return SMESH::Sew_Error
4583     #  @ingroup l2_modif_trsf
4584     def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4585                                FirstNodeID2, SecondNodeID2):
4586         return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4587                                                  FirstNodeID2, SecondNodeID2)
4588
4589     ## Sews border to side
4590     #  @return SMESH::Sew_Error
4591     #  @ingroup l2_modif_trsf
4592     def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4593                          FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4594         return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4595                                            FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4596
4597     ## Sews two sides of a mesh. The nodes belonging to Side1 are
4598     #  merged with the nodes of elements of Side2.
4599     #  The number of elements in theSide1 and in theSide2 must be
4600     #  equal and they should have similar nodal connectivity.
4601     #  The nodes to merge should belong to side borders and
4602     #  the first node should be linked to the second.
4603     #  @return SMESH::Sew_Error
4604     #  @ingroup l2_modif_trsf
4605     def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4606                          NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4607                          NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4608         return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4609                                            NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4610                                            NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4611
4612     ## Sets new nodes for the given element.
4613     #  @param ide the element id
4614     #  @param newIDs nodes ids
4615     #  @return If the number of nodes does not correspond to the type of element - returns false
4616     #  @ingroup l2_modif_edit
4617     def ChangeElemNodes(self, ide, newIDs):
4618         return self.editor.ChangeElemNodes(ide, newIDs)
4619
4620     ## If during the last operation of MeshEditor some nodes were
4621     #  created, this method returns the list of their IDs, \n
4622     #  if new nodes were not created - returns empty list
4623     #  @return the list of integer values (can be empty)
4624     #  @ingroup l1_auxiliary
4625     def GetLastCreatedNodes(self):
4626         return self.editor.GetLastCreatedNodes()
4627
4628     ## If during the last operation of MeshEditor some elements were
4629     #  created this method returns the list of their IDs, \n
4630     #  if new elements were not created - returns empty list
4631     #  @return the list of integer values (can be empty)
4632     #  @ingroup l1_auxiliary
4633     def GetLastCreatedElems(self):
4634         return self.editor.GetLastCreatedElems()
4635
4636     ## Clears sequences of nodes and elements created by mesh edition oparations
4637     #  @ingroup l1_auxiliary
4638     def ClearLastCreated(self):
4639         self.editor.ClearLastCreated()
4640
4641     ## Creates duplicates of given elements, i.e. creates new elements based on the 
4642     #  same nodes as the given ones.
4643     #  @param theElements - container of elements to duplicate. It can be a Mesh,
4644     #         sub-mesh, group, filter or a list of element IDs. If \a theElements is
4645     #         a Mesh, elements of highest dimension are duplicated
4646     #  @param theGroupName - a name of group to contain the generated elements.
4647     #                    If a group with such a name already exists, the new elements
4648     #                    are added to the existng group, else a new group is created.
4649     #                    If \a theGroupName is empty, new elements are not added 
4650     #                    in any group.
4651     # @return a group where the new elements are added. None if theGroupName == "".
4652     #  @ingroup l2_modif_edit
4653     def DoubleElements(self, theElements, theGroupName=""):
4654         unRegister = genObjUnRegister()
4655         if isinstance( theElements, Mesh ):
4656             theElements = theElements.mesh
4657         elif isinstance( theElements, list ):
4658             theElements = self.GetIDSource( theElements, SMESH.ALL )
4659             unRegister.set( theElements )
4660         return self.editor.DoubleElements(theElements, theGroupName)
4661
4662     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4663     #  @param theNodes identifiers of nodes to be doubled
4664     #  @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4665     #         nodes. If list of element identifiers is empty then nodes are doubled but
4666     #         they not assigned to elements
4667     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4668     #  @ingroup l2_modif_edit
4669     def DoubleNodes(self, theNodes, theModifiedElems):
4670         return self.editor.DoubleNodes(theNodes, theModifiedElems)
4671
4672     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4673     #  This method provided for convenience works as DoubleNodes() described above.
4674     #  @param theNodeId identifiers of node to be doubled
4675     #  @param theModifiedElems identifiers of elements to be updated
4676     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4677     #  @ingroup l2_modif_edit
4678     def DoubleNode(self, theNodeId, theModifiedElems):
4679         return self.editor.DoubleNode(theNodeId, theModifiedElems)
4680
4681     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4682     #  This method provided for convenience works as DoubleNodes() described above.
4683     #  @param theNodes group of nodes to be doubled
4684     #  @param theModifiedElems group of elements to be updated.
4685     #  @param theMakeGroup forces the generation of a group containing new nodes.
4686     #  @return TRUE or a created group if operation has been completed successfully,
4687     #          FALSE or None otherwise
4688     #  @ingroup l2_modif_edit
4689     def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4690         if theMakeGroup:
4691             return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4692         return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4693
4694     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4695     #  This method provided for convenience works as DoubleNodes() described above.
4696     #  @param theNodes list of groups of nodes to be doubled
4697     #  @param theModifiedElems list of groups of elements to be updated.
4698     #  @param theMakeGroup forces the generation of a group containing new nodes.
4699     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4700     #  @ingroup l2_modif_edit
4701     def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4702         if theMakeGroup:
4703             return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4704         return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4705
4706     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4707     #  @param theElems - the list of elements (edges or faces) to be replicated
4708     #         The nodes for duplication could be found from these elements
4709     #  @param theNodesNot - list of nodes to NOT replicate
4710     #  @param theAffectedElems - the list of elements (cells and edges) to which the
4711     #         replicated nodes should be associated to.
4712     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4713     #  @ingroup l2_modif_edit
4714     def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4715         return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4716
4717     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4718     #  @param theElems - the list of elements (edges or faces) to be replicated
4719     #         The nodes for duplication could be found from these elements
4720     #  @param theNodesNot - list of nodes to NOT replicate
4721     #  @param theShape - shape to detect affected elements (element which geometric center
4722     #         located on or inside shape).
4723     #         The replicated nodes should be associated to affected elements.
4724     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4725     #  @ingroup l2_modif_edit
4726     def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4727         return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4728
4729     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4730     #  This method provided for convenience works as DoubleNodes() described above.
4731     #  @param theElems - group of of elements (edges or faces) to be replicated
4732     #  @param theNodesNot - group of nodes not to replicated
4733     #  @param theAffectedElems - group of elements to which the replicated nodes
4734     #         should be associated to.
4735     #  @param theMakeGroup forces the generation of a group containing new elements.
4736     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
4737     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
4738     #          FALSE or None otherwise
4739     #  @ingroup l2_modif_edit
4740     def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4741                              theMakeGroup=False, theMakeNodeGroup=False):
4742         if theMakeGroup or theMakeNodeGroup:
4743             twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4744                                                             theAffectedElems,
4745                                                             theMakeGroup, theMakeNodeGroup)
4746             if theMakeGroup and theMakeNodeGroup:
4747                 return twoGroups
4748             else:
4749                 return twoGroups[ int(theMakeNodeGroup) ]
4750         return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4751
4752     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4753     #  This method provided for convenience works as DoubleNodes() described above.
4754     #  @param theElems - group of of elements (edges or faces) to be replicated
4755     #  @param theNodesNot - group of nodes not to replicated
4756     #  @param theShape - shape to detect affected elements (element which geometric center
4757     #         located on or inside shape).
4758     #         The replicated nodes should be associated to affected elements.
4759     #  @ingroup l2_modif_edit
4760     def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4761         return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4762
4763     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4764     #  This method provided for convenience works as DoubleNodes() described above.
4765     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4766     #  @param theNodesNot - list of groups of nodes not to replicated
4767     #  @param theAffectedElems - group of elements to which the replicated nodes
4768     #         should be associated to.
4769     #  @param theMakeGroup forces the generation of a group containing new elements.
4770     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
4771     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
4772     #          FALSE or None otherwise
4773     #  @ingroup l2_modif_edit
4774     def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4775                              theMakeGroup=False, theMakeNodeGroup=False):
4776         if theMakeGroup or theMakeNodeGroup:
4777             twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4778                                                              theAffectedElems,
4779                                                              theMakeGroup, theMakeNodeGroup)
4780             if theMakeGroup and theMakeNodeGroup:
4781                 return twoGroups
4782             else:
4783                 return twoGroups[ int(theMakeNodeGroup) ]
4784         return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4785
4786     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4787     #  This method provided for convenience works as DoubleNodes() described above.
4788     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4789     #  @param theNodesNot - list of groups of nodes not to replicated
4790     #  @param theShape - shape to detect affected elements (element which geometric center
4791     #         located on or inside shape).
4792     #         The replicated nodes should be associated to affected elements.
4793     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4794     #  @ingroup l2_modif_edit
4795     def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4796         return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4797
4798     ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4799     #  This method is the first step of DoubleNodeElemGroupsInRegion.
4800     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4801     #  @param theNodesNot - list of groups of nodes not to replicated
4802     #  @param theShape - shape to detect affected elements (element which geometric center
4803     #         located on or inside shape).
4804     #         The replicated nodes should be associated to affected elements.
4805     #  @return groups of affected elements
4806     #  @ingroup l2_modif_edit
4807     def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4808         return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4809
4810     ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4811     # The list of groups must describe a partition of the mesh volumes.
4812     # The nodes of the internal faces at the boundaries of the groups are doubled.
4813     # In option, the internal faces are replaced by flat elements.
4814     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4815     # @param theDomains - list of groups of volumes
4816     # @param createJointElems - if TRUE, create the elements
4817     # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4818     #        the boundary between \a theDomains and the rest mesh
4819     # @return TRUE if operation has been completed successfully, FALSE otherwise
4820     def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4821        return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4822
4823     ## Double nodes on some external faces and create flat elements.
4824     # Flat elements are mainly used by some types of mechanic calculations.
4825     #
4826     # Each group of the list must be constituted of faces.
4827     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4828     # @param theGroupsOfFaces - list of groups of faces
4829     # @return TRUE if operation has been completed successfully, FALSE otherwise
4830     def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4831         return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4832     
4833     ## identify all the elements around a geom shape, get the faces delimiting the hole
4834     #
4835     def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4836         return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4837
4838     def _getFunctor(self, funcType ):
4839         fn = self.functors[ funcType._v ]
4840         if not fn:
4841             fn = self.smeshpyD.GetFunctor(funcType)
4842             fn.SetMesh(self.mesh)
4843             self.functors[ funcType._v ] = fn
4844         return fn
4845
4846     ## Returns value of a functor for a given element
4847     #  @param funcType an item of SMESH.FunctorType enum
4848     #         Type "SMESH.FunctorType._items" in the Python Console to see all items.
4849     #  @param elemId element or node ID
4850     #  @param isElem @a elemId is ID of element or node
4851     #  @return the functor value or zero in case of invalid arguments
4852     def FunctorValue(self, funcType, elemId, isElem=True):
4853         fn = self._getFunctor( funcType )
4854         if fn.GetElementType() == self.GetElementType(elemId, isElem):
4855             val = fn.GetValue(elemId)
4856         else:
4857             val = 0
4858         return val
4859
4860     ## Get length of 1D element or sum of lengths of all 1D mesh elements
4861     #  @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4862     #  @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4863     #  @ingroup l1_measurements
4864     def GetLength(self, elemId=None):
4865         length = 0
4866         if elemId == None:
4867             length = self.smeshpyD.GetLength(self)
4868         else:
4869             length = self.FunctorValue(SMESH.FT_Length, elemId)
4870         return length
4871
4872     ## Get area of 2D element or sum of areas of all 2D mesh elements
4873     #  @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4874     #  @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4875     #  @ingroup l1_measurements
4876     def GetArea(self, elemId=None):
4877         area = 0
4878         if elemId == None:
4879             area = self.smeshpyD.GetArea(self)
4880         else:
4881             area = self.FunctorValue(SMESH.FT_Area, elemId)
4882         return area
4883
4884     ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4885     #  @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4886     #  @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4887     #  @ingroup l1_measurements
4888     def GetVolume(self, elemId=None):
4889         volume = 0
4890         if elemId == None:
4891             volume = self.smeshpyD.GetVolume(self)
4892         else:
4893             volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
4894         return volume
4895
4896     ## Get maximum element length.
4897     #  @param elemId mesh element ID
4898     #  @return element's maximum length value
4899     #  @ingroup l1_measurements
4900     def GetMaxElementLength(self, elemId):
4901         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4902             ftype = SMESH.FT_MaxElementLength3D
4903         else:
4904             ftype = SMESH.FT_MaxElementLength2D
4905         return self.FunctorValue(ftype, elemId)
4906
4907     ## Get aspect ratio of 2D or 3D element.
4908     #  @param elemId mesh element ID
4909     #  @return element's aspect ratio value
4910     #  @ingroup l1_measurements
4911     def GetAspectRatio(self, elemId):
4912         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4913             ftype = SMESH.FT_AspectRatio3D
4914         else:
4915             ftype = SMESH.FT_AspectRatio
4916         return self.FunctorValue(ftype, elemId)
4917
4918     ## Get warping angle of 2D element.
4919     #  @param elemId mesh element ID
4920     #  @return element's warping angle value
4921     #  @ingroup l1_measurements
4922     def GetWarping(self, elemId):
4923         return self.FunctorValue(SMESH.FT_Warping, elemId)
4924
4925     ## Get minimum angle of 2D element.
4926     #  @param elemId mesh element ID
4927     #  @return element's minimum angle value
4928     #  @ingroup l1_measurements
4929     def GetMinimumAngle(self, elemId):
4930         return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
4931
4932     ## Get taper of 2D element.
4933     #  @param elemId mesh element ID
4934     #  @return element's taper value
4935     #  @ingroup l1_measurements
4936     def GetTaper(self, elemId):
4937         return self.FunctorValue(SMESH.FT_Taper, elemId)
4938
4939     ## Get skew of 2D element.
4940     #  @param elemId mesh element ID
4941     #  @return element's skew value
4942     #  @ingroup l1_measurements
4943     def GetSkew(self, elemId):
4944         return self.FunctorValue(SMESH.FT_Skew, elemId)
4945
4946     ## Return minimal and maximal value of a given functor.
4947     #  @param funType a functor type, an item of SMESH.FunctorType enum
4948     #         (one of SMESH.FunctorType._items)
4949     #  @param meshPart a part of mesh (group, sub-mesh) to treat
4950     #  @return tuple (min,max)
4951     #  @ingroup l1_measurements
4952     def GetMinMax(self, funType, meshPart=None):
4953         unRegister = genObjUnRegister()
4954         if isinstance( meshPart, list ):
4955             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
4956             unRegister.set( meshPart )
4957         if isinstance( meshPart, Mesh ):
4958             meshPart = meshPart.mesh
4959         fun = self._getFunctor( funType )
4960         if fun:
4961             if meshPart:
4962                 if hasattr( meshPart, "SetMesh" ):
4963                     meshPart.SetMesh( self.mesh ) # set mesh to filter
4964                 hist = fun.GetLocalHistogram( 1, False, meshPart )
4965             else:
4966                 hist = fun.GetHistogram( 1, False )
4967             if hist:
4968                 return hist[0].min, hist[0].max
4969         return None
4970
4971     pass # end of Mesh class
4972
4973
4974 ## class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
4975 #  with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
4976 #
4977 class meshProxy(SMESH._objref_SMESH_Mesh):
4978     def __init__(self):
4979         SMESH._objref_SMESH_Mesh.__init__(self)
4980     def __deepcopy__(self, memo=None):
4981         new = self.__class__()
4982         return new
4983     def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
4984         if len( args ) == 3:
4985             args += SMESH.ALL_NODES, True
4986         return SMESH._objref_SMESH_Mesh.CreateDimGroup( self, *args )
4987     pass
4988 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
4989
4990 ## class used to compensate change of CORBA API of SMESH_MeshEditor for backward compatibility
4991 #  with old dump scripts which call SMESH_MeshEditor directly and not via smeshBuilder.Mesh
4992 #
4993 class meshEditor(SMESH._objref_SMESH_MeshEditor):
4994     def __init__(self):
4995         SMESH._objref_SMESH_MeshEditor.__init__(self)
4996         self.mesh = None
4997     def __getattr__(self, name ): # method called if an attribute not found
4998         if not self.mesh:         # look for name() method in Mesh class
4999             self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
5000         if hasattr( self.mesh, name ):
5001             return getattr( self.mesh, name )
5002         if name == "ExtrusionAlongPathObjX":
5003             return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
5004         print "meshEditor: attribute '%s' NOT FOUND" % name
5005         return None
5006     def __deepcopy__(self, memo=None):
5007         new = self.__class__()
5008         return new
5009     def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
5010         if len( args ) == 1: args += False,
5011         return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
5012     def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
5013         if len( args ) == 2: args += False,
5014         return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
5015     def MergeNodes(self,*args): # a 2nd arg added (NodesToKeep)
5016         if len( args ) == 1:
5017             return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [] )
5018         NodesToKeep = args[1]
5019         unRegister  = genObjUnRegister()
5020         if NodesToKeep:
5021             if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
5022                 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
5023             if not isinstance( NodesToKeep, list ):
5024                 NodesToKeep = [ NodesToKeep ]
5025         return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep )
5026     pass
5027 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
5028
5029 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
5030 #
5031 class Pattern(SMESH._objref_SMESH_Pattern):
5032
5033     def LoadFromFile(self, patternTextOrFile ):
5034         text = patternTextOrFile
5035         if os.path.exists( text ):
5036             text = open( patternTextOrFile ).read()
5037             pass
5038         return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
5039
5040     def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
5041         decrFun = lambda i: i-1
5042         theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
5043         theMesh.SetParameters(Parameters)
5044         return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
5045
5046     def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
5047         decrFun = lambda i: i-1
5048         theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
5049         theMesh.SetParameters(Parameters)
5050         return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
5051
5052     def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
5053         if isinstance( mesh, Mesh ):
5054             mesh = mesh.GetMesh()
5055         return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
5056
5057 # Registering the new proxy for Pattern
5058 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
5059
5060 ## Private class used to bind methods creating algorithms to the class Mesh
5061 #
5062 class algoCreator:
5063     def __init__(self):
5064         self.mesh = None
5065         self.defaultAlgoType = ""
5066         self.algoTypeToClass = {}
5067
5068     # Stores a python class of algorithm
5069     def add(self, algoClass):
5070         if type( algoClass ).__name__ == 'classobj' and \
5071            hasattr( algoClass, "algoType"):
5072             self.algoTypeToClass[ algoClass.algoType ] = algoClass
5073             if not self.defaultAlgoType and \
5074                hasattr( algoClass, "isDefault") and algoClass.isDefault:
5075                 self.defaultAlgoType = algoClass.algoType
5076             #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
5077
5078     # creates a copy of self and assign mesh to the copy
5079     def copy(self, mesh):
5080         other = algoCreator()
5081         other.defaultAlgoType = self.defaultAlgoType
5082         other.algoTypeToClass  = self.algoTypeToClass
5083         other.mesh = mesh
5084         return other
5085
5086     # creates an instance of algorithm
5087     def __call__(self,algo="",geom=0,*args):
5088         algoType = self.defaultAlgoType
5089         for arg in args + (algo,geom):
5090             if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
5091                 geom = arg
5092             if isinstance( arg, str ) and arg:
5093                 algoType = arg
5094         if not algoType and self.algoTypeToClass:
5095             algoType = self.algoTypeToClass.keys()[0]
5096         if self.algoTypeToClass.has_key( algoType ):
5097             #print "Create algo",algoType
5098             return self.algoTypeToClass[ algoType ]( self.mesh, geom )
5099         raise RuntimeError, "No class found for algo type %s" % algoType
5100         return None
5101
5102 # Private class used to substitute and store variable parameters of hypotheses.
5103 #
5104 class hypMethodWrapper:
5105     def __init__(self, hyp, method):
5106         self.hyp    = hyp
5107         self.method = method
5108         #print "REBIND:", method.__name__
5109         return
5110
5111     # call a method of hypothesis with calling SetVarParameter() before
5112     def __call__(self,*args):
5113         if not args:
5114             return self.method( self.hyp, *args ) # hypothesis method with no args
5115
5116         #print "MethWrapper.__call__",self.method.__name__, args
5117         try:
5118             parsed = ParseParameters(*args)     # replace variables with their values
5119             self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
5120             result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
5121         except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
5122             # maybe there is a replaced string arg which is not variable
5123             result = self.method( self.hyp, *args )
5124         except ValueError, detail: # raised by ParseParameters()
5125             try:
5126                 result = self.method( self.hyp, *args )
5127             except omniORB.CORBA.BAD_PARAM:
5128                 raise ValueError, detail # wrong variable name
5129
5130         return result
5131     pass
5132
5133 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
5134 class genObjUnRegister:
5135
5136     def __init__(self, genObj=None):
5137         self.genObjList = []
5138         self.set( genObj )
5139         return
5140
5141     def set(self, genObj):
5142         "Store one or a list of of SALOME.GenericObj'es"
5143         if isinstance( genObj, list ):
5144             self.genObjList.extend( genObj )
5145         else:
5146             self.genObjList.append( genObj )
5147         return
5148
5149     def __del__(self):
5150         for genObj in self.genObjList:
5151             if genObj and hasattr( genObj, "UnRegister" ):
5152                 genObj.UnRegister()
5153
5154 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
5155     #
5156     #print "pluginName: ", pluginName
5157     pluginBuilderName = pluginName + "Builder"
5158     try:
5159         exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
5160     except Exception, e:
5161         from salome_utils import verbose
5162         if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
5163         continue
5164     exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5165     plugin = eval( pluginBuilderName )
5166     #print "  plugin:" , str(plugin)
5167
5168     # add methods creating algorithms to Mesh
5169     for k in dir( plugin ):
5170         if k[0] == '_': continue
5171         algo = getattr( plugin, k )
5172         #print "             algo:", str(algo)
5173         if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
5174             #print "                     meshMethod:" , str(algo.meshMethod)
5175             if not hasattr( Mesh, algo.meshMethod ):
5176                 setattr( Mesh, algo.meshMethod, algoCreator() )
5177                 pass
5178             getattr( Mesh, algo.meshMethod ).add( algo )
5179             pass
5180         pass
5181     pass
5182 del pluginName