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