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