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