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