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