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