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