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