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