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