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