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