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