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