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